diff --git a/.dockerignore b/.dockerignore index 75ea5de6ca2..664eefdb4ee 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,3 +1,4 @@ +.git/ *.iml out/ *.ipr @@ -13,35 +14,13 @@ generated-sources/* generated-code/* *.swp *.swo - -/target -/generated-files -/nbactions.xml -*.pyc -__pycache__ -samples/server-generator/scalatra/output -samples/server-generator/node/output/node_modules -samples/server-generator/scalatra/target -samples/server-generator/scalatra/output/.history -samples/client/petstore/qt5cpp/PetStore/moc_* -samples/client/petstore/qt5cpp/PetStore/*.o -samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata -samples/client/petstore/qt5cpp/build-* -samples/client/petstore/qt5cpp/PetStore/PetStore -samples/client/petstore/qt5cpp/PetStore/Makefile -samples/client/petstore/java/hello.txt -samples/client/petstore/android/default/hello.txt -samples/client/petstore/objc/Build -samples/client/petstore/objc/Pods -samples/server/petstore/nodejs/node_modules -target -.idea -.lib -atlassian-ide-plugin.xml +*.bak +project/ +samples/* +target/ +.idea/ +.lib/ .DS_Store -samples/client/petstore/php/SwaggerClient-php/composer.lock -samples/client/petstore/php/SwaggerClient-php/vendor/ - -samples/client/petstore/silex/SwaggerServer/composer.lock -samples/client/petstore/silex/SwaggerServer/venodr/ +# Not needed in a linux container +bin/windows/* diff --git a/.travis.yml b/.travis.yml index 1a62cea3161..e0290b10205 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,6 +24,12 @@ before_install: - docker pull swaggerapi/petstore - docker run -d -e SWAGGER_HOST=http://petstore.swagger.io -e SWAGGER_BASE_PATH=/v2 -p 80:8080 swaggerapi/petstore - docker ps -a + # Add bats test framework and cURL for Bash script integration tests + - sudo add-apt-repository ppa:duggan/bats --yes + - sudo apt-get update -qq + - sudo apt-get install -qq bats + - sudo apt-get install -qq curl + # show host table to confirm petstore.swagger.io is mapped to localhost - cat /etc/hosts @@ -34,7 +40,15 @@ install: - export PATH="${TRAVIS_BUILD_DIR}/Godeps/_workspace/bin:$PATH" script: + # fail fast + - set -e + # fail if templates/generators contain carriage return '\r' + - /bin/bash ./bin/utils/detect_carriage_return.sh + # fail if generators contain tab '\t' + - /bin/bash ./bin/utils/detect_tab_in_java_class.sh + # run integration tests defined in maven pom.xml - mvn verify -Psamples + # docker test - if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME; fi env: diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b187c39192c..e0b6576bf95 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -30,6 +30,7 @@ For a list of variables available in the template, please refer to this [page](h ### Style guide Code change should conform to the programming style guide of the respective languages: - Android: https://source.android.com/source/code-style.html +- Bash: https://github.com/bahamas10/bash-style-guide - C#: https://msdn.microsoft.com/en-us/library/vstudio/ff926074.aspx - C++: https://google.github.io/styleguide/cppguide.html - Clojure: https://github.com/bbatsov/clojure-style-guide @@ -75,3 +76,5 @@ To start the CI tests, you can run `mvn verify -Psamples` (assuming you've all t - Document the fix in the code to make the code more readable - Make sure test cases passed after the change (one way is to leverage https://travis-ci.org/ to run the CI tests) - File a PR with meaningful title, description and commit messages. A good example is [PR-3306](https://github.com/swagger-api/swagger-codegen/pull/3306) +- Recommended git settings + - `git config --global core.autocrlf input` to tell Git convert CRLF to LF on commit but not the other way around diff --git a/Dockerfile b/Dockerfile index 0a3d093290e..ec291fef4af 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,13 +1,22 @@ -FROM maven:3.3-jdk-7 +FROM jimschubert/8-jdk-alpine-mvn:1.0 -WORKDIR /src -VOLUME /src -VOLUME /root/.m2/repository +ENV GEN_DIR /opt/swagger-codegen -ADD . /opt/swagger-codegen +RUN set -x && \ + apk add --no-cache bash -RUN cd /opt/swagger-codegen && mvn package +RUN mkdir /opt -ENTRYPOINT ["java", "-jar", "/opt/swagger-codegen/modules/swagger-codegen-cli/target/swagger-codegen-cli.jar"] +ADD . ${GEN_DIR} -CMD ["help"] +VOLUME ${MAVEN_HOME}/.m2/repository + +WORKDIR ${GEN_DIR} + +RUN mvn -am -pl "modules/swagger-codegen-cli" package + +COPY docker-entrypoint.sh /usr/local/bin/ + +ENTRYPOINT ["docker-entrypoint.sh"] + +CMD ["build"] diff --git a/README.md b/README.md index 3024c333569..a9a4b63a596 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,8 @@ ## Overview This is the swagger codegen project, which allows generation of API client libraries (SDK generation), server stubs and documentation automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification). Currently, the following languages/frameworks are supported: -- **API clients**: **ActionScript**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, Node) -- **Server stubs**: **C#** (ASP.NET Core, NancyFx), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), **PHP** (Lumen, Slim, Silex), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** (Scalatra) +- **API clients**: **ActionScript**, **Bash**, **C#** (.net 2.0, 4.0 or later), **C++** (cpprest, Qt5, Tizen), **Clojure**, **Dart**, **Elixir**, **Go**, **Groovy**, **Haskell**, **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign), **Node.js** (ES5, ES6, AngularJS with Google Closure Compiler annotations) **Objective-C**, **Perl**, **PHP**, **Python**, **Ruby**, **Scala**, **Swift** (2.x, 3.x), **Typescript** (Angular1.x, Angular2.x, Fetch, Node) +- **Server stubs**: **C#** (ASP.NET Core, NancyFx), **Erlang**, **Go**, **Haskell**, **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, RestEasy), **PHP** (Lumen, Slim, Silex, [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Scala** ([Finch](https://github.com/finagle/finch), Scalatra) - **API documentation generators**: **HTML**, **Confluence Wiki** - **Others**: **JMeter** @@ -110,16 +110,41 @@ After cloning the project, you can build it from source with this command: mvn clean package ``` +### Homebrew + +To install, run `brew install swagger-codegen` + +Here is an example usage: +``` +swagger-codegen generate -i http://petstore.swagger.io/v2/swagger.json -l ruby -o /tmp/test/ +``` + ### Docker -#### Build and run using docker + +#### Development in docker + +You can use `run-in-docker.sh` to do all development. This script maps your local repository to `/gen` +in the docker container. It also maps `~/.m2/repository` to the appropriate container location. + +To execute `mvn package`: ``` git clone https://github.com/swagger-api/swagger-codegen cd swagger-codegen ./run-in-docker.sh mvn package - ``` +``` +Build artifacts are now accessible in your working directory. +Once built, `run-in-docker.sh` will act as an executable for swagger-codegen-cli. To generate code, you'll need to output to a directory under `/gen` (e.g. `/gen/out`). For example: + +``` +./run-in-docker.sh help # Executes 'help' command for swagger-codegen-cli +./run-in-docker.sh langs # Executes 'langs' command for swagger-codegen-cli +./run-in-docker.sh /gen/bin/go-petstore.sh # Builds the Go client +./run-in-docker.sh generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml \ + -l go -o /gen/out/go-petstore -DpackageName=petstore # generates go client, outputs locally to ./out/go-petstore +``` #### Run Docker in Vagrant Prerequisite: install [Vagrant](https://www.vagrantup.com/downloads.html) and [VirtualBox](https://www.virtualbox.org/wiki/Downloads). @@ -132,18 +157,54 @@ cd /vagrant ./run-in-docker.sh mvn package ``` -#### Public Docker image +#### Public Pre-built Docker images - - https://hub.docker.com/r/swaggerapi/swagger-generator/ (official) - - https://hub.docker.com/r/jimschubert/swagger-codegen-cli/ (unofficial) + - https://hub.docker.com/r/swaggerapi/swagger-generator/ (official web service) + - https://hub.docker.com/r/swaggerapi/swagger-codegen-cli/ (official CLI) +======= -### Homebrew -To install, run `brew install swagger-codegen` +##### Swagger Generator Docker Image + +The Swagger Generator image can act as a self-hosted web application and API for generating code. This container can be incorporated into a CI pipeline, and requires at least two HTTP requests and some docker orchestration to access generated code. + +Example usage (note this assumes `jq` is installed for command line processing of JSON): -Here is an example usage: ``` -swagger-codegen generate -i http://petstore.swagger.io/v2/swagger.json -l ruby -o /tmp/test/ +# Start container and save the container id +CID=$(docker run -d swaggerapi/swagger-generator) +# allow for startup +sleep 5 +# Get the IP of the running container +GEN_IP=$(docker inspect --format '{{.NetworkSettings.IPAddress}}' $CID) +# Execute an HTTP request and store the download link +RESULT=$(curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{ + "swaggerUrl": "http://petstore.swagger.io/v2/swagger.json" +}' 'http://localhost:8188/api/gen/clients/javascript' | jq '.link' | tr -d '"') +# Download the generated zip and redirect to a file +curl $RESULT > result.zip +# Shutdown the swagger generator image +docker stop $CID && docker rm $CID ``` + +In the example above, `result.zip` will contain the generated client. + +##### Swagger Codegen Docker Image + +The Swagger Codegen image acts as a standalone executable. It can be used as an alternative to installing via homebrew, or for developers who are unable to install Java or upgrade the installed version. + +To generate code with this image, you'll need to mount a local location as a volume. + +Example: + +``` +docker run --rm -v ${PWD}:/local swagger-api/swagger-codegen generate \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l go \ + -o /local/out/go +``` + +The generated code will be located under `./out/go` in the current directory. + ## Getting Started To generate a PHP client for http://petstore.swagger.io/v2/swagger.json, please run the following @@ -289,6 +350,10 @@ OPTIONS the format of swaggerType=generatedType,swaggerType=generatedType. For example: array=List,map=Map,string=String + --reserved-words-mappings + specifies how a reserved name should be escaped to. Otherwise, the + default _ is used. For example id=identifier + -v, --verbose verbose mode @@ -331,6 +396,10 @@ You would then compile your library in the `output/myLibrary` folder with `mvn p ``` java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar:modules/swagger-codegen-cli/target/swagger-codegen-cli.jar io.swagger.codegen.SwaggerCodegen ``` +For Windows users, you will need to use `;` instead of `:` in the classpath, e.g. +``` +java -cp output/myLibrary/target/myClientCodegen-swagger-codegen-1.0.0.jar;modules/swagger-codegen-cli/target/swagger-codegen-cli.jar io.swagger.codegen.SwaggerCodegen +``` Note the `myClientCodegen` is an option now, and you can use the usual arguments for generating your library: @@ -459,6 +528,7 @@ AndroidClientCodegen.java AspNet5ServerCodegen.java AspNetCoreServerCodegen.java AsyncScalaClientCodegen.java +BashClientCodegen.java CSharpClientCodegen.java ClojureClientCodegen.java CsharpDotNet2ClientCodegen.java @@ -784,25 +854,32 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [goTransverse](http://www.gotransverse.com/api) - [GraphHopper](https://graphhopper.com/) - [Gravitate Solutions](http://gravitatesolutions.com/) +- [Hewlett Packard Enterprise](https://hpe.com) +- [High Technologies Center](http://htc-cs.com) - [IMS Health](http://www.imshealth.com/en/solution-areas/technology-and-applications) - [Intent HQ](http://www.intenthq.com) - [Interactive Intelligence](http://developer.mypurecloud.com/) - [Kabuku](http://www.kabuku.co.jp/en) +- [Kurio](https://kurio.co.id) - [Kuroi](http://kuroiwebdesign.com/) - [Kuary](https://kuary.com/) +- [Kubernetes](https://kubernetes.io/) - [LANDR Audio](https://www.landr.com/) - [Lascaux](http://www.lascaux.it/) - [Leica Geosystems AG](http://leica-geosystems.com) - [LiveAgent](https://www.ladesk.com/) - [LXL Tech](http://lxltech.com) +- [MailMojo](https://mailmojo.no/) - [Mindera](http://mindera.com/) - [Mporium](http://mporium.com/) +- [Neverfail](https://neverfail.com/) - [nViso](http://www.nviso.ch/) - [Okiok](https://www.okiok.com) - [Onedata](http://onedata.org) - [OrderCloud.io](http://ordercloud.io) - [OSDN](https://osdn.jp) - [PagerDuty](https://www.pagerduty.com) +- [PagerTree](https://pagertree.com) - [Pepipost](https://www.pepipost.com) - [Plexxi](http://www.plexxi.com) - [Pixoneye](http://www.pixoneye.com/) @@ -819,9 +896,12 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Saritasa](https://www.saritasa.com/) - [SCOOP Software GmbH](http://www.scoop-software.de) - [Shine Solutions](https://shinesolutions.com/) +- [Simpfony](https://www.simpfony.com/) - [Skurt](http://www.skurt.com) +- [Slamby](https://www.slamby.com/) - [SmartRecruiters](https://www.smartrecruiters.com/) - [snapCX](https://snapcx.io) +- [SPINEN](http://www.spinen.com) - [SRC](https://www.src.si/) - [StyleRecipe](http://stylerecipe.co.jp) - [Svenska Spel AB](https://www.svenskaspel.se/) @@ -832,6 +912,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [VMware](https://vmware.com/) - [W.UP](http://wup.hu/?siteLang=en) - [Wealthfront](https://www.wealthfront.com/) +- [Webever GmbH](https://www.webever.de/) - [WEXO A/S](https://www.wexo.dk/) - [Zalando](https://tech.zalando.com) - [ZEEF.com](https://zeef.com/) @@ -882,15 +963,19 @@ Swagger Codegen core team members are contributors who have been making signific | Python Flask | | | Ruby Sinatra | @wing328 (2016/05/01) | | | Scala Scalatra | | | +| Scala Finch | @jimschubert (2017/01/28) | + ## Template Creator Here is a list of template creators: * API Clients: * Akka-Scala: @cchafer + * Bash: @bkryza * C++ REST: @Danielku15 * C# (.NET 2.0): @who * Clojure: @xhh * Dart: @yissachar + * Elixir: @niku * Groovy: @victorgit * Go: @wing328 * Java (Feign): @davidkiss @@ -922,7 +1007,9 @@ Here is a list of template creators: * JAX-RS CXF (CDI): @nickcmaynard * PHP Lumen: @abcsum * PHP Slim: @jfastnacht + * PHP Zend Expressive (with Path Handler): @Articus * Ruby on Rails 5: @zlx + * Scala Finch: @jimschubert * Documentation * HTML Doc 2: @jhitchcock * Confluence Wiki: @jhitchcock @@ -972,7 +1059,7 @@ When code is generated from this project, it shall be considered **AS IS** and o License ------- -Copyright 2016 SmartBear Software +Copyright 2017 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/bin/bash-petstore.sh b/bin/bash-petstore.sh new file mode 100755 index 00000000000..9988a1157f2 --- /dev/null +++ b/bin/bash-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +args="$@ generate -t modules/swagger-codegen/src/main/resources/bash -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l bash -o samples/client/petstore/bash -c modules/swagger-codegen/src/test/resources/2_0/bash-config.json" + +java $JAVA_OPTS -jar $executable $args diff --git a/bin/elixir-petstore.sh b/bin/elixir-petstore.sh new file mode 100755 index 00000000000..915a02cfc05 --- /dev/null +++ b/bin/elixir-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +args="$@ generate -t modules/swagger-codegen/src/main/resources/elixir -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l elixir -o samples/client/petstore/elixir" + +java $JAVA_OPTS -jar $executable $args diff --git a/bin/finch-petstore-server.sh b/bin/finch-petstore-server.sh new file mode 100755 index 00000000000..9cf4eeb740d --- /dev/null +++ b/bin/finch-petstore-server.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate $@ -t modules/swagger-codegen/src/main/resources/finch -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l finch -o samples/server/petstore/finch" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-cxf-petstore-server-annotated-base-path.sh b/bin/jaxrs-cxf-petstore-server-annotated-base-path.sh new file mode 100755 index 00000000000..eb79a73b25a --- /dev/null +++ b/bin/jaxrs-cxf-petstore-server-annotated-base-path.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf-annotated-base-path -DhideGenerationTimestamp=true,useAnnotatedBasePath=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-cxf-petstore-server-non-spring-application.sh b/bin/jaxrs-cxf-petstore-server-non-spring-application.sh new file mode 100755 index 00000000000..e22a18dea6e --- /dev/null +++ b/bin/jaxrs-cxf-petstore-server-non-spring-application.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf-non-spring-app -DhideGenerationTimestamp=true,generateNonSpringApplication=true" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-cxf-petstore-server.sh b/bin/jaxrs-cxf-petstore-server.sh index 3618e5935a7..4c69eac4452 100755 --- a/bin/jaxrs-cxf-petstore-server.sh +++ b/bin/jaxrs-cxf-petstore-server.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf -DhideGenerationTimestamp=true" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs-cxf -o samples/server/petstore/jaxrs-cxf -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-spec-petstore-server.sh b/bin/jaxrs-spec-petstore-server.sh index 768d20d4748..9482e1a8972 100755 --- a/bin/jaxrs-spec-petstore-server.sh +++ b/bin/jaxrs-spec-petstore-server.sh @@ -26,6 +26,7 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l jaxrs-spec -o samples/server/petstore/jaxrs-spec -DhideGenerationTimestamp=true" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l jaxrs-spec -o samples/server/petstore/jaxrs-spec +-DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/nancyfx-petstore-server.sh b/bin/nancyfx-petstore-server.sh index 20797fa0c1f..2b9b2994cbf 100755 --- a/bin/nancyfx-petstore-server.sh +++ b/bin/nancyfx-petstore-server.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/nancyfx -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nancyfx -o samples/server/petstore/nancyfx" +ags="generate $@ -t modules/swagger-codegen/src/main/resources/nancyfx -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l nancyfx -o samples/server/petstore/nancyfx" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/perl-petstore.sh b/bin/perl-petstore.sh index f3eb5b17bd9..8dd64398708 100755 --- a/bin/perl-petstore.sh +++ b/bin/perl-petstore.sh @@ -27,7 +27,7 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" # complex module name used for testing -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l perl -o samples/client/petstore/perl" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l perl -o samples/client/petstore/perl -DhideGenerationTimestamp=true" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/spring-all-pestore.sh b/bin/spring-all-pestore.sh index de3998266f0..eb69ef2c4ac 100755 --- a/bin/spring-all-pestore.sh +++ b/bin/spring-all-pestore.sh @@ -1,6 +1,8 @@ #!/bin/sh ./bin/spring-cloud-feign-petstore.sh +./bin/spring-delegate.sh +./bin/spring-delegate-j8.sh ./bin/spring-stubs.sh ./bin/spring-mvc-petstore-j8-async-server.sh ./bin/springboot-petstore-server.sh diff --git a/bin/spring-delegate-j8.sh b/bin/spring-delegate-j8.sh new file mode 100755 index 00000000000..5585caa6b8b --- /dev/null +++ b/bin/spring-delegate-j8.sh @@ -0,0 +1,34 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l spring -o samples/server/petstore/springboot-delegate-j8 -DdelegatePattern=true,hideGenerationTimestamp=true,java8=true" + +echo "Removing files and folders under samples/server/petstore/springboot-delegate-j8/src/main" +rm -rf samples/server/petstore/springboot-delegate-j8/src/main +find samples/server/petstore/springboot -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/spring-delegate.sh b/bin/spring-delegate.sh new file mode 100755 index 00000000000..1e523501cd9 --- /dev/null +++ b/bin/spring-delegate.sh @@ -0,0 +1,34 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaSpring -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l spring -o samples/server/petstore/springboot-delegate -DdelegatePattern=true,hideGenerationTimestamp=true" + +echo "Removing files and folders under samples/server/petstore/springboot-delegate/src/main" +rm -rf samples/server/petstore/springboot-delegate/src/main +find samples/server/petstore/springboot -maxdepth 1 -type f ! -name "README.md" -exec rm {} + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/utils/detect_carriage_return.sh b/bin/utils/detect_carriage_return.sh new file mode 100755 index 00000000000..e55c64f64b6 --- /dev/null +++ b/bin/utils/detect_carriage_return.sh @@ -0,0 +1,18 @@ +#!/bin/bash + +# grep for \r in the templates +grep -RUIl $'\r$' modules/swagger-codegen/src/main/resources/* + +if [ $? -ne 1 ]; then + echo "Templates contain carriage return '/r'. Please remove it and try again." + exit 1; +fi + + +# grep for \r in the generators +grep -RUIl $'\r$' modules/swagger-codegen/src/main/java/io/swagger/codegen/*.java + +if [ $? -ne 1 ]; then + echo "Generators contain carriage return '/r'. Please remove it and try again." + exit 1; +fi diff --git a/bin/utils/detect_tab_in_java_class.sh b/bin/utils/detect_tab_in_java_class.sh new file mode 100755 index 00000000000..8d612acd2e0 --- /dev/null +++ b/bin/utils/detect_tab_in_java_class.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +# grep for \t in the generators +grep -RUIl $'\t$' modules/swagger-codegen/src/main/java/io/swagger/codegen/*.java + +if [ $? -ne 1 ]; then + echo "Generators (Java class files) contain tab '/t'. Please remove it and try again." + exit 1; +fi + diff --git a/bin/windows/javascript-petstore-all.bat b/bin/windows/javascript-petstore-all.bat new file mode 100755 index 00000000000..69a36f51b22 --- /dev/null +++ b/bin/windows/javascript-petstore-all.bat @@ -0,0 +1,2 @@ +call .\bin\windows\javascript-petstore.bat +call .\bin\windows\javascript-promise-petstore.bat diff --git a/bin/windows/javascript-petstore.bat b/bin/windows/javascript-petstore.bat index cb7f97bab2c..da6ae295a1c 100755 --- a/bin/windows/javascript-petstore.bat +++ b/bin/windows/javascript-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.json -l javascript -o samples\client\petstore\javascript +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l javascript -o samples\client\petstore\javascript -java %JAVA_OPTS% -jar %executable% %ags% +java -DappName=PetstoreClient %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/javascript-promise-petstore.bat b/bin/windows/javascript-promise-petstore.bat new file mode 100755 index 00000000000..4179e43d1d8 --- /dev/null +++ b/bin/windows/javascript-promise-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l javascript -o samples\client\petstore\javascript-promise --additional-properties usePromises=true + +java -DappName=PetstoreClient %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/windows/ze-ph-petstore.bat b/bin/windows/ze-ph-petstore.bat new file mode 100644 index 00000000000..a25de587857 --- /dev/null +++ b/bin/windows/ze-ph-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l ze-ph -o samples\server\petstore\ze-ph + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/ze-ph-petstore-server.sh b/bin/ze-ph-petstore-server.sh new file mode 100644 index 00000000000..9289ed2f55d --- /dev/null +++ b/bin/ze-ph-petstore-server.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/ze-ph -i modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml -l ze-ph -o samples/server/petstore/ze-ph" + +java $JAVA_OPTS -jar $executable $ags diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh new file mode 100755 index 00000000000..943ae1a2927 --- /dev/null +++ b/docker-entrypoint.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash + +set -euo pipefail + +# GEN_DIR allows to share the entrypoint between Dockerfile and run-in-docker.sh (backward compatible) +GEN_DIR=${GEN_DIR:-/opt/swagger-codegen} +JAVA_OPTS=${JAVA_OPTS:-"-Xmx1024M -DloggerPath=conf/log4j.properties"} + +codegen="${GEN_DIR}/modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +case "$1" in + generate|help|langs|meta|config-help) + # If ${GEN_DIR} has been mapped elsewhere from default, and that location has not been built + if [[ ! -f "${codegen}" ]]; then + (cd ${GEN_DIR} && exec mvn -am -pl "modules/swagger-codegen-cli" package) + fi + command=$1 + shift + exec java ${JAVA_OPTS} -jar ${codegen} ${command} "$@" + ;; + *) # Any other commands, e.g. docker run imagename ls -la or docker run -it imagename /bin/bash + exec "$@" + ;; +esac diff --git a/modules/swagger-codegen-cli/Dockerfile b/modules/swagger-codegen-cli/Dockerfile new file mode 100644 index 00000000000..1068581cbc7 --- /dev/null +++ b/modules/swagger-codegen-cli/Dockerfile @@ -0,0 +1,7 @@ +FROM java:8-jre-alpine + +ADD target/swagger-codegen-cli.jar /opt/swagger-codegen-cli/swagger-codegen-cli.jar + +ENTRYPOINT ["java", "-jar", "/opt/swagger-codegen-cli/swagger-codegen-cli.jar"] + +CMD ["help"] \ No newline at end of file diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java index 8c7beab502b..01303e64559 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java @@ -117,7 +117,14 @@ public class Generate implements Runnable { @Option(name = {"--http-user-agent"}, title = "http user agent", description = CodegenConstants.HTTP_USER_AGENT_DESC) private String httpUserAgent; + + @Option(name = {"--reserved-words-mappings"}, title = "import mappings", + description = "specifies how a reserved name should be escaped to. Otherwise, the default _ is used. For example id=identifier") + private String reservedWordsMappings; + @Option(name = {"--ignore-file-override"}, title = "ignore file override location", description = CodegenConstants.IGNORE_FILE_OVERRIDE_DESC) + private String ignoreFileOverride; + @Override public void run() { @@ -211,13 +218,17 @@ public class Generate implements Runnable { configurator.setHttpUserAgent(httpUserAgent); } + if (isNotEmpty(ignoreFileOverride)) { + configurator.setIgnoreFileOverride(ignoreFileOverride); + } + applySystemPropertiesKvp(systemProperties, configurator); applyInstantiationTypesKvp(instantiationTypes, configurator); applyImportMappingsKvp(importMappings, configurator); applyTypeMappingsKvp(typeMappings, configurator); applyAdditionalPropertiesKvp(additionalProperties, configurator); applyLanguageSpecificPrimitivesCsv(languageSpecificPrimitives, configurator); - + applyReservedWordsMappingsKvp(reservedWordsMappings, configurator); final ClientOptInput clientOptInput = configurator.toClientOptInput(); new DefaultGenerator().opts(clientOptInput).generate(); diff --git a/modules/swagger-codegen-maven-plugin/README.md b/modules/swagger-codegen-maven-plugin/README.md index a7284fdb3c5..64382be8678 100644 --- a/modules/swagger-codegen-maven-plugin/README.md +++ b/modules/swagger-codegen-maven-plugin/README.md @@ -45,9 +45,11 @@ mvn clean compile - `modelPackage` - the package to use for generated model objects/classes - `apiPackage` - the package to use for generated api objects/classes - `invokerPackage` - the package to use for the generated invoker objects -- `modelNamePrefix` and `modelNameSuffix` - Sets the pre- or suffix for model classes and enums. +- `modelNamePrefix` and `modelNameSuffix` - Sets the pre- or suffix for model classes and enums +- `useJaxbAnnotations` - enable Jaxb annotations inside the generated models - `configOptions` - a map of language-specific parameters (see below) - `configHelp` - dumps the configuration help for the specified library (generates no sources) +- `ignoreFileOverride` - specifies the full path to a `.swagger-codegen-ignore` used for pattern based overrides of generated outputs ### Custom Generator diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java index 813762112d2..613c2b9186f 100644 --- a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -21,6 +21,7 @@ import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyImportMapp import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyInstantiationTypesKvp; import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyLanguageSpecificPrimitivesCsv; import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyTypeMappingsKvp; +import static io.swagger.codegen.config.CodegenConfiguratorUtils.applyReservedWordsMappingsKvp; import static org.apache.commons.lang3.StringUtils.isNotEmpty; import java.io.File; @@ -161,6 +162,12 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(name = "modelNameSuffix", required = false) private String modelNameSuffix; + /** + * Sets an optional ignoreFileOverride path + */ + @Parameter(name = "ignoreFileOverride", required = false) + private String ignoreFileOverride; + /** * A map of language-specific parameters as passed with the -c option to the command line */ @@ -215,6 +222,10 @@ public class CodeGenMojo extends AbstractMojo { configurator.setGitRepoId(gitRepoId); } + if(isNotEmpty(ignoreFileOverride)) { + configurator.setIgnoreFileOverride(ignoreFileOverride); + } + configurator.setLang(language); configurator.setOutputDir(output.getAbsolutePath()); @@ -284,6 +295,10 @@ public class CodeGenMojo extends AbstractMojo { if(configOptions.containsKey("additional-properties")) { applyAdditionalPropertiesKvp(configOptions.get("additional-properties").toString(), configurator); } + + if(configOptions.containsKey("reserved-words-mappings")) { + applyReservedWordsMappingsKvp(configOptions.get("reserved-words-mappings").toString(), configurator); + } } if (environmentVariables != null) { @@ -330,7 +345,7 @@ public class CodeGenMojo extends AbstractMojo { } if (addCompileSourceRoot) { - final Object sourceFolderObject = configOptions.get(CodegenConstants.SOURCE_FOLDER); + final Object sourceFolderObject = configOptions == null ? null : configOptions.get(CodegenConstants.SOURCE_FOLDER); final String sourceFolder = sourceFolderObject == null ? "src/main/java" : sourceFolderObject.toString(); String sourceJavaFolder = output.toString() + "/" + sourceFolder; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java index 849651baa9d..abf77b59cb1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/AbstractGenerator.java @@ -56,7 +56,7 @@ public abstract class AbstractGenerator { if (is == null) { is = new FileInputStream(new File(name)); // May throw but never return a null value } - return new InputStreamReader(is); + return new InputStreamReader(is, "UTF-8"); } catch (Exception e) { LOGGER.error(e.getMessage()); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java index c4f0dc1ce7a..839f0800e15 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/Codegen.java @@ -25,9 +25,9 @@ import io.swagger.parser.SwaggerParser; */ @Deprecated public class Codegen extends DefaultGenerator { - + private static final Logger LOGGER = LoggerFactory.getLogger(Codegen.class); - + static Map configs = new HashMap(); static String configString; static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:" + diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 4b0ef89593f..4ffb9558230 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -14,7 +14,7 @@ import com.samskivert.mustache.Mustache.Compiler; public interface CodegenConfig { CodegenType getTag(); - + String getName(); String getHelp(); @@ -118,6 +118,8 @@ public interface CodegenConfig { Map modelDocTemplateFiles(); Set languageSpecificPrimitives(); + + Map reservedWordsMappings(); void preprocessSwagger(Swagger swagger); @@ -197,4 +199,8 @@ public interface CodegenConfig { String getHttpUserAgent(); String getCommonTemplateDir(); + + void setIgnoreFilePathOverride(String ignoreFileOverride); + + String getIgnoreFilePathOverride(); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index 094ff38e8fd..30707bce341 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -12,6 +12,8 @@ public class CodegenConstants { public static final String TEMPLATE_DIR = "templateDir"; + public static final String ALLOW_UNICODE_IDENTIFIERS = "allowUnicodeIdentifiers"; + public static final String ALLOW_UNICODE_IDENTIFIERS_DESC = "boolean, toggles whether unicode identifiers are allowed in names or not, default is false"; public static final String INVOKER_PACKAGE = "invokerPackage"; public static final String INVOKER_PACKAGE_DESC = "root package for generated code"; @@ -19,6 +21,12 @@ public class CodegenConstants { public static final String PHP_INVOKER_PACKAGE = "phpInvokerPackage"; public static final String PHP_INVOKER_PACKAGE_DESC = "root package for generated php code"; + public static final String PERL_MODULE_NAME = "perlModuleName"; + public static final String PERL_MODULE_NAME_DESC = "root module name for generated perl code"; + + public static final String PYTHON_PACKAGE_NAME = "pythonPackageName"; + public static final String PYTHON_PACKAGE_NAME_DESC = "package name for generated python code"; + public static final String GROUP_ID = "groupId"; public static final String GROUP_ID_DESC = "groupId in generated pom.xml"; @@ -28,6 +36,33 @@ public class CodegenConstants { public static final String ARTIFACT_VERSION = "artifactVersion"; public static final String ARTIFACT_VERSION_DESC = "artifact version in generated pom.xml"; + public static final String ARTIFACT_URL = "artifactUrl"; + public static final String ARTIFACT_URL_DESC = "artifact URL in generated pom.xml"; + + public static final String ARTIFACT_DESCRIPTION = "artifactDescription"; + public static final String ARTIFACT_DESCRIPTION_DESC = "artifact description in generated pom.xml"; + + public static final String SCM_CONNECTION = "scmConnection"; + public static final String SCM_CONNECTION_DESC = "SCM connection in generated pom.xml"; + + public static final String SCM_DEVELOPER_CONNECTION = "scmDeveloperConnection"; + public static final String SCM_DEVELOPER_CONNECTION_DESC = "SCM developer connection in generated pom.xml"; + + public static final String SCM_URL = "scmUrl"; + public static final String SCM_URL_DESC = "SCM URL in generated pom.xml"; + + public static final String DEVELOPER_NAME = "developerName"; + public static final String DEVELOPER_NAME_DESC = "developer name in generated pom.xml"; + + public static final String DEVELOPER_EMAIL = "developerEmail"; + public static final String DEVELOPER_EMAIL_DESC = "developer email in generated pom.xml"; + + public static final String DEVELOPER_ORGANIZATION = "developerOrganization"; + public static final String DEVELOPER_ORGANIZATION_DESC = "developer organization in generated pom.xml"; + + public static final String DEVELOPER_ORGANIZATION_URL = "developerOrganizationUrl"; + public static final String DEVELOPER_ORGANIZATION_URL_DESC = "developer organization URL in generated pom.xml"; + public static final String LICENSE_NAME = "licenseName"; public static final String LICENSE_NAME_DESC = "The name of the license"; @@ -86,6 +121,9 @@ public class CodegenConstants { public static final String USE_COLLECTION = "useCollection"; public static final String USE_COLLECTION_DESC = "Deserialize array types to Collection instead of List."; + public static final String INTERFACE_PREFIX = "interfacePrefix"; + public static final String INTERFACE_PREFIX_DESC = "Prefix interfaces with a community standard or widely accepted prefix."; + public static final String RETURN_ICOLLECTION = "returnICollection"; public static final String RETURN_ICOLLECTION_DESC = "Return ICollection instead of the concrete type."; @@ -137,8 +175,15 @@ public class CodegenConstants { public static final String GENERATE_MODEL_TESTS_DESC = "Specifies that model tests are to be generated."; public static final String HIDE_GENERATION_TIMESTAMP = "hideGenerationTimestamp"; - public static final String HIDE_GENERATION_TIMESTAMP_DESC = "Hides the generation timestamp."; + public static final String HIDE_GENERATION_TIMESTAMP_DESC = "Hides the generation timestamp when files are generated."; public static final String GENERATE_PROPERTY_CHANGED = "generatePropertyChanged"; public static final String GENERATE_PROPERTY_CHANGED_DESC = "Specifies that models support raising property changed events."; + + public static final String NON_PUBLIC_API = "nonPublicApi"; + public static final String NON_PUBLIC_API_DESC = "Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers."; + + public static final String IGNORE_FILE_OVERRIDE = "ignoreFileOverride"; + public static final String IGNORE_FILE_OVERRIDE_DESC = "Specifies an override location for the .swagger-codegen-ignore file. Most useful on initial generation."; + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index 75edc6b7fbd..3a0db92c5a4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -90,6 +90,7 @@ public class CodegenParameter { output.collectionFormat = this.collectionFormat; output.isCollectionFormatMulti = this.isCollectionFormatMulti; output.description = this.description; + output.unescapedDescription = this.unescapedDescription; output.baseType = this.baseType; output.isFormParam = this.isFormParam; output.isQueryParam = this.isQueryParam; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index 4e6b9f8b879..de6ebb715f2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -7,9 +7,11 @@ import java.util.Map; import java.util.Objects; public class CodegenProperty implements Cloneable { - public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum, - dataFormat, name, min, max, defaultValue, defaultValueWithParam, baseType, containerType; + public String baseName, complexType, getter, setter, description, datatype, + datatypeWithEnum, dataFormat, name, min, max, defaultValue, defaultValueWithParam, + baseType, containerType, title; + /** The 'description' string without escape charcters needed by some programming languages/targets */ public String unescapedDescription; /** @@ -49,7 +51,10 @@ public class CodegenProperty implements Cloneable { public boolean isInherited; public String nameInCamelCase; // property name in camel case // enum name based on the property name, usually use as a prefix (e.g. VAR_NAME) for enum name (e.g. VAR_NAME_VALUE1) - public String enumName; + public String enumName; + public Integer maxItems; + public Integer minItems; + @Override public String toString() { @@ -74,6 +79,7 @@ public class CodegenProperty implements Cloneable { result = prime * result + ((defaultValue == null) ? 0 : defaultValue.hashCode()); result = prime * result + ((defaultValueWithParam == null) ? 0 : defaultValueWithParam.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode()); + result = prime * result + ((title == null) ? 0 : title.hashCode()); result = prime * result + ((example == null) ? 0 : example.hashCode()); result = prime * result + (exclusiveMaximum ? 13:31); result = prime * result + (exclusiveMinimum ? 13:31); @@ -117,6 +123,8 @@ public class CodegenProperty implements Cloneable { result = prime * result + Objects.hashCode(isInherited); result = prime * result + Objects.hashCode(nameInCamelCase); result = prime * result + Objects.hashCode(enumName); + result = prime * result + ((maxItems == null) ? 0 : maxItems.hashCode()); + result = prime * result + ((minItems == null) ? 0 : minItems.hashCode()); return result; } @@ -144,6 +152,9 @@ public class CodegenProperty implements Cloneable { if ((this.description == null) ? (other.description != null) : !this.description.equals(other.description)) { return false; } + if ((this.title == null) ? (other.title != null) : !this.title.equals(other.title)) { + return false; + } if ((this.datatype == null) ? (other.datatype != null) : !this.datatype.equals(other.datatype)) { return false; } @@ -283,6 +294,12 @@ public class CodegenProperty implements Cloneable { if (!Objects.equals(this.enumName, other.enumName)) { return false; } + if (this.maxItems != other.maxItems && (this.maxItems == null || !this.maxItems.equals(other.maxItems))) { + return false; + } + if (this.minItems != other.minItems && (this.minItems == null || !this.minItems.equals(other.minItems))) { + return false; + } return true; } @@ -307,6 +324,6 @@ public class CodegenProperty implements Cloneable { throw new IllegalStateException(e); } } - - + + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java index fb09f820be5..4f1c9c54c3e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java @@ -19,6 +19,7 @@ public class CodegenResponse { public Boolean isFile = Boolean.FALSE; public Object schema; public String jsonSchema; + public Map vendorExtensions; public boolean isWildcard() { return "0".equals(code) || "default".equals(code); @@ -68,6 +69,8 @@ public class CodegenResponse { return false; if (schema != null ? !schema.equals(that.schema) : that.schema != null) return false; + if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null) + return false; return jsonSchema != null ? jsonSchema.equals(that.jsonSchema) : that.jsonSchema == null; } @@ -91,6 +94,7 @@ public class CodegenResponse { result = 31 * result + (isFile != null ? isFile.hashCode() : 0); result = 31 * result + (schema != null ? schema.hashCode() : 0); result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0); + result = 31 * result + (vendorExtensions != null ? vendorExtensions.hashCode() : 0); return result; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index c1daf3ce8ab..99b9ba4f381 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -92,6 +92,7 @@ public class DefaultCodegen { protected Map modelTestTemplateFiles = new HashMap(); protected Map apiDocTemplateFiles = new HashMap(); protected Map modelDocTemplateFiles = new HashMap(); + protected Map reservedWordsMappings = new HashMap(); protected String templateDir; protected String embeddedTemplateDir; protected String commonTemplateDir = "_common"; @@ -106,6 +107,7 @@ public class DefaultCodegen { protected String library; protected Boolean sortParamsByRequiredFlag = true; protected Boolean ensureUniqueParams = true; + protected Boolean allowUnicodeIdentifiers = false; protected String gitUserId, gitRepoId, releaseNote; protected String httpUserAgent; protected Boolean hideGenerationTimestamp = true; @@ -114,6 +116,8 @@ public class DefaultCodegen { // Then translated back during JSON encoding and decoding protected Map specialCharReplacements = new HashMap(); + protected String ignoreFilePathOverride; + public List cliOptions() { return cliOptions; } @@ -141,6 +145,11 @@ public class DefaultCodegen { .get(CodegenConstants.ENSURE_UNIQUE_PARAMS).toString())); } + if (additionalProperties.containsKey(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS)) { + this.setAllowUnicodeIdentifiers(Boolean.valueOf(additionalProperties + .get(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS).toString())); + } + if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_PREFIX)){ this.setModelNamePrefix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_PREFIX)); } @@ -148,7 +157,6 @@ public class DefaultCodegen { if(additionalProperties.containsKey(CodegenConstants.MODEL_NAME_SUFFIX)){ this.setModelNameSuffix((String) additionalProperties.get(CodegenConstants.MODEL_NAME_SUFFIX)); } - } // override with any special post-processing for all models @@ -185,12 +193,18 @@ public class DefaultCodegen { for (String name : allModels.keySet()) { CodegenModel cm = allModels.get(name); CodegenModel parent = allModels.get(cm.parent); + // if a discriminator exists on the parent, don't add this child to the inheritance heirarchy + // TODO Determine what to do if the parent discriminator name == the grandparent discriminator name while (parent != null) { if (parent.children == null) { - parent.children = new ArrayList(); + parent.children = new ArrayList(); } parent.children.add(cm); - parent = allModels.get(parent.parent); + if (parent.discriminator == null) { + parent = allModels.get(parent.parent); + } else { + parent = null; + } } } } @@ -303,6 +317,10 @@ public class DefaultCodegen { * @return the sanitized variable name for enum */ public String toEnumVarName(String value, String datatype) { + if (value.length() == 0) { + return "EMPTY"; + } + String var = value.replaceAll("\\W+", "_").toUpperCase(); if (var.matches("\\d.*")) { return "_" + var; @@ -346,7 +364,7 @@ public class DefaultCodegen { // override with any special handling of the JMustache compiler @SuppressWarnings("unused") public Compiler processCompiler(Compiler compiler) { - return compiler; + return compiler; } // override with any special text escaping logic @@ -464,6 +482,10 @@ public class DefaultCodegen { public Map modelDocTemplateFiles() { return modelDocTemplateFiles; } + + public Map reservedWordsMappings() { + return reservedWordsMappings; + } public Map apiTestTemplateFiles() { return apiTestTemplateFiles; @@ -565,6 +587,10 @@ public class DefaultCodegen { this.ensureUniqueParams = ensureUniqueParams; } + public void setAllowUnicodeIdentifiers(Boolean allowUnicodeIdentifiers) { + this.allowUnicodeIdentifiers = allowUnicodeIdentifiers; + } + /** * Return the regular expression/JSON schema pattern (http://json-schema.org/latest/json-schema-validation.html#anchor33) * @@ -819,6 +845,10 @@ public class DefaultCodegen { cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants .ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); + //name formatting options + cliOptions.add(CliOption.newBoolean(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, CodegenConstants + .ALLOW_UNICODE_IDENTIFIERS_DESC).defaultValue(Boolean.FALSE.toString())); + // initialize special character mapping initalizeSpecialCharacterMapping(); } @@ -1261,6 +1291,18 @@ public class DefaultCodegen { allProperties = new LinkedHashMap(); allRequired = new ArrayList(); m.allVars = new ArrayList(); + int modelImplCnt = 0; // only one inline object allowed in a ComposedModel + for (Model innerModel: ((ComposedModel)model).getAllOf()) { + if (innerModel instanceof ModelImpl) { + if (m.discriminator == null) { + m.discriminator = ((ModelImpl) innerModel).getDiscriminator(); + } + if (modelImplCnt++ > 1) { + LOGGER.warn("More than one inline schema specified in allOf:. Only the first one is recognized. All others are ignored."); + break; // only one ModelImpl with discriminator allowed in allOf + } + } + } } else { allProperties = null; allRequired = null; @@ -1436,6 +1478,7 @@ public class DefaultCodegen { property.nameInCamelCase = camelize(property.name, false); property.description = escapeText(p.getDescription()); property.unescapedDescription = p.getDescription(); + property.title = p.getTitle(); property.getter = "get" + getterAndSetterCapitalize(name); property.setter = "set" + getterAndSetterCapitalize(name); property.example = toExampleValue(p); @@ -1680,16 +1723,18 @@ public class DefaultCodegen { property.baseType = getSwaggerType(p); - if (p instanceof ArrayProperty) { + if (p instanceof ArrayProperty) { property.isContainer = true; property.isListContainer = true; property.containerType = "array"; property.baseType = getSwaggerType(p); // handle inner property ArrayProperty ap = (ArrayProperty) p; + property.maxItems = ap.getMaxItems(); + property.minItems = ap.getMinItems(); CodegenProperty cp = fromProperty(property.name, ap.getItems()); updatePropertyForArray(property, cp); - } else if (p instanceof MapProperty) { + } else if (p instanceof MapProperty) { property.isContainer = true; property.isMapContainer = true; property.containerType = "map"; @@ -1714,6 +1759,7 @@ public class DefaultCodegen { LOGGER.warn("skipping invalid array property " + Json.pretty(property)); return; } + property.dataFormat = innerProperty.dataFormat; if (!languageSpecificPrimitives.contains(innerProperty.baseType)) { property.complexType = innerProperty.baseType; } else { @@ -1750,6 +1796,7 @@ public class DefaultCodegen { property.isPrimitiveType = true; } property.items = innerProperty; + property.dataFormat = innerProperty.dataFormat; // inner item is Enum if (isPropertyInnerMostEnum(property)) { // isEnum is set to true when the type is an enum @@ -1876,7 +1923,7 @@ public class DefaultCodegen { * @return Codegen Operation object */ public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { - return fromOperation(path, httpMethod, operation, definitions, null); + return fromOperation(path, httpMethod, operation, definitions, null); } /** @@ -2184,6 +2231,7 @@ public class DefaultCodegen { r.schema = response.getSchema(); r.examples = toExamples(response.getExamples()); r.jsonSchema = Json.pretty(response); + r.vendorExtensions = response.getVendorExtensions(); addHeaders(response, r.headers); if (r.schema != null) { @@ -2354,7 +2402,7 @@ public class DefaultCodegen { // validation // handle maximum, minimum properly for int/long by removing the trailing ".0" - if ("integer".equals(type)) { + if ("integer".equals(qp.getType())) { p.maximum = qp.getMaximum() == null ? null : String.valueOf(qp.getMaximum().longValue()); p.minimum = qp.getMinimum() == null ? null : String.valueOf(qp.getMinimum().longValue()); } else { @@ -2531,7 +2579,7 @@ public class DefaultCodegen { @SuppressWarnings("static-method") public List fromSecurity(Map schemes) { if (schemes == null) { - return Collections.emptyList(); + return Collections.emptyList(); } List secs = new ArrayList(schemes.size()); @@ -2555,8 +2603,8 @@ public class DefaultCodegen { sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isOAuth = false; sec.isBasic = true; } else { - final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; - sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; + final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; + sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; sec.isOAuth = true; sec.flow = oauth2Definition.getFlow(); if (sec.flow == null) { @@ -3191,11 +3239,11 @@ public class DefaultCodegen { // encountered so far and hopefully make it easier for others to add more special // cases in the future. - // better error handling when map/array type is invalid - if (name == null) { - LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN"); - return "ERROR_UNKNOWN"; - } + // better error handling when map/array type is invalid + if (name == null) { + LOGGER.error("String to be sanitized is null. Default to ERROR_UNKNOWN"); + return "ERROR_UNKNOWN"; + } // if the name is just '$', map it to 'value' for the time being. if ("$".equals(name)) { @@ -3224,7 +3272,14 @@ public class DefaultCodegen { // remove everything else other than word, number and _ // $php_variable => php_variable - return name.replaceAll("[^a-zA-Z0-9_]", ""); + if (allowUnicodeIdentifiers) { //could be converted to a single line with ?: operator + name = Pattern.compile("\\W", Pattern.UNICODE_CHARACTER_CLASS).matcher(name).replaceAll(""); + } + else { + name = name.replaceAll("\\W", ""); + } + + return name; } /** @@ -3416,11 +3471,44 @@ public class DefaultCodegen { public boolean convertPropertyToBooleanAndWriteBack(String propertyKey) { boolean booleanValue = false; if (additionalProperties.containsKey(propertyKey)) { - booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString()); + booleanValue = convertPropertyToBoolean(propertyKey); // write back as boolean - additionalProperties.put(propertyKey, booleanValue); + writePropertyBack(propertyKey, booleanValue); } return booleanValue; } + + /** + * Provides an override location, if any is specified, for the .swagger-codegen-ignore. + * + * This is originally intended for the first generation only. + * + * @return a string of the full path to an override ignore file. + */ + public String getIgnoreFilePathOverride() { + return ignoreFilePathOverride; + } + + /** + * Sets an override location for the .swagger-codegen.ignore location for the first code generation. + * + * @param ignoreFileOverride The full path to an ignore file + */ + public void setIgnoreFilePathOverride(final String ignoreFileOverride) { + this.ignoreFilePathOverride = ignoreFileOverride; + } + + public boolean convertPropertyToBoolean(String propertyKey) { + boolean booleanValue = false; + if (additionalProperties.containsKey(propertyKey)) { + booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString()); + } + + return booleanValue; + } + + public void writePropertyBack(String propertyKey, boolean value) { + additionalProperties.put(propertyKey, value); + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 94d1579671e..03433e64580 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -42,7 +42,21 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { this.swagger = opts.getSwagger(); this.config = opts.getConfig(); this.config.additionalProperties().putAll(opts.getOpts().getProperties()); - ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir()); + + String ignoreFileLocation = this.config.getIgnoreFilePathOverride(); + if(ignoreFileLocation != null) { + final File ignoreFile = new File(ignoreFileLocation); + if(ignoreFile.exists() && ignoreFile.canRead()) { + this.ignoreProcessor = new CodegenIgnoreProcessor(ignoreFile); + } else { + LOGGER.warn("Ignore file specified at {} is not valid. This will fall back to an existing ignore file if present in the output directory.", ignoreFileLocation); + } + } + + if(this.ignoreProcessor == null) { + this.ignoreProcessor = new CodegenIgnoreProcessor(this.config.getOutputDir()); + } + return this; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index 6ac586af8f4..b21e89711ff 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -54,12 +54,15 @@ public class CodegenConfigurator { private String artifactId; private String artifactVersion; private String library; + private String ignoreFileOverride; private Map systemProperties = new HashMap(); private Map instantiationTypes = new HashMap(); private Map typeMappings = new HashMap(); private Map additionalProperties = new HashMap(); private Map importMappings = new HashMap(); private Set languageSpecificPrimitives = new HashSet(); + private Map reservedWordMappings = new HashMap(); + private String gitUserId="GIT_USER_ID"; private String gitRepoId="GIT_REPO_ID"; private String releaseNote="Minor update"; @@ -263,7 +266,7 @@ public class CodegenConfigurator { this.additionalProperties = additionalProperties; return this; } - + public CodegenConfigurator addAdditionalProperty(String key, Object value) { this.additionalProperties.put(key, value); return this; @@ -341,7 +344,30 @@ public class CodegenConfigurator { this.httpUserAgent= httpUserAgent; return this; } + + public Map getReservedWordsMappings() { + return reservedWordMappings; + } + + public CodegenConfigurator setReservedWordsMappings(Map reservedWordsMappings) { + this.reservedWordMappings = reservedWordsMappings; + return this; + } + + public CodegenConfigurator addAdditionalReservedWordMapping(String key, String value) { + this.reservedWordMappings.put(key, value); + return this; + } + public String getIgnoreFileOverride() { + return ignoreFileOverride; + } + + public CodegenConfigurator setIgnoreFileOverride(final String ignoreFileOverride) { + this.ignoreFileOverride = ignoreFileOverride; + return this; + } + public ClientOptInput toClientOptInput() { Validate.notEmpty(lang, "language must be specified"); @@ -355,12 +381,14 @@ public class CodegenConfigurator { config.setInputSpec(inputSpec); config.setOutputDir(outputDir); config.setSkipOverwrite(skipOverwrite); + config.setIgnoreFilePathOverride(ignoreFileOverride); config.instantiationTypes().putAll(instantiationTypes); config.typeMapping().putAll(typeMappings); config.importMapping().putAll(importMappings); config.languageSpecificPrimitives().addAll(languageSpecificPrimitives); - + config.reservedWordsMappings().putAll(reservedWordMappings); + checkAndSetAdditionalProperty(apiPackage, CodegenConstants.API_PACKAGE); checkAndSetAdditionalProperty(modelPackage, CodegenConstants.MODEL_PACKAGE); checkAndSetAdditionalProperty(invokerPackage, CodegenConstants.INVOKER_PACKAGE); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java index b5a6a6355be..90a96837797 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfiguratorUtils.java @@ -58,6 +58,13 @@ public final class CodegenConfiguratorUtils { } } + public static void applyReservedWordsMappingsKvp(String reservedWordMappings, CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(reservedWordMappings); + for (Map.Entry entry : map.entrySet()) { + configurator.addAdditionalReservedWordMapping(entry.getKey(), entry.getValue()); + } + } + private static Set createSetFromCsvList(String csvProperty) { final List values = OptionUtils.splitCommaSeparatedList(csvProperty); return new HashSet(values); @@ -74,4 +81,6 @@ public final class CodegenConfiguratorUtils { return result; } + + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java index ed9ab123354..c59449be439 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/examples/XmlExampleGenerator.java @@ -9,13 +9,22 @@ import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.BooleanProperty; import io.swagger.models.properties.DateProperty; import io.swagger.models.properties.DateTimeProperty; -import io.swagger.models.properties.IntegerProperty; import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.DecimalProperty; +import io.swagger.models.properties.DoubleProperty; +import io.swagger.models.properties.BaseIntegerProperty; +import io.swagger.models.properties.AbstractNumericProperty; +import io.swagger.models.properties.PasswordProperty; +import io.swagger.models.properties.UUIDProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; + import org.codehaus.plexus.util.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -25,6 +34,7 @@ import java.util.Map; import java.util.Set; public class XmlExampleGenerator { + protected final Logger LOGGER = LoggerFactory.getLogger(XmlExampleGenerator.class); public static String NEWLINE = "\n"; public static String TAG_START = "<"; public static String CLOSE_TAG = ">"; @@ -163,45 +173,44 @@ public class XmlExampleGenerator { return sb.toString(); } + /** + * Get the example string value for the given Property. + * + * If an example value was not provided in the specification, a default will be generated. + * + * @param property Property to get example string for + * + * @return Example String + */ protected String getExample(Property property) { - if (property instanceof DateTimeProperty) { - if (property.getExample() != null) { - return property.getExample().toString(); - } else { - return "2000-01-23T04:56:07.000Z"; - } - } else if (property instanceof StringProperty) { - if (property.getExample() != null) { - return property.getExample().toString(); - } else { - return "string"; - } + if (property.getExample() != null) { + return property.getExample().toString(); + } else if (property instanceof DateTimeProperty) { + return "2000-01-23T04:56:07.000Z"; } else if (property instanceof DateProperty) { - if (property.getExample() != null) { - return property.getExample().toString(); - } else { - return "2000-01-23"; - } - } else if (property instanceof IntegerProperty) { - if (property.getExample() != null) { - return property.getExample().toString(); - } else { - return "0"; - } + return "2000-01-23"; } else if (property instanceof BooleanProperty) { - if (property.getExample() != null) { - return property.getExample().toString(); - } else { - return "true"; - } + return "true"; } else if (property instanceof LongProperty) { - if (property.getExample() != null) { - return property.getExample().toString(); - } else { - return "123456"; - } + return "123456789"; + } else if (property instanceof DoubleProperty) { // derived from DecimalProperty so make sure this is first + return "3.149"; + } else if (property instanceof DecimalProperty) { + return "1.3579"; + } else if (property instanceof PasswordProperty) { + return "********"; + } else if (property instanceof UUIDProperty) { + return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; + // do these last in case the specific types above are derived from these classes + } else if (property instanceof StringProperty) { + return "aeiou"; + } else if (property instanceof BaseIntegerProperty) { + return "123"; + } else if (property instanceof AbstractNumericProperty) { + return "1.23"; } - return "not implemented " + property; + LOGGER.warn("default example value not implemented for " + property); + return ""; } @SuppressWarnings("static-method") diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/CodegenIgnoreProcessor.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/CodegenIgnoreProcessor.java index fb25ac82b28..2852c6eed96 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/CodegenIgnoreProcessor.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/CodegenIgnoreProcessor.java @@ -8,34 +8,71 @@ import org.slf4j.LoggerFactory; import java.io.*; import java.util.ArrayList; +import java.util.Collection; import java.util.List; +/** + * Presents a processing utility for parsing and evaluating files containing common ignore patterns. (.swagger-codegen-ignore) + */ public class CodegenIgnoreProcessor { private static final Logger LOGGER = LoggerFactory.getLogger(CodegenIgnoreProcessor.class); - private final String outputPath; + + private File ignoreFile = null; + private List exclusionRules = new ArrayList<>(); private List inclusionRules = new ArrayList<>(); - public CodegenIgnoreProcessor(String outputPath) { - this.outputPath = outputPath; - final File directory = new File(outputPath); - if(directory.exists() && directory.isDirectory()){ - final File codegenIgnore = new File(directory, ".swagger-codegen-ignore"); - if(codegenIgnore.exists() && codegenIgnore.isFile()){ - try { - loadCodegenRules(codegenIgnore); - } catch (IOException e) { - LOGGER.error("Could not process .swagger-codegen-ignore.", e.getMessage()); - } - } else { - // log info message - LOGGER.info("No .swagger-codegen-ignore file found."); - } + /** + * Loads the default ignore file (.swagger-codegen-ignore) from the specified path. + * + * @param baseDirectory The base directory of the files to be processed. This contains the ignore file. + */ + public CodegenIgnoreProcessor(final String baseDirectory) { + this(baseDirectory, ".swagger-codegen-ignore"); + } + + /** + * Loads the specified ignore file by name ([ignoreFile]) from the specified path. + * + * @param baseDirectory The base directory of the files to be processed. This contains the ignore file. + * @param ignoreFile The file containing ignore patterns. + */ + @SuppressWarnings("WeakerAccess") + public CodegenIgnoreProcessor(final String baseDirectory, final String ignoreFile) { + final File directory = new File(baseDirectory); + final File targetIgnoreFile = new File(directory, ignoreFile); + if (directory.exists() && directory.isDirectory()) { + loadFromFile(targetIgnoreFile); + } else { + LOGGER.warn("Directory does not exist, or is inaccessible. No file will be evaluated."); } } - void loadCodegenRules(File codegenIgnore) throws IOException { + /** + * Constructs an instance of {@link CodegenIgnoreProcessor} from an ignore file defined by {@code targetIgnoreFile}. + * + * @param targetIgnoreFile The ignore file location. + */ + public CodegenIgnoreProcessor(final File targetIgnoreFile) { + loadFromFile(targetIgnoreFile); + } + + private void loadFromFile(File targetIgnoreFile) { + if (targetIgnoreFile.exists() && targetIgnoreFile.isFile()) { + try { + loadCodegenRules(targetIgnoreFile); + this.ignoreFile = targetIgnoreFile; + } catch (IOException e) { + LOGGER.error(String.format("Could not process %s.", targetIgnoreFile.getName()), e.getMessage()); + } + } else { + // log info message + LOGGER.info(String.format("No %s file found.", targetIgnoreFile.getName())); + } + } + + void loadCodegenRules(final File codegenIgnore) throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(codegenIgnore))) { String line; @@ -61,8 +98,17 @@ public class CodegenIgnoreProcessor { } } - public boolean allowsFile(File targetFile) { - File file = new File(new File(this.outputPath).toURI().relativize(targetFile.toURI()).getPath()); + /** + * Determines whether or not a file defined by {@code toEvaluate} is allowed, + * under the exclusion rules from the ignore file being processed. + * + * @param targetFile The file to check against exclusion rules from the ignore file. + * @return {@code false} if file matches any pattern in the ignore file (disallowed), otherwise {@code true} (allowed). + */ + public boolean allowsFile(final File targetFile) { + if(this.ignoreFile == null) return true; + + File file = new File(this.ignoreFile.getParentFile().toURI().relativize(targetFile.toURI()).getPath()); Boolean directoryExcluded = false; Boolean exclude = false; if(exclusionRules.size() == 0 && inclusionRules.size() == 0) { @@ -124,10 +170,23 @@ public class CodegenIgnoreProcessor { return Boolean.FALSE.equals(exclude); } + /** + * Allows a consumer to manually inspect explicit "inclusion rules". That is, patterns in the ignore file which have been negated. + * + * @return A {@link ImmutableList#copyOf(Collection)} of rules which possibly negate exclusion rules in the ignore file. + */ public List getInclusionRules() { return ImmutableList.copyOf(inclusionRules); } + /** + * Allows a consumer to manually inspect all "exclusion rules". That is, patterns in the ignore file which represent + * files and directories to be excluded, unless explicitly overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules. + * + * NOTE: Existence in this list doesn't mean a file is excluded. The rule can be overridden by {@link CodegenIgnoreProcessor#getInclusionRules()} rules. + * + * @return A {@link ImmutableList#copyOf(Collection)} of rules which define exclusions by patterns in the ignore file. + */ public List getExclusionRules() { return ImmutableList.copyOf(exclusionRules); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java index 137cb071cab..2d2394302f8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ignore/rules/Rule.java @@ -51,6 +51,8 @@ public abstract class Rule { * Example: **\/*.bak excludes all backup. Adding !/test.bak will include test.bak in the project root. *

* NOTE: It is not possible to re-include a file if a parent directory of that file is excluded. + * + * @return {@code true} if the rule is negated (inverse), otherwise {@code false} (normal). */ public Boolean getNegated() { return this.syntax != null && this.syntax.size() > 0 && this.syntax.get(0).getToken() == IgnoreLineParser.Token.NEGATE; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index 922e9213add..e9259a4b3f4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -27,6 +27,8 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co protected String packageCompany = "Swagger"; protected String packageCopyright = "No Copyright"; + protected String interfacePrefix = "I"; + protected String sourceFolder = "src"; // TODO: Add option for test folder output location. Nice to allow e.g. ./test instead of ./src. @@ -254,6 +256,19 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES)) { setOptionalEmitDefaultValue(Boolean.valueOf(additionalProperties.get(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES).toString())); } + + if (additionalProperties.containsKey(CodegenConstants.INTERFACE_PREFIX)) { + String useInterfacePrefix = additionalProperties.get(CodegenConstants.INTERFACE_PREFIX).toString(); + if("false".equals(useInterfacePrefix.toLowerCase())) { + setInterfacePrefix(""); + } else if(!"true".equals(useInterfacePrefix.toLowerCase())) { + // NOTE: if user passes "true" explicitly, we use the default I- prefix. The other supported case here is a custom prefix. + setInterfacePrefix(sanitizeName(useInterfacePrefix)); + } + } + + // This either updates additionalProperties with the above fixes, or sets the default if the option was not specified. + additionalProperties.put(CodegenConstants.INTERFACE_PREFIX, interfacePrefix); } @Override @@ -401,10 +416,13 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co } return name; - } + } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } @@ -466,7 +484,13 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co if (p instanceof StringProperty) { StringProperty dp = (StringProperty) p; if (dp.getDefault() != null) { - return "\"" + dp.getDefault() + "\""; + String _default = dp.getDefault(); + if (dp.getEnum() == null) { + return "\"" + _default + "\""; + } else { + // convert to enum var name later in postProcessModels + return _default; + } } } else if (p instanceof BooleanProperty) { BooleanProperty dp = (BooleanProperty) p; @@ -613,8 +637,20 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co this.sourceFolder = sourceFolder; } + public String getInterfacePrefix() { + return interfacePrefix; + } + + public void setInterfacePrefix(final String interfacePrefix) { + this.interfacePrefix = interfacePrefix; + } + @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "Empty"; + } + // for symbol, e.g. $, # if (getSymbolName(name) != null) { return camelize(getSymbolName(name)); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java index 5741ade12f6..3ab3895bb4b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaCodegen.java @@ -52,6 +52,15 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code protected String groupId = "io.swagger"; protected String artifactId = "swagger-java"; protected String artifactVersion = "1.0.0"; + protected String artifactUrl = "https://github.com/swagger-api/swagger-codegen"; + protected String artifactDescription = "Swagger Java"; + protected String developerName = "Swagger"; + protected String developerEmail = "apiteam@swagger.io"; + protected String developerOrganization = "Swagger"; + protected String developerOrganizationUrl = "http://swagger.io"; + protected String scmConnection = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + protected String scmDeveloperConnection = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + protected String scmUrl = "https://github.com/swagger-api/swagger-codegen"; protected String licenseName = "Unlicense"; protected String licenseUrl = "http://unlicense.org"; protected String projectFolder = "src" + File.separator + "main"; @@ -118,6 +127,15 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_VERSION, CodegenConstants.ARTIFACT_VERSION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_URL, CodegenConstants.ARTIFACT_URL_DESC)); + cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_DESCRIPTION, CodegenConstants.ARTIFACT_DESCRIPTION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SCM_CONNECTION, CodegenConstants.SCM_CONNECTION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SCM_DEVELOPER_CONNECTION, CodegenConstants.SCM_DEVELOPER_CONNECTION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SCM_URL, CodegenConstants.SCM_URL_DESC)); + cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_NAME, CodegenConstants.DEVELOPER_NAME_DESC)); + cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_EMAIL, CodegenConstants.DEVELOPER_EMAIL_DESC)); + cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_ORGANIZATION, CodegenConstants.DEVELOPER_ORGANIZATION_DESC)); + cliOptions.add(new CliOption(CodegenConstants.DEVELOPER_ORGANIZATION_URL, CodegenConstants.DEVELOPER_ORGANIZATION_URL_DESC)); cliOptions.add(new CliOption(CodegenConstants.LICENSE_NAME, CodegenConstants.LICENSE_NAME_DESC)); cliOptions.add(new CliOption(CodegenConstants.LICENSE_URL, CodegenConstants.LICENSE_URL_DESC)); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); @@ -191,6 +209,60 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); } + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_URL)) { + this.setArtifactUrl((String) additionalProperties.get(CodegenConstants.ARTIFACT_URL)); + } else { + additionalProperties.put(CodegenConstants.ARTIFACT_URL, artifactUrl); + } + + if (additionalProperties.containsKey(CodegenConstants.ARTIFACT_DESCRIPTION)) { + this.setArtifactDescription((String) additionalProperties.get(CodegenConstants.ARTIFACT_DESCRIPTION)); + } else { + additionalProperties.put(CodegenConstants.ARTIFACT_DESCRIPTION, artifactDescription); + } + + if (additionalProperties.containsKey(CodegenConstants.SCM_CONNECTION)) { + this.setScmConnection((String) additionalProperties.get(CodegenConstants.SCM_CONNECTION)); + } else { + additionalProperties.put(CodegenConstants.SCM_CONNECTION, scmConnection); + } + + if (additionalProperties.containsKey(CodegenConstants.SCM_DEVELOPER_CONNECTION)) { + this.setScmDeveloperConnection((String) additionalProperties.get(CodegenConstants.SCM_DEVELOPER_CONNECTION)); + } else { + additionalProperties.put(CodegenConstants.SCM_DEVELOPER_CONNECTION, scmDeveloperConnection); + } + + if (additionalProperties.containsKey(CodegenConstants.SCM_URL)) { + this.setScmUrl((String) additionalProperties.get(CodegenConstants.SCM_URL)); + } else { + additionalProperties.put(CodegenConstants.SCM_URL, scmUrl); + } + + if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_NAME)) { + this.setDeveloperName((String) additionalProperties.get(CodegenConstants.DEVELOPER_NAME)); + } else { + additionalProperties.put(CodegenConstants.DEVELOPER_NAME, developerName); + } + + if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_EMAIL)) { + this.setDeveloperEmail((String) additionalProperties.get(CodegenConstants.DEVELOPER_EMAIL)); + } else { + additionalProperties.put(CodegenConstants.DEVELOPER_EMAIL, developerEmail); + } + + if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_ORGANIZATION)) { + this.setDeveloperOrganization((String) additionalProperties.get(CodegenConstants.DEVELOPER_ORGANIZATION)); + } else { + additionalProperties.put(CodegenConstants.DEVELOPER_ORGANIZATION, developerOrganization); + } + + if (additionalProperties.containsKey(CodegenConstants.DEVELOPER_ORGANIZATION_URL)) { + this.setDeveloperOrganizationUrl((String) additionalProperties.get(CodegenConstants.DEVELOPER_ORGANIZATION_URL)); + } else { + additionalProperties.put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, developerOrganizationUrl); + } + if (additionalProperties.containsKey(CodegenConstants.LICENSE_NAME)) { this.setLicenseName((String) additionalProperties.get(CodegenConstants.LICENSE_NAME)); } else { @@ -336,6 +408,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } @@ -434,11 +509,22 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public String toModelName(final String name) { - final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix); + final String sanitizedName = sanitizeName(name); + + String nameWithPrefixSuffix = sanitizedName; + if (!StringUtils.isEmpty(modelNamePrefix)) { + // add '_' so that model name can be camelized correctly + nameWithPrefixSuffix = modelNamePrefix + "_" + nameWithPrefixSuffix; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + // add '_' so that model name can be camelized correctly + nameWithPrefixSuffix = nameWithPrefixSuffix + "_" + modelNameSuffix; + } // camelize the model name // phone_number => PhoneNumber - final String camelizedName = camelize(sanitizedName); + final String camelizedName = camelize(nameWithPrefixSuffix); // model name cannot use reserved keyword, e.g. return if (isReservedWord(camelizedName)) { @@ -448,7 +534,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code } // model name starts with number - if (name.matches("^\\d.*")) { + 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); return modelName; @@ -815,6 +901,10 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code @Override public String toEnumVarName(String value, String datatype) { + if (value.length() == 0) { + return "EMPTY"; + } + // for symbol, e.g. $, # if (getSymbolName(value) != null) { return getSymbolName(value).toUpperCase(); @@ -929,6 +1019,42 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code this.artifactVersion = artifactVersion; } + public void setArtifactUrl(String artifactUrl) { + this.artifactUrl = artifactUrl; + } + + public void setArtifactDescription(String artifactDescription) { + this.artifactDescription = artifactDescription; + } + + public void setScmConnection(String scmConnection) { + this.scmConnection = scmConnection; + } + + public void setScmDeveloperConnection(String scmDeveloperConnection) { + this.scmDeveloperConnection = scmDeveloperConnection; + } + + public void setScmUrl(String scmUrl) { + this.scmUrl = scmUrl; + } + + public void setDeveloperName(String developerName) { + this.developerName = developerName; + } + + public void setDeveloperEmail(String developerEmail) { + this.developerEmail = developerEmail; + } + + public void setDeveloperOrganization(String developerOrganization) { + this.developerOrganization = developerOrganization; + } + + public void setDeveloperOrganizationUrl(String developerOrganizationUrl) { + this.developerOrganizationUrl = developerOrganizationUrl; + } + public void setLicenseName(String licenseName) { this.licenseName = licenseName; } @@ -1008,4 +1134,22 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code return escapeText(pattern); } + public boolean convertPropertyToBoolean(String propertyKey) { + boolean booleanValue = false; + if (additionalProperties.containsKey(propertyKey)) { + booleanValue = Boolean.valueOf(additionalProperties.get(propertyKey).toString()); + } + + return booleanValue; + } + + public void writePropertyBack(String propertyKey, boolean value) { + additionalProperties.put(propertyKey, value); + } + + @Override + public String sanitizeTag(String tag) { + return camelize(sanitizeName(tag)); + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java index 08410c47d44..3dc349edb70 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractJavaJAXRSServerCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; +import io.swagger.codegen.languages.features.BeanValidationFeatures; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; @@ -10,7 +11,7 @@ import org.slf4j.LoggerFactory; import java.util.*; -public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen { +public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen implements BeanValidationFeatures { /** * Name of the sub-directory in "src/main/resource" where to find the * Mustache template for the JAX-RS Codegen. @@ -19,6 +20,9 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen protected String implFolder = "src/main/java"; protected String testResourcesFolder = "src/test/resources"; protected String title = "Swagger Server"; + + protected boolean useBeanValidation = true; + static Logger LOGGER = LoggerFactory.getLogger(AbstractJavaJAXRSServerCodegen.class); public AbstractJavaJAXRSServerCodegen() @@ -40,6 +44,8 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen cliOptions.add(new CliOption(CodegenConstants.IMPL_FOLDER, CodegenConstants.IMPL_FOLDER_DESC)); cliOptions.add(new CliOption("title", "a title describing the application")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); + } @@ -60,6 +66,15 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen if (additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); } + + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); + } + + if (useBeanValidation) { + writePropertyBack(USE_BEANVALIDATION, useBeanValidation); + } + } @Override @@ -204,4 +219,9 @@ public abstract class AbstractJavaJAXRSServerCodegen extends AbstractJavaCodegen private String implFileFolder(String output) { return outputFolder + "/" + output + "/" + apiPackage().replace('.', '/'); } + + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java index f0eb365d0c8..8d9c3e6c7fc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractPhpCodegen.java @@ -251,8 +251,11 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg .replaceAll(regLastPathSeparator+ "$", ""); } - @Override - public String escapeReservedWord(String name) { + @Override + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } @@ -589,6 +592,10 @@ public abstract class AbstractPhpCodegen extends DefaultCodegen implements Codeg @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "EMPTY"; + } + // for symbol, e.g. $, # if (getSymbolName(name) != null) { return (getSymbolName(name)).toUpperCase(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java index e482fa1dd27..cd9a5fd3432 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractScalaCodegen.java @@ -67,7 +67,10 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen { } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index a5b20e2cca7..fde9717ebd0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -112,7 +112,6 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp } } - @Override public CodegenType getTag() { return CodegenType.CLIENT; @@ -120,6 +119,9 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp @Override public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } @@ -155,8 +157,8 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp @Override public String toVarName(String name) { - // should be the same as variable name - return getNameUsingModelPropertyNaming(name); + // should be the same as variable name + return getNameUsingModelPropertyNaming(name); } @Override @@ -291,6 +293,10 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "Empty"; + } + // for symbol, e.g. $, # if (getSymbolName(name) != null) { return camelize(getSymbolName(name)); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java index 8be1c1f6d50..d77763a126d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -154,6 +154,9 @@ public class AkkaScalaClientCodegen extends AbstractScalaCodegen implements Code @Override public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "`" + name + "`"; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 4fb1660db46..ba96eb2e6e9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -119,7 +119,10 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNetCoreServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNetCoreServerCodegen.java index 2045a249d97..576211f2c43 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNetCoreServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNetCoreServerCodegen.java @@ -14,8 +14,6 @@ import static java.util.UUID.randomUUID; public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { - protected String sourceFolder = "src" + File.separator + packageName; - private final String packageGuid = "{" + randomUUID().toString().toUpperCase() + "}"; @SuppressWarnings("hiding") @@ -24,6 +22,7 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { public AspNetCoreServerCodegen() { super(); + setSourceFolder("src"); outputFolder = "generated-code" + File.separator + this.getName(); modelTemplateFiles.put("model.mustache", ".cs"); @@ -91,38 +90,53 @@ public class AspNetCoreServerCodegen extends AbstractCSharpCodegen { apiPackage = packageName + ".Controllers"; modelPackage = packageName + ".Models"; + String packageFolder = sourceFolder + File.separator + packageName; + supportingFiles.add(new SupportingFile("NuGet.Config", "", "NuGet.Config")); supportingFiles.add(new SupportingFile("global.json", "", "global.json")); supportingFiles.add(new SupportingFile("build.sh.mustache", "", "build.sh")); supportingFiles.add(new SupportingFile("build.bat.mustache", "", "build.bat")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("Solution.mustache", "", this.packageName + ".sln")); - supportingFiles.add(new SupportingFile("Dockerfile.mustache", this.sourceFolder, "Dockerfile")); - supportingFiles.add(new SupportingFile("gitignore", this.sourceFolder, ".gitignore")); - supportingFiles.add(new SupportingFile("appsettings.json", this.sourceFolder, "appsettings.json")); + supportingFiles.add(new SupportingFile("Dockerfile.mustache", packageFolder, "Dockerfile")); + supportingFiles.add(new SupportingFile("gitignore", packageFolder, ".gitignore")); + supportingFiles.add(new SupportingFile("appsettings.json", packageFolder, "appsettings.json")); - supportingFiles.add(new SupportingFile("project.json.mustache", this.sourceFolder, "project.json")); - supportingFiles.add(new SupportingFile("Startup.mustache", this.sourceFolder, "Startup.cs")); - supportingFiles.add(new SupportingFile("Program.mustache", this.sourceFolder, "Program.cs")); - supportingFiles.add(new SupportingFile("web.config", this.sourceFolder, "web.config")); + supportingFiles.add(new SupportingFile("project.json.mustache", packageFolder, "project.json")); + supportingFiles.add(new SupportingFile("Startup.mustache", packageFolder, "Startup.cs")); + supportingFiles.add(new SupportingFile("Program.mustache", packageFolder, "Program.cs")); + supportingFiles.add(new SupportingFile("web.config", packageFolder, "web.config")); - supportingFiles.add(new SupportingFile("Project.xproj.mustache", this.sourceFolder, this.packageName + ".xproj")); + supportingFiles.add(new SupportingFile("Project.xproj.mustache", packageFolder, this.packageName + ".xproj")); - supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", this.sourceFolder + File.separator + "Properties", "launchSettings.json")); + supportingFiles.add(new SupportingFile("Properties" + File.separator + "launchSettings.json", packageFolder + File.separator + "Properties", "launchSettings.json")); - supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "README.md", this.sourceFolder + File.separator + "wwwroot", "README.md")); - supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "index.html", this.sourceFolder + File.separator + "wwwroot", "index.html")); - supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "web.config", this.sourceFolder + File.separator + "wwwroot", "web.config")); + supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "README.md", packageFolder + File.separator + "wwwroot", "README.md")); + supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "index.html", packageFolder + File.separator + "wwwroot", "index.html")); + supportingFiles.add(new SupportingFile("wwwroot" + File.separator + "web.config", packageFolder + File.separator + "wwwroot", "web.config")); + } + + @Override + public void setSourceFolder(final String sourceFolder) { + if(sourceFolder == null) { + LOGGER.warn("No sourceFolder specified, using default"); + this.sourceFolder = "src" + File.separator + this.packageName; + } else if(!sourceFolder.equals("src") && !sourceFolder.startsWith("src")) { + LOGGER.warn("ASP.NET Core requires source code exists under src. Adjusting."); + this.sourceFolder = "src" + File.separator + sourceFolder; + } else { + this.sourceFolder = sourceFolder; + } } @Override public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + "Controllers"; + return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Controllers"; } @Override public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + "Models"; + return outputFolder + File.separator + sourceFolder + File.separator + packageName + File.separator + "Models"; } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java new file mode 100644 index 00000000000..49cd8352866 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/BashClientCodegen.java @@ -0,0 +1,662 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.*; +import io.swagger.models.parameters.*; +import io.swagger.models.Model; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.*; +import java.io.File; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public class BashClientCodegen extends DefaultCodegen implements CodegenConfig { + + protected String apiVersion = "1.0.0"; + + protected String curlOptions; + protected boolean processMarkdown = false; + protected String scriptName = "client.sh"; + protected boolean generateBashCompletion = false; + protected boolean generateZshCompletion = false; + protected String hostEnvironmentVariable; + protected String basicAuthEnvironmentVariable; + protected String apiKeyAuthEnvironmentVariable; + + + public static final String CURL_OPTIONS = "curlOptions"; + public static final String PROCESS_MARKDOWN = "processMarkdown"; + public static final String SCRIPT_NAME = "scriptName"; + public static final String + GENERATE_BASH_COMPLETION = "generateBashCompletion"; + public static final String + GENERATE_ZSH_COMPLETION = "generateZshCompletion"; + public static final String + HOST_ENVIRONMENT_VARIABLE_NAME = "hostEnvironmentVariable"; + public static final String + BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME = "basicAuthEnvironmentVariable"; + public static final String + APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME = "apiKeyAuthEnvironmentVariable"; + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + 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 -l flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "bash"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with + * help tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates a Bash client script based on cURL."; + } + + public BashClientCodegen() { + super(); + + /** + * Set the output folder here + */ + outputFolder = "generated-code/bash"; + + /** + * No model files. + */ + modelTemplateFiles.clear(); + + + /** + * No API files. + */ + apiTemplateFiles.clear(); + + + /** + * Templates location for client script and bash completion template. + */ + embeddedTemplateDir = templateDir = "bash"; + + + /** + * Allow the user to force the script to always include certain cURL + * comamnds + */ + cliOptions.add(CliOption.newString(CURL_OPTIONS, "Default cURL options")); + cliOptions.add(CliOption.newBoolean(PROCESS_MARKDOWN, + "Convert all Markdown Markup into terminal formatting")); + cliOptions.add(CliOption.newString(SCRIPT_NAME, + "The name of the script that will be generated "+ + "(e.g. petstore-cli)")); + cliOptions.add(CliOption.newBoolean(GENERATE_BASH_COMPLETION, + "Whether to generate the Bash completion script")); + cliOptions.add(CliOption.newBoolean(GENERATE_ZSH_COMPLETION, + "Whether to generate the Zsh completion script")); + cliOptions.add(CliOption.newString(HOST_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where host can be defined "+ + "(e.g. PETSTORE_HOST='http://petstore.swagger.io:8080')")); + cliOptions.add(CliOption.newString(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where username and password " + + + "can be defined (e.g. PETSTORE_CREDS='username:password')")); + cliOptions.add(CliOption.newBoolean(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, + "Name of environment variable where API key " + + + "can be defined (e.g. PETSTORE_APIKEY='kjhasdGASDa5asdASD')")); + + /** + * Bash reserved words. + */ + reservedWords = new HashSet ( + Arrays.asList( + "case", + "do", + "done", + "elif", + "else", + "esac", + "fi", + "for", + "function", + "if", + "in", + "select", + "then", + "time", + "until", + "while") + ); + + typeMapping.clear(); + typeMapping.put("array", "array"); + typeMapping.put("map", "map"); + typeMapping.put("List", "array"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("int", "integer"); + typeMapping.put("float", "float"); + typeMapping.put("number", "integer"); + typeMapping.put("DateTime", "string"); + typeMapping.put("long", "integer"); + typeMapping.put("short", "integer"); + typeMapping.put("char", "string"); + typeMapping.put("double", "float"); + typeMapping.put("object", "map"); + typeMapping.put("integer", "integer"); + typeMapping.put("ByteArray", "string"); + typeMapping.put("binary", "binary"); + + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files. + */ + additionalProperties.put("apiVersion", apiVersion); + + /** + * Language Specific Primitives. These types will not trigger imports by + * the client generator + */ + languageSpecificPrimitives = new HashSet(); + } + + + @Override + public void processOpts() { + super.processOpts(); + String curlopts = ""; + + if (additionalProperties.containsKey(CURL_OPTIONS)) { + setCurlOptions(additionalProperties.get(CURL_OPTIONS).toString()); + additionalProperties.put("x-codegen-curl-options", curlopts); + } + + if (additionalProperties.containsKey(PROCESS_MARKDOWN)) { + setProcessMarkdown( + Boolean.parseBoolean( + additionalProperties.get(PROCESS_MARKDOWN).toString())); + } + + if (additionalProperties.containsKey(GENERATE_BASH_COMPLETION)) { + setGenerateBashCompletion( + Boolean.parseBoolean( + additionalProperties.get(GENERATE_BASH_COMPLETION).toString())); + } + + if (additionalProperties.containsKey(GENERATE_ZSH_COMPLETION)) { + setGenerateZshCompletion( + Boolean.parseBoolean( + additionalProperties.get(GENERATE_ZSH_COMPLETION).toString())); + } + + if (additionalProperties.containsKey(SCRIPT_NAME)) { + setScriptName(additionalProperties.get(SCRIPT_NAME).toString()); + } + additionalProperties.put("x-codegen-script-name", scriptName); + + if (additionalProperties.containsKey(HOST_ENVIRONMENT_VARIABLE_NAME)) { + setHostEnvironmentVariable( + additionalProperties.get(HOST_ENVIRONMENT_VARIABLE_NAME).toString()); + additionalProperties.put("x-codegen-host-env", hostEnvironmentVariable); + } + + if (additionalProperties.containsKey(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME)) { + setBasicAuthEnvironmentVariable( + additionalProperties.get(BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); + additionalProperties.put("x-codegen-basicauth-env", basicAuthEnvironmentVariable); + } + + if (additionalProperties.containsKey(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME)) { + setApiKeyAuthEnvironmentVariable( + additionalProperties.get(APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME).toString()); + additionalProperties.put("x-codegen-apikey-env", apiKeyAuthEnvironmentVariable); + } + + supportingFiles.add(new SupportingFile( + "client.mustache", "", scriptName)); + supportingFiles.add(new SupportingFile( + "bash-completion.mustache", "", scriptName+".bash-completion")); + supportingFiles.add(new SupportingFile( + "zsh-completion.mustache", "", "_"+scriptName)); + supportingFiles.add(new SupportingFile( + "README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile( + "Dockerfile.mustache", "", "Dockerfile")); + } + + public void setCurlOptions(String curlOptions) { + this.curlOptions = curlOptions; + } + + public void setProcessMarkdown(boolean processMarkdown) { + this.processMarkdown = processMarkdown; + } + + public void setScriptName(String scriptName) { + this.scriptName = scriptName; + } + + public void setGenerateBashCompletion(boolean generateBashCompletion) { + this.generateBashCompletion = generateBashCompletion; + } + + public void setGenerateZshCompletion(boolean generateZshCompletion) { + this.generateZshCompletion = generateZshCompletion; + } + + public void setHostEnvironmentVariable(String hostEnvironmentVariable) { + this.hostEnvironmentVariable = hostEnvironmentVariable; + } + + public void setBasicAuthEnvironmentVariable(String + basicAuthEnvironmentVariable) { + this.basicAuthEnvironmentVariable = basicAuthEnvironmentVariable; + } + + public void setApiKeyAuthEnvironmentVariable(String + apiKeyAuthEnvironmentVariable) { + this.apiKeyAuthEnvironmentVariable = apiKeyAuthEnvironmentVariable; + } + + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle + * escaping those terms here. This logic is only called if a variable + * matches the reseved words. + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + /** + * Location to write model files. You can use the modelPackage() as defined + * when the class is instantiated. + */ + public String modelFileFolder() { + return outputFolder; + } + + /** + * Location to write api files. You can use the apiPackage() as defined when + * the class is instantiated. + */ + @Override + public String apiFileFolder() { + return outputFolder; + } + + + /** + * Optional - type declaration. This is a String which is used by the + * templates to instantiate your types. There is typically special handling + * for different property types + * + * @return a string value used as the `dataType` field for model templates, + * `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + /** + * Optional - swagger type conversion. This is used to map swagger types in + * a `Property` into either language specific types via `typeMapping` or into + * complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + * @see io.swagger.models.properties.Property + */ + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return type; + } + else + type = swaggerType; + return toModelName(type); + } + + + /** + * Convert Swagger Parameter object to Codegen Parameter object + * + * @param param Swagger parameter object + * @param imports set of imports for library/package/module + * @return Codegen Parameter object + */ + @Override + public CodegenParameter fromParameter(Parameter param, Set imports) { + + CodegenParameter p = super.fromParameter(param, imports); + + if(param instanceof BodyParameter) { + + Model model = ((BodyParameter)param).getSchema(); + + } + else if(param instanceof SerializableParameter) { + + /** + * Currently it's not possible to specify in the codegen other collection + * formats than 'multi' + */ + SerializableParameter sparam = (SerializableParameter)param; + + if( sparam.getCollectionFormat() != null + && !sparam.getCollectionFormat().isEmpty()) { + + String collectionFormat = sparam.getCollectionFormat(); + + if(sparam.isExclusiveMaximum()!=null && sparam.isExclusiveMaximum()) { + p.vendorExtensions.put("x-codegen-collection-max-items", + sparam.getMaxItems()); + } + + if(sparam.isExclusiveMinimum()!=null && sparam.isExclusiveMinimum()) { + p.vendorExtensions.put("x-codegen-collection-min-items", + sparam.getMinItems()); + } + + if( (collectionFormat.equals("multi")) + && (param.getIn().equals("query")) ) { + + /** + * 'multi' is only supported for query parameters + */ + p.vendorExtensions.put("x-codegen-collection-multi", true); + + } + else if(collectionFormat.equals("csv")) { + p.vendorExtensions.put("x-codegen-collection-csv", true); + } + else if(collectionFormat.equals("ssv")) { + p.vendorExtensions.put("x-codegen-collection-ssv", true); + } + else if(collectionFormat.equals("tsv")) { + p.vendorExtensions.put("x-codegen-collection-tsv", true); + } + else if(collectionFormat.equals("pipes")) { + p.vendorExtensions.put("x-codegen-collection-pipes", true); + } + else { + /** Unsupported collection format */ + } + + } + + } + + return p; + + } + + /** + * Override with any special text escaping logic + */ + @SuppressWarnings("static-method") + public String escapeText(String input) { + if (input == null) { + return input; + } + + /** + * Trim the input text always. + */ + String result = input.trim(); + + /** + * remove standalone '\' + * + * replace " with \" + * outter unescape to retain the original multi-byte characters + */ + result = escapeUnsafeCharacters( + StringEscapeUtils.unescapeJava( + StringEscapeUtils.escapeJava(result).replace("\\/", "/")) + .replace("\\", "\\\\") + .replace("\"", "\\\"")); + + if(this.processMarkdown) { + + /** + * Convert markdown strong **Bold text** and __Bold text__ + * to bash bold control sequences (tput bold) + */ + result = result.replaceAll("(?m)(^|\\s)\\*{2}([\\w\\d ]+)\\*{2}($|\\s)", + "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); + + result = result.replaceAll("(?m)(^|\\s)_{2}([\\w\\d ]+)_{2}($|\\s)", + "\\$\\(tput bold\\) $2 \\$\\(tput sgr0\\)"); + /** + * Convert markdown *Italics text* and _Italics text_ to bash dim + * control sequences (tput dim) + */ + result = result.replaceAll("(?m)(^|\\s)\\*{1}([\\w\\d ]+)\\*{1}($|\\s)", + "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); + + result = result.replaceAll("(?m)(^|\\s)_{1}([\\w\\d ]+)_{1}($|\\s)", + "\\$\\(tput dim\\) $2 \\$\\(tput sgr0\\)"); + + + /** + * Convert all markdown section 1 level headers with bold + */ + result = result.replaceAll("(?m)^\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + +"$1\\$\\(tput sgr0\\)"); + + /** + * Convert all markdown section 2 level headers with bold + */ + result = result.replaceAll("(?m)^\\#\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + +"$1\\$\\(tput sgr0\\)"); + + /** + * Convert all markdown section 3 level headers with bold + */ + result = result.replaceAll("(?m)^\\#\\#\\#\\s+(.+)$", + "\n\\$\\(tput bold\\)\\$\\(tput setaf 7\\)" + +"$1\\$\\(tput sgr0\\)"); + + /** + * Convert all markdown code blocks into --- delimited sections + */ + result = result.replaceAll("(?m)\\s*```.*$", + "\n---"); + + result = result.replaceAll("(?m)\\s*\\'\\'\\'.*$", + "\n---"); + + /** + * Remove any trailing new line at the end of the string + */ + result = result.replaceAll("\\s+$", ""); + } + + return result; + } + + @Override + public String escapeQuotationMark(String input) { + return input; + } + + /** + * Override with any special text escaping logic to handle unsafe + * characters so as to avoid code injection. + * + * @param input String to be cleaned up + * @return string with unsafe characters removed or escaped + */ + public String escapeUnsafeCharacters(String input) { + + /** + * Replace backticks with normal single quotes. + */ + String result = input.replaceAll("`", "'"); + + return result; + } + + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, + Operation operation, + Map definitions, + Swagger swagger) { + + CodegenOperation op = super.fromOperation(path, httpMethod, operation, + definitions, swagger); + + /** + * Check if the operation has a Bash codegen specific description + * for help + */ + if(op.vendorExtensions.containsKey("x-bash-codegen-description")) { + String bash_description + = (String)op.vendorExtensions.get("x-bash-codegen-description"); + + op.vendorExtensions.put("x-bash-codegen-description", + escapeText(bash_description)); + } + + /** + * Check if operation has an 'x-code-samples' vendor extension with + * Shell example + */ + if(op.vendorExtensions.containsKey("x-code-samples")) { + + List codesamples = (List)op.vendorExtensions.get("x-code-samples"); + + for (Object codesample : codesamples) { + ObjectNode codesample_object = (ObjectNode)codesample; + + if((codesample_object.get("lang").asText()).equals("Shell")) { + + op.vendorExtensions.put("x-bash-codegen-sample", + escapeUnsafeCharacters( + codesample_object.get("source").asText())); + + } + + } + } + + for (CodegenParameter p : op.bodyParams) { + if(p.dataType != null && definitions.get(p.dataType) != null) { + /** + * If the operation produces Json and has nonempty example + * try to reformat it. + */ + if(operation.getConsumes() != null + && operation.getConsumes().contains("application/json") + && definitions.get(p.dataType).getExample() != null) { + + ObjectMapper mapper = new ObjectMapper(); + try { + p.vendorExtensions.put( + "x-codegen-body-example", + mapper.writerWithDefaultPrettyPrinter().writeValueAsString( + definitions.get(p.dataType).getExample())); + } + catch(JsonProcessingException e) { + e.printStackTrace(); + } + } + else { + /** + * Otherwise present whatever is provided as example + */ + p.vendorExtensions.put( + "x-codegen-body-example", + definitions.get(p.dataType).getExample()); + } + } + } + + return op; + + } + + /** + * Preprocess original properties from the Swagger definition where necessary. + * + * @param swagger [description] + */ + @Override + public void preprocessSwagger(Swagger swagger) { + super.preprocessSwagger(swagger); + + if ("/".equals(swagger.getBasePath())) { + swagger.setBasePath(""); + } + + if(swagger.getInfo() != null + && swagger.getInfo().getVendorExtensions()!=null) { + String bash_codegen_app_description + = (String)swagger.getInfo().getVendorExtensions() + .get("x-bash-codegen-description"); + + if(bash_codegen_app_description != null) { + + bash_codegen_app_description + = escapeText(bash_codegen_app_description); + + additionalProperties.put("x-bash-codegen-app-description", + bash_codegen_app_description); + + } + } + + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 26df3d83e5c..1d85e7b8ae3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -1,6 +1,9 @@ package io.swagger.codegen.languages; import com.google.common.collect.ImmutableMap; + +import com.sun.org.apache.bcel.internal.classfile.Code; + import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenType; import io.swagger.codegen.CodegenModel; @@ -45,6 +48,9 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { protected Map regexModifiers; protected final Map frameworks; + // By default, generated code is considered public + protected boolean nonPublicApi = Boolean.FALSE; + public CSharpClientCodegen() { super(); modelTemplateFiles.put("model.mustache", ".cs"); @@ -72,6 +78,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { CodegenConstants.OPTIONAL_PROJECT_GUID_DESC, null); + addOption(CodegenConstants.INTERFACE_PREFIX, + CodegenConstants.INTERFACE_PREFIX_DESC, + interfacePrefix); + CliOption framework = new CliOption( CodegenConstants.DOTNET_FRAMEWORK, CodegenConstants.DOTNET_FRAMEWORK_DESC @@ -126,6 +136,18 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { CodegenConstants.PACKAGE_DESCRIPTION_DESC, this.generatePropertyChanged); + // NOTE: This will reduce visibility of all public members in templates. Users can use InternalsVisibleTo + // https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx + // to expose to shared code if the generated code is not embedded into another project. Otherwise, users of codegen + // should rely on default public visibility. + addSwitch(CodegenConstants.NON_PUBLIC_API, + CodegenConstants.NON_PUBLIC_API_DESC, + this.nonPublicApi); + + addSwitch(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, + CodegenConstants.ALLOW_UNICODE_IDENTIFIERS_DESC, + this.allowUnicodeIdentifiers); + regexModifiers = new HashMap(); regexModifiers.put('i', "IgnoreCase"); regexModifiers.put('m', "Multiline"); @@ -228,6 +250,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { .get(CodegenConstants.OPTIONAL_ASSEMBLY_INFO).toString())); } + if (additionalProperties.containsKey(CodegenConstants.NON_PUBLIC_API)) { + setNonPublicApi(Boolean.valueOf(additionalProperties.get(CodegenConstants.NON_PUBLIC_API).toString())); + } + final String testPackageName = testPackageName(); String packageFolder = sourceFolder + File.separator + packageName; String clientPackageDir = packageFolder + File.separator + clientPackage; @@ -293,6 +319,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { if (optionalProjectFileFlag) { supportingFiles.add(new SupportingFile("Solution.mustache", "", packageName + ".sln")); supportingFiles.add(new SupportingFile("Project.mustache", packageFolder, packageName + ".csproj")); + supportingFiles.add(new SupportingFile("nuspec.mustache", packageFolder, packageName + ".nuspec")); if(Boolean.FALSE.equals(excludeTests)) { // NOTE: This exists here rather than previous excludeTests block because the test project is considered an optional project file. @@ -494,6 +521,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { @Override public String toEnumVarName(String value, String datatype) { + if (value.length() == 0) { + return "Empty"; + } + // for symbol, e.g. $, # if (getSymbolName(value) != null) { return camelize(getSymbolName(value)); @@ -547,6 +578,14 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { this.generatePropertyChanged = generatePropertyChanged; } + public boolean isNonPublicApi() { + return nonPublicApi; + } + + public void setNonPublicApi(final boolean nonPublicApi) { + this.nonPublicApi = nonPublicApi; + } + @Override public String toModelDocFilename(String name) { return toModelFilename(name); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java index 4c7cc7c1f0b..ea4c358c197 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CppRestClientCodegen.java @@ -62,7 +62,7 @@ public class CppRestClientCodegen extends DefaultCodegen implements CodegenConfi apiTemplateFiles.put("api-header.mustache", ".h"); apiTemplateFiles.put("api-source.mustache", ".cpp"); - templateDir = "cpprest"; + embeddedTemplateDir = templateDir = "cpprest"; cliOptions.clear(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java index dbcf9d70613..82d5a76a609 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java @@ -10,6 +10,8 @@ import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.codegen.CliOption; +import org.apache.commons.lang3.StringUtils; + import java.io.File; import java.util.Arrays; import java.util.HashMap; @@ -170,7 +172,10 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } @@ -230,11 +235,26 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege @Override public String toModelName(String name) { + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + name = sanitizeName(name); // model name cannot use reserved keyword, e.g. return if (isReservedWord(name)) { - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + 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)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) } // camelize the model name @@ -281,12 +301,18 @@ public class CsharpDotNet2ClientCodegen extends DefaultCodegen implements Codege @Override public String toOperationId(String operationId) { - // method name cannot use reserved keyword, e.g. return - if (isReservedWord(operationId)) { - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + // throw exception if method name is empty (should not occur as an auto-generated method name will be used) + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); } - return camelize(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))); + operationId = "call_" + operationId; + } + + return camelize(sanitizeName(operationId)); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index 8d2591f0521..d2a09a8ee3c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -174,7 +174,10 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ElixirClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ElixirClientCodegen.java new file mode 100644 index 00000000000..1a611e4d590 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ElixirClientCodegen.java @@ -0,0 +1,388 @@ +package io.swagger.codegen.languages; + +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; +import io.swagger.codegen.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import java.io.IOException; +import java.io.Writer; +import java.util.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig { + // source folder where to write the files + protected String sourceFolder = "lib"; + protected String apiVersion = "1.0.0"; + + String supportedElixirVersion = "1.4"; + List extraApplications = Arrays.asList(":logger"); + List deps = Arrays.asList( + "{:tesla, \"~> 0.5.0\"}", + "{:poison, \">= 1.0.0\"}" + ); + + + public ElixirClientCodegen() { + super(); + + // set the output folder here + outputFolder = "generated-code/elixir"; + + /** + * Models. You can write model files using the modelTemplateFiles map. + * if you want to create one template for file, you can do so here. + * for multiple files for model, just put another entry in the `modelTemplateFiles` with + * a different extension + */ + modelTemplateFiles.put( + "model.mustache", // the template to use + ".ex"); // the extension for each file to write + + /** + * Api classes. You can write classes for each Api file with the apiTemplateFiles map. + * as with models, add multiple entries with different extensions for multiple files per + * class + */ + apiTemplateFiles.put( + "api.mustache", // the template to use + ".ex"); // the extension for each file to write + + /** + * 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. + */ + templateDir = "elixir"; + + /** + * Reserved words. Override this with reserved words specific to your language + */ + reservedWords = new HashSet( + Arrays.asList( + "sample1", // replace with static values + "sample2") + ); + + /** + * Additional Properties. These values can be passed to the templates and + * are available in models, apis, and supporting files + */ + additionalProperties.put("apiVersion", apiVersion); + + /** + * Supporting Files. You can write single files for the generator with the + * entire object tree available. If the input file has a suffix of `.mustache + * it will be processed by the template engine. Otherwise, it will be copied + */ + supportingFiles.add(new SupportingFile("README.md.mustache", // the input template or file + "", // the destination folder, relative `outputFolder` + "README.md") // the output file + ); + supportingFiles.add(new SupportingFile("config.exs.mustache", + "config", + "config.exs") + ); + supportingFiles.add(new SupportingFile("mix.exs.mustache", + "", + "mix.exs") + ); + supportingFiles.add(new SupportingFile("test_helper.exs.mustache", + "test", + "test_helper.exs") + ); + + /** + * Language Specific Primitives. These types will not trigger imports by + * the client generator + */ + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "Type1", // replace these with your types + "Type2") + ); + } + + /** + * Configures the type of generator. + * + * @return the CodegenType for this generator + * @see io.swagger.codegen.CodegenType + */ + 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 -l flag. + * + * @return the friendly name for the generator + */ + public String getName() { + return "elixir"; + } + + /** + * Returns human-friendly help for the generator. Provide the consumer with help + * tips, parameters here + * + * @return A string value for the help message + */ + public String getHelp() { + return "Generates an elixir client library (alpha)."; + } + + @Override + public void processOpts() { + super.processOpts(); + additionalProperties.put("supportedElixirVersion", supportedElixirVersion); + additionalProperties.put("extraApplications", join(",", extraApplications)); + additionalProperties.put("deps", deps); + additionalProperties.put("underscored", new Mustache.Lambda() { + @Override + public void execute(Template.Fragment fragment, Writer writer) throws IOException { + writer.write(underscored(fragment.execute())); + } + }); + additionalProperties.put("modulized", new Mustache.Lambda() { + @Override + public void execute(Template.Fragment fragment, Writer writer) throws IOException { + writer.write(modulized(fragment.execute())); + } + }); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) super.postProcessOperations(objs).get("operations"); + List os = (List) operations.get("operation"); + List newOs = new ArrayList(); + Pattern pattern = Pattern.compile("(.*)\\{([^\\}]+)\\}(.*)"); + for (CodegenOperation o : os) { + ArrayList pathTemplateNames = new ArrayList(); + Matcher matcher = pattern.matcher(o.path); + StringBuffer buffer = new StringBuffer(); + while (matcher.find()) { + String pathTemplateName = matcher.group(2); + matcher.appendReplacement(buffer, "$1" + "#{" + underscore(pathTemplateName) + "}" + "$3"); + pathTemplateNames.add(pathTemplateName); + } + ExtendedCodegenOperation eco = new ExtendedCodegenOperation(o); + if (buffer.toString().isEmpty()) { + eco.setReplacedPathName(o.path); + } else { + eco.setReplacedPathName(buffer.toString()); + } + eco.setPathTemplateNames(pathTemplateNames); + newOs.add(eco); + } + operations.put("operation", newOs); + return objs; + } + + // We should use String.join if we can use Java8 + String join(CharSequence charSequence, Iterable iterable) { + StringBuilder buf = new StringBuilder(); + for (String str : iterable) { + if (0 < buf.length()) { + buf.append((charSequence)); + } + buf.append(str); + } + return buf.toString(); + } + + String underscored(String words) { + ArrayList underscoredWords = new ArrayList(); + for (String word : words.split(" ")) { + underscoredWords.add(underscore(word)); + } + return join("_", underscoredWords); + } + + String modulized(String words) { + ArrayList modulizedWords = new ArrayList(); + for (String word : words.split(" ")) { + modulizedWords.add(camelize(word)); + } + return join("", modulizedWords); + } + + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reseved words + * + * @return the escaped term + */ + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + /** + * Location to write model files. You can use the modelPackage() as defined when the class is + * instantiated + */ + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + underscored((String) additionalProperties.get("appName")) + "/" + "model"; + } + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + underscored((String) additionalProperties.get("appName")) + "/" + "api"; + } + + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "Default"; + } + return initialCaps(name); + } + + @Override + public String toApiFilename(String name) { + return snakeCase(name); + } + + @Override + public String toModelFilename(String name) { + return snakeCase(name); + } + + /** + * Optional - type declaration. This is a String which is used by the templates to instantiate your + * types. There is typically special handling for different property types + * + * @return a string value used as the `dataType` field for model templates, `returnType` for api templates + */ + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + /** + * Optional - swagger type conversion. This is used to map swagger types in a `Property` into + * either language specific types via `typeMapping` or into complex models if there is not a mapping. + * + * @return a string value of the type or complex model for this property + * @see io.swagger.models.properties.Property + */ + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return toModelName(type); + } else + type = swaggerType; + return toModelName(type); + } + + class ExtendedCodegenOperation extends CodegenOperation { + private List pathTemplateNames = new ArrayList(); + private String replacedPathName; + + public ExtendedCodegenOperation(CodegenOperation o) { + super(); + + // Copy all fields of CodegenOperation + 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.returnTypeIsPrimitive = o.returnTypeIsPrimitive; + this.returnSimpleType = o.returnSimpleType; + this.subresourceOperation = o.subresourceOperation; + this.isMapContainer = o.isMapContainer; + this.isListContainer = o.isListContainer; + this.isMultipart = o.isMultipart; + this.hasMore = o.hasMore; + this.isResponseBinary = o.isResponseBinary; + 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.path = o.path; + this.operationId = o.operationId; + this.returnType = o.returnType; + 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.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.authMethods = o.authMethods; + this.tags = o.tags; + this.responses = o.responses; + this.imports = o.imports; + this.examples = o.examples; + this.externalDocs = o.externalDocs; + this.vendorExtensions = o.vendorExtensions; + this.nickname = o.nickname; + this.operationIdLowerCase = o.operationIdLowerCase; + } + + public List getPathTemplateNames() { + return pathTemplateNames; + } + + public void setPathTemplateNames(List pathTemplateNames) { + this.pathTemplateNames = pathTemplateNames; + } + + public String getReplacedPathName() { + return replacedPathName; + } + + public void setReplacedPathName(String replacedPathName) { + this.replacedPathName = replacedPathName; + } + } + + @Override + public String escapeQuotationMark(String input) { + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + // no need to escape as Elixir does not support multi-line comments + return input; + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java index 65162cdd228..5a78713b414 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ErlangServerCodegen.java @@ -182,8 +182,11 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - return name + "_"; // add an underscore to the name + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; } /** diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java new file mode 100644 index 00000000000..4a3eed3a01b --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java @@ -0,0 +1,320 @@ +package io.swagger.codegen.languages; + +import com.google.common.base.Strings; +import io.swagger.codegen.*; +import io.swagger.models.Model; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.petstore.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "finch-server"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + protected String packageName = "io.swagger.petstore"; + + public FinchServerCodegen() { + super(); + outputFolder = "generated-code/finch"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + embeddedTemplateDir = templateDir = "finch"; + + apiPackage = packageName + ".apis"; + modelPackage = packageName + ".models"; + + setReservedWordsLowerCase( + Arrays.asList( + // Scala + "abstract", "case", "catch", "class", "def", + "do", "else", "extends", "false", "final", + "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", + "object", "override", "package", "private", "protected", + "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", + "var", "while", "with", "yield", + // Scala-interop languages keywords + "abstract", "continue", "switch", "assert", + "default", "synchronized", "goto", + "break", "double", "implements", "byte", + "public", "throws", "enum", "instanceof", "transient", + "int", "short", "char", "interface", "static", + "void", "finally", "long", "strictfp", "volatile", "const", "float", + "native") + ); + + defaultIncludes = new HashSet( + Arrays.asList("double", + "Int", + "Long", + "Float", + "Double", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "List", + "Set", + "Map") + ); + + typeMapping = new HashMap(); + typeMapping.put("string", "String"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("integer", "Int"); + typeMapping.put("float", "Float"); + typeMapping.put("long", "Long"); + typeMapping.put("double", "Double"); + typeMapping.put("number", "BigDecimal"); + typeMapping.put("date-time", "LocalDateTime"); + typeMapping.put("date", "LocalDateTime"); + typeMapping.put("file", "File"); + typeMapping.put("array", "Seq"); + typeMapping.put("list", "List"); + typeMapping.put("map", "Map"); + typeMapping.put("object", "Object"); + typeMapping.put("binary", "Array[Byte]"); + typeMapping.put("Date", "LocalDateTime"); + typeMapping.put("DateTime", "LocalDateTime"); + + additionalProperties.put("modelPackage", modelPackage()); + additionalProperties.put("apiPackage", apiPackage()); + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appDescription", "A sample swagger server"); + additionalProperties.put("infoUrl", "http://swagger.io"); + additionalProperties.put("infoEmail", "apiteam@swagger.io"); + additionalProperties.put("licenseInfo", "Apache 2.0"); + additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } else { + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + } + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); + supportingFiles.add(new SupportingFile("Server.mustache", sourceFolder, "Server.scala")); + supportingFiles.add(new SupportingFile("DataAccessor.mustache", sourceFolder, "DataAccessor.scala")); + + supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties")); + supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt")); + supportingFiles.add(new SupportingFile("sbt", "", "sbt")); + + supportingFiles.add(new SupportingFile("endpoint.mustache", sourceFolder, "endpoint.scala")); + supportingFiles.add(new SupportingFile("errors.mustache", sourceFolder, "errors.scala")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "Boolean", + "Double", + "Int", + "Integer", + "Long", + "Float", + "Any", + "AnyVal", + "AnyRef", + "Object") + ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); + + importMapping = new HashMap(); + importMapping.put("BigDecimal", "java.math.BigDecimal"); + importMapping.put("UUID", "java.util.UUID"); + importMapping.put("File", "java.io.File"); + importMapping.put("Date", "java.util.Date"); + importMapping.put("Timestamp", "java.sql.Timestamp"); + importMapping.put("Map", "scala.collection.immutable.Map"); + importMapping.put("HashMap", "scala.collection.immutable.HashMap"); + importMapping.put("Seq", "scala.collection.immutable.Seq"); + importMapping.put("ArrayBuffer", "scala.collection.mutable.ArrayBuffer"); + importMapping.put("DateTime", "java.time.LocalDateTime"); + importMapping.put("LocalDateTime", "java.time.LocalDateTime"); + importMapping.put("LocalDate", "java.time.LocalDate"); + importMapping.put("LocalTime", "java.time.LocalTime"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Finch package name (e.g. io.swagger.petstore).") + .defaultValue(this.packageName)); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "finch"; + } + + @Override + public String getHelp() { + return "Generates a Scala server application with Finch."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar); + } + + /** + * Convert Swagger Model object to Codegen Model object + * + * @param name the name of the model + * @param model Swagger Model object + * @param allDefinitions a map of all Swagger models from the spec + * @return Codegen Model object + */ + @Override + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); + return codegenModel; + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.httpMethod = op.httpMethod.toLowerCase(); + + String path = new String(op.path); + // remove first / + if (path.startsWith("/")) { + path = path.substring(1); + } + // remove last / + if (path.endsWith("/")) { + path = path.substring(0, path.length()-1); + } + + String[] items = path.split("/", -1); + String scalaPath = ""; + int pathParamIndex = 0; + + for (int i = 0; i < items.length; ++i) { + if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {} + // find the datatype of the parameter + final CodegenParameter cp = op.pathParams.get(pathParamIndex); + + // TODO: Handle non-primitives… + scalaPath = scalaPath + cp.dataType.toLowerCase(); + + pathParamIndex++; + } else { + scalaPath = scalaPath + "\"" + items[i] + "\""; + } + + if (i != items.length -1) { + scalaPath = scalaPath + " :: "; + } + } + + for (CodegenParameter p : op.allParams) { + // TODO: This hacky, should be converted to mappings if possible to keep it clean. + // This could also be done using template imports + if(Boolean.TRUE.equals(p.isPrimitiveType)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType.toLowerCase()); + p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); + } else if(Boolean.TRUE.equals(p.isBodyParam)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "jsonBody["+ p.dataType + "]"); + p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); + } else if(Boolean.TRUE.equals(p.isContainer) || Boolean.TRUE.equals(p.isListContainer)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "params(\""+ p.paramName + "\")"); + p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType.replaceAll("^[^\\[]+", "Seq")); + } else if(Boolean.TRUE.equals(p.isFile)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "fileUpload(\""+ p.paramName + "\")"); + p.vendorExtensions.put("x-codegen-normalized-input-type", "FileUpload"); + } else { + p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType); + p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); + } + } + + op.vendorExtensions.put("x-codegen-path", scalaPath); + } + return objs; + } + + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } + return toModelName(type); + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java index 2d00c8cf7a2..1a9cbdd6299 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java @@ -177,8 +177,11 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig } @Override - public String escapeReservedWord(String name) { - return name + "_"; + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java index e0c7218b723..e99a6b29e38 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlaskConnexionCodegen.java @@ -236,10 +236,13 @@ public class FlaskConnexionCodegen extends DefaultCodegen implements CodegenConf * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; // add an underscore to the name } - + /** * Location to write api files. You can use the apiPackage() as defined when the class is * instantiated diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index f6e91d1795e..dab49acd9ac 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -43,7 +43,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig { modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); - templateDir = "go"; + embeddedTemplateDir = templateDir = "go"; setReservedWordsLowerCase( Arrays.asList( @@ -180,9 +180,10 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig { // - XName // - X_Name // ... or maybe a suffix? - // - Name_ ... think this will work. - - // FIXME: This should also really be a customizable option + // - Name_ ... think this will work. + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return camelize(name) + '_'; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java index 39c544fba42..b7d2b00967a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoServerCodegen.java @@ -204,6 +204,9 @@ public class GoServerCodegen extends DefaultCodegen implements CodegenConfig { */ @Override public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; // add an underscore to the name } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java index 526ce0b10b2..97f73fcebb6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/HaskellServantCodegen.java @@ -154,8 +154,11 @@ public class HaskellServantCodegen extends DefaultCodegen implements CodegenConf * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - return name + "_"; + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; } public String firstLetterToUpper(String word) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java index 89893176493..6ebfbea6f17 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java @@ -68,7 +68,7 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig { * 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. */ - templateDir = "JMeter"; + embeddedTemplateDir = templateDir = "JMeter"; /* * Api Package. Optional, if needed, this can be used in templates @@ -119,10 +119,13 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig { * * @return the escaped term */ - @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name - } + @Override + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; + } /** * Location to write model files. You can use the modelPackage() as defined when the class is diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java index 6404f74e3a0..720cbc49331 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaCXFServerCodegen.java @@ -27,8 +27,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen protected boolean addConsumesProducesJson = true; protected boolean useJaxbAnnotations = true; - - protected boolean useBeanValidation = false; protected boolean generateSpringApplication = false; @@ -41,7 +39,7 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen protected boolean useWadlFeature = false; protected boolean useMultipartFeature = false; - + protected boolean useBeanValidationFeature = false; protected boolean generateSpringBootApplication= false; @@ -56,6 +54,10 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen protected boolean useLoggingFeatureForTests = false; + protected boolean useAnnotatedBasePath = false; + + protected boolean generateNonSpringApplication = false; + public JavaCXFServerCodegen() { super(); @@ -84,7 +86,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen cliOptions.add(CliOption.newBoolean(USE_JAXB_ANNOTATIONS, "Use JAXB annotations for XML")); - cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); cliOptions.add(CliOption.newBoolean(GENERATE_SPRING_APPLICATION, "Generate Spring application")); cliOptions.add(CliOption.newBoolean(USE_SPRING_ANNOTATION_CONFIG, "Use Spring Annotation Config")); @@ -108,6 +109,9 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen cliOptions .add(CliOption.newBoolean(ADD_CONSUMES_PRODUCES_JSON, "Add @Consumes/@Produces Json to API interface")); + cliOptions.add(CliOption.newBoolean(USE_ANNOTATED_BASE_PATH, "Use @Path annotations for basePath")); + + cliOptions.add(CliOption.newBoolean(GENERATE_NON_SPRING_APPLICATION, "Generate non-Spring application")); } @@ -121,11 +125,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen this.setUseJaxbAnnotations(useJaxbAnnotationsProp); } - if (additionalProperties.containsKey(USE_BEANVALIDATION)) { - boolean useBeanValidationProp = convertPropertyToBooleanAndWriteBack(USE_BEANVALIDATION); - this.setUseBeanValidation(useBeanValidationProp); - } - if (additionalProperties.containsKey(ADD_CONSUMES_PRODUCES_JSON)) { this.setAddConsumesProducesJson(convertPropertyToBooleanAndWriteBack(ADD_CONSUMES_PRODUCES_JSON)); } @@ -159,6 +158,16 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp); } + if (additionalProperties.containsKey(USE_ANNOTATED_BASE_PATH)) { + boolean useAnnotatedBasePathProp = convertPropertyToBooleanAndWriteBack(USE_ANNOTATED_BASE_PATH); + this.setUseAnnotatedBasePath(useAnnotatedBasePathProp); + } + + if (additionalProperties.containsKey(GENERATE_NON_SPRING_APPLICATION)) { + boolean generateNonSpringApplication = convertPropertyToBooleanAndWriteBack(GENERATE_NON_SPRING_APPLICATION); + this.setGenerateNonSpringApplication(generateNonSpringApplication); + } + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("server/pom.mustache", "", "pom.xml")); @@ -191,10 +200,12 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen (testResourcesFolder + '/'), "application.properties")); } - } - + if (this.generateNonSpringApplication) { + writeOptional(outputFolder, new SupportingFile("server/nonspring-web.mustache", + ("src/main/webapp/WEB-INF"), "web.xml")); + } } @Override @@ -224,10 +235,6 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen return "Generates a Java JAXRS Server application based on Apache CXF framework."; } - public void setUseBeanValidation(boolean useBeanValidation) { - this.useBeanValidation = useBeanValidation; - } - public void setGenerateSpringApplication(boolean generateSpringApplication) { this.generateSpringApplication = generateSpringApplication; } @@ -293,4 +300,12 @@ public class JavaCXFServerCodegen extends AbstractJavaJAXRSServerCodegen this.addConsumesProducesJson = addConsumesProducesJson; } + public void setUseAnnotatedBasePath(boolean useAnnotatedBasePath) { + this.useAnnotatedBasePath = useAnnotatedBasePath; + } + + public void setGenerateNonSpringApplication(boolean generateNonSpringApplication) { + this.generateNonSpringApplication = generateNonSpringApplication; + } + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java index be214dae514..d3895532f76 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSCXFCDIServerCodegen.java @@ -1,8 +1,10 @@ package io.swagger.codegen.languages; +import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.languages.features.BeanValidationFeatures; import java.io.File; @@ -13,7 +15,10 @@ import java.io.File; * in /src/gen/java and a sample ServiceImpl in /src/main/java. The API uses CDI * to get an instance of ServiceImpl that implements the Service interface. */ -public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen { +public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen implements BeanValidationFeatures { + + protected boolean useBeanValidation = true; + /** * Default constructor */ @@ -32,6 +37,8 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen { // Updated template directory embeddedTemplateDir = templateDir = JAXRS_TEMPLATE_DIRECTORY_NAME + File.separator + "cxf-cdi"; + + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); } @Override @@ -43,6 +50,14 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen { public void processOpts() { super.processOpts(); + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); + } + + if (useBeanValidation) { + writePropertyBack(USE_BEANVALIDATION, useBeanValidation); + } + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen // writeOptional means these files are only written if they don't already exist @@ -73,4 +88,7 @@ public class JavaJAXRSCXFCDIServerCodegen extends JavaJAXRSSpecServerCodegen { + "Apache CXF runtime and a Java EE runtime with CDI enabled."; } + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java index 7c8d03c1375..6c91e175db5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJAXRSSpecServerCodegen.java @@ -2,27 +2,30 @@ package io.swagger.codegen.languages; import java.io.File; import java.io.IOException; - import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import org.apache.commons.io.FileUtils; + import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.languages.features.BeanValidationFeatures; import io.swagger.models.Operation; import io.swagger.models.Swagger; +import io.swagger.models.properties.Property; import io.swagger.util.Json; -import org.apache.commons.io.FileUtils; -public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen -{ - public JavaJAXRSSpecServerCodegen() - { +public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen +{ + + public JavaJAXRSSpecServerCodegen() + { super(); invokerPackage = "io.swagger.api"; artifactId = "swagger-jaxrs-server"; @@ -67,26 +70,27 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen library.setEnum(supportedLibraries); cliOptions.add(library); - } - - @Override - public void processOpts() - { - super.processOpts(); - - supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen + } + + @Override + public void processOpts() + { + super.processOpts(); + + supportingFiles.clear(); // Don't need extra files provided by AbstractJAX-RS & Java Codegen writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("RestApplication.mustache", (sourceFolder + '/' + invokerPackage).replace(".", "/"), "RestApplication.java")); - } + } + - @Override - public String getName() - { - return "jaxrs-spec"; - } + @Override + public String getName() + { + return "jaxrs-spec"; + } @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { @@ -127,16 +131,16 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen model.imports.remove("JsonProperty"); } - @Override + @Override public void preprocessSwagger(Swagger swagger) { - //copy input swagger to output folder - try { - String swaggerJson = Json.pretty(swagger); + //copy input swagger to output folder + try { + String swaggerJson = Json.pretty(swagger); FileUtils.writeStringToFile(new File(outputFolder + File.separator + "swagger.json"), swaggerJson); - } catch (IOException e) { + } catch (IOException e) { throw new RuntimeException(e.getMessage(), e.getCause()); - } - super.preprocessSwagger(swagger); + } + super.preprocessSwagger(swagger); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java index b8aef14410b..8cbd3a485d5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaJerseyServerCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; +import io.swagger.codegen.languages.features.BeanValidationFeatures; import io.swagger.models.Operation; import java.util.*; @@ -12,7 +13,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { protected static final String LIBRARY_JERSEY1 = "jersey1"; protected static final String LIBRARY_JERSEY2 = "jersey2"; - + /** * Default library template to use. (Default:{@value #DEFAULT_LIBRARY}) */ @@ -84,7 +85,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { if (StringUtils.isEmpty(library)) { setLibrary(DEFAULT_LIBRARY); } - + if ( additionalProperties.containsKey(CodegenConstants.IMPL_FOLDER)) { implFolder = (String) additionalProperties.get(CodegenConstants.IMPL_FOLDER); } @@ -160,5 +161,5 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { opList.add(co); co.baseName = basePath; } - + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java index c1bd8a23cd5..7627884c407 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; +import io.swagger.codegen.languages.features.BeanValidationFeatures; import io.swagger.codegen.languages.features.JbossFeature; import io.swagger.models.Operation; import org.apache.commons.lang3.BooleanUtils; @@ -12,7 +13,7 @@ import java.util.*; public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen implements JbossFeature { protected boolean generateJbossDeploymentDescriptor = true; - + public JavaResteasyServerCodegen() { super(); @@ -58,7 +59,7 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen im GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); this.setGenerateJbossDeploymentDescriptor(generateJbossDeploymentDescriptorProp); } - + writeOptional(outputFolder, new SupportingFile("pom.mustache", "", "pom.xml")); writeOptional(outputFolder, new SupportingFile("gradle.mustache", "", "build.gradle")); writeOptional(outputFolder, new SupportingFile("settingsGradle.mustache", "", "settings.gradle")); @@ -214,7 +215,7 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen im return objs; } - + public void setGenerateJbossDeploymentDescriptor(boolean generateJbossDeploymentDescriptor) { this.generateJbossDeploymentDescriptor = generateJbossDeploymentDescriptor; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index 8a1ff5ce1d2..8b68dcdbd16 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -84,7 +84,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo modelTestTemplateFiles.put("model_test.mustache", ".js"); apiTemplateFiles.put("api.mustache", ".js"); apiTestTemplateFiles.put("api_test.mustache", ".js"); - templateDir = "Javascript"; + embeddedTemplateDir = templateDir = "Javascript"; apiPackage = "api"; modelPackage = "model"; modelDocTemplateFiles.put("model_doc.mustache", ".md"); @@ -313,7 +313,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } @@ -1021,6 +1024,10 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo @Override public String toEnumVarName(String value, String datatype) { + if (value.length() == 0) { + return "empty"; + } + // for symbol, e.g. $, # if (getSymbolName(value) != null) { return (getSymbolName(value)).toUpperCase(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java index 0b619824c4d..779f51d178b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java @@ -102,7 +102,10 @@ public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implem } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java index 3e2c3432356..ace3ccaa4e2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NancyFXServerCodegen.java @@ -1,20 +1,7 @@ package io.swagger.codegen.languages; import static com.google.common.base.Strings.isNullOrEmpty; -import static io.swagger.codegen.CodegenConstants.OPTIONAL_PROJECT_FILE; -import static io.swagger.codegen.CodegenConstants.OPTIONAL_PROJECT_FILE_DESC; -import static io.swagger.codegen.CodegenConstants.PACKAGE_NAME; -import static io.swagger.codegen.CodegenConstants.PACKAGE_VERSION; -import static io.swagger.codegen.CodegenConstants.RETURN_ICOLLECTION; -import static io.swagger.codegen.CodegenConstants.RETURN_ICOLLECTION_DESC; -import static io.swagger.codegen.CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG; -import static io.swagger.codegen.CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC; -import static io.swagger.codegen.CodegenConstants.SOURCE_FOLDER; -import static io.swagger.codegen.CodegenConstants.SOURCE_FOLDER_DESC; -import static io.swagger.codegen.CodegenConstants.USE_COLLECTION; -import static io.swagger.codegen.CodegenConstants.USE_COLLECTION_DESC; -import static io.swagger.codegen.CodegenConstants.USE_DATETIME_OFFSET; -import static io.swagger.codegen.CodegenConstants.USE_DATETIME_OFFSET_DESC; +import static io.swagger.codegen.CodegenConstants.*; import static io.swagger.codegen.CodegenType.SERVER; import static java.util.Arrays.asList; import static java.util.UUID.randomUUID; @@ -71,6 +58,9 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { outputFolder = "generated-code" + File.separator + getName(); apiTemplateFiles.put("api.mustache", ".cs"); + // Early versions use no prefix for interfaces. Defaulting to I- common practice would break existing users. + setInterfacePrefix(""); + // contextually reserved words setReservedWordsLowerCase( asList("var", "async", "await", "dynamic", "yield") @@ -82,6 +72,7 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { addOption(PACKAGE_NAME, "C# package name (convention: Title.Case).", packageName); addOption(PACKAGE_VERSION, "C# package version.", packageVersion); addOption(SOURCE_FOLDER, SOURCE_FOLDER_DESC, sourceFolder); + addOption(INTERFACE_PREFIX, INTERFACE_PREFIX_DESC, interfacePrefix); // CLI Switches addSwitch(SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_BY_REQUIRED_FLAG_DESC, sortParamsByRequiredFlag); @@ -292,6 +283,10 @@ public class NancyFXServerCodegen extends AbstractCSharpCodegen { @Override public String toEnumVarName(final String name, final String datatype) { + if (name.length() == 0) { + return "Empty"; + } + final String enumName = camelize( sanitizeName(name) .replaceFirst("^_", "") diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index 87e44d23632..bd1d988e90a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -147,13 +147,16 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig /** * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping - * those terms here. This logic is only called if a variable matches the reseved words + * those terms here. This logic is only called if a variable matches the reserved words * * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; } /** @@ -307,7 +310,12 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig if (info.getTitle() != null) { // when info.title is defined, use it for projectName // used in package.json - projectName = dashize(info.getTitle()); + projectName = info.getTitle() + .replaceAll("[^a-zA-Z0-9]", "-") + .replaceAll("^[-]*", "") + .replaceAll("[-]*$", "") + .replaceAll("[-]{2,}", "-") + .toLowerCase(); this.additionalProperties.put("projectName", projectName); } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index dd5d56e5c64..4598113c370 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -539,8 +539,17 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return toVarName(name); } + /** + * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping + * those terms here. This logic is only called if a variable matches the reserved words + * + * @return the escaped term + */ @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index db892f8a7ff..bf50765f1ca 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -109,7 +109,8 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); cliOptions.add(CliOption.newBoolean(CodegenConstants.ENSURE_UNIQUE_PARAMS, CodegenConstants .ENSURE_UNIQUE_PARAMS_DESC).defaultValue(Boolean.TRUE.toString())); - + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC) + .defaultValue(Boolean.TRUE.toString())); } @@ -134,6 +135,14 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("apiDocPath", apiDocPath); additionalProperties.put("modelDocPath", modelDocPath); + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiClient.pm")); supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Configuration.pm")); supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiFactory.pm")); @@ -162,6 +171,9 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } @@ -396,7 +408,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public void setParameterExampleValue(CodegenParameter p) { - if (Boolean.TRUE.equals(p.isString) || Boolean.TRUE.equals(p.isBinary) || + if (Boolean.TRUE.equals(p.isString) || Boolean.TRUE.equals(p.isBinary) || Boolean.TRUE.equals(p.isByteArray) || Boolean.TRUE.equals(p.isFile)) { p.example = "'" + p.example + "'"; } else if (Boolean.TRUE.equals(p.isBoolean)) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index 4748513686b..d0b6589a587 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -232,17 +232,25 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + + // Update the invokerPackage for the default apiPackage and modelPackage + apiPackage = invokerPackage + "\\" + apiDirName; + modelPackage = invokerPackage + "\\" + modelDirName; } else { additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); } - if (!additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { - additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); + if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { + // Update model package to contain the specified model package name and the invoker package + modelPackage = invokerPackage + "\\" + (String) additionalProperties.get(CodegenConstants.MODEL_PACKAGE); } + additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); - if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { - additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); + if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { + // Update model package to contain the specified model package name and the invoker package + apiPackage = invokerPackage + "\\" + (String) additionalProperties.get(CodegenConstants.API_PACKAGE); } + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); if (additionalProperties.containsKey(COMPOSER_PROJECT_NAME)) { this.setComposerProjectName((String) additionalProperties.get(COMPOSER_PROJECT_NAME)); @@ -307,7 +315,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } @@ -480,7 +491,13 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { // add prefix and/or suffic only if name does not start wth \ (e.g. \DateTime) if (!name.matches("^\\\\.*")) { - name = modelNamePrefix + name + modelNameSuffix; + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } } // camelize the model name @@ -644,6 +661,10 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "EMPTY"; + } + // number if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { String varName = name; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 8c05d6d72d6..b7983823bbd 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -251,7 +251,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java index 67df2543ad5..8c0aac51546 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Qt5CPPGenerator.java @@ -198,8 +198,11 @@ public class Qt5CPPGenerator extends DefaultCodegen implements CodegenConfig { * @return the escaped term */ @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; } /** diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java index 5147d4a5b00..dd35131cb74 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Rails5ServerCodegen.java @@ -186,7 +186,10 @@ public class Rails5ServerCodegen extends DefaultCodegen implements CodegenConfig } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index 390a06335c8..4dca4806180 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -330,7 +330,10 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } @@ -568,6 +571,10 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "EMPTY"; + } + // number if ("Integer".equals(datatype) || "Float".equals(datatype)) { String varName = name; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java index cab432e5d17..065dd8409b5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -65,7 +65,6 @@ public class ScalatraServerCodegen extends AbstractScalaCodegen implements Codeg // mapped to String as a workaround typeMapping.put("binary", "String"); - additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appDescription", "A sample swagger server"); additionalProperties.put("infoUrl", "http://swagger.io"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java index a840b77e05a..9fe6eb2b34a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SilexServerCodegen.java @@ -107,10 +107,13 @@ public class SilexServerCodegen extends DefaultCodegen implements CodegenConfig } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } - + @Override public String apiFileFolder() { return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java index e68d6c3509c..32506898bcf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java @@ -104,7 +104,10 @@ public class SinatraServerCodegen extends DefaultCodegen implements CodegenConfi } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java index 6eb5beb9e61..042dd6b1bb0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SlimFrameworkServerCodegen.java @@ -118,7 +118,10 @@ public class SlimFrameworkServerCodegen extends DefaultCodegen implements Codege } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java index 07a59155839..2a69c2cf4f7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; +import io.swagger.codegen.languages.features.BeanValidationFeatures; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; @@ -8,16 +9,18 @@ import io.swagger.models.Swagger; import java.io.File; import java.util.*; -public class SpringCodegen extends AbstractJavaCodegen { +public class SpringCodegen extends AbstractJavaCodegen implements BeanValidationFeatures { public static final String DEFAULT_LIBRARY = "spring-boot"; public static final String TITLE = "title"; public static final String CONFIG_PACKAGE = "configPackage"; public static final String BASE_PACKAGE = "basePackage"; public static final String INTERFACE_ONLY = "interfaceOnly"; + public static final String DELEGATE_PATTERN = "delegatePattern"; public static final String SINGLE_CONTENT_TYPES = "singleContentTypes"; public static final String JAVA_8 = "java8"; public static final String ASYNC = "async"; public static final String RESPONSE_WRAPPER = "responseWrapper"; + public static final String USE_TAGS = "useTags"; public static final String SPRING_MVC_LIBRARY = "spring-mvc"; public static final String SPRING_CLOUD_LIBRARY = "spring-cloud"; @@ -25,10 +28,13 @@ public class SpringCodegen extends AbstractJavaCodegen { protected String configPackage = "io.swagger.configuration"; protected String basePackage = "io.swagger"; protected boolean interfaceOnly = false; + protected boolean delegatePattern = false; protected boolean singleContentTypes = false; protected boolean java8 = false; protected boolean async = false; protected String responseWrapper = ""; + protected boolean useTags = false; + protected boolean useBeanValidation = true; public SpringCodegen() { super(); @@ -50,10 +56,13 @@ public class SpringCodegen extends AbstractJavaCodegen { cliOptions.add(new CliOption(CONFIG_PACKAGE, "configuration package for generated code")); cliOptions.add(new CliOption(BASE_PACKAGE, "base package for generated code")); cliOptions.add(CliOption.newBoolean(INTERFACE_ONLY, "Whether to generate only API interface stubs without the server files.")); + cliOptions.add(CliOption.newBoolean(DELEGATE_PATTERN, "Whether to generate the server files using the delegate pattern")); cliOptions.add(CliOption.newBoolean(SINGLE_CONTENT_TYPES, "Whether to select only one produces/consumes content-type by operation.")); cliOptions.add(CliOption.newBoolean(JAVA_8, "use java8 default interface")); cliOptions.add(CliOption.newBoolean(ASYNC, "use async Callable controllers")); cliOptions.add(new CliOption(RESPONSE_WRAPPER, "wrap the responses in given type (Future,Callable,CompletableFuture,ListenableFuture,DeferredResult,HystrixCommand,RxObservable,RxSingle or fully qualified type)")); + cliOptions.add(CliOption.newBoolean(USE_TAGS, "use tags for creating interface and controller classnames")); + cliOptions.add(CliOption.newBoolean(USE_BEANVALIDATION, "Use BeanValidation API annotations")); supportedLibraries.put(DEFAULT_LIBRARY, "Spring-boot Server application using the SpringFox integration."); supportedLibraries.put(SPRING_MVC_LIBRARY, "Spring-MVC Server application using the SpringFox integration."); @@ -121,10 +130,18 @@ public class SpringCodegen extends AbstractJavaCodegen { this.setInterfaceOnly(Boolean.valueOf(additionalProperties.get(INTERFACE_ONLY).toString())); } + if (additionalProperties.containsKey(DELEGATE_PATTERN)) { + this.setDelegatePattern(Boolean.valueOf(additionalProperties.get(DELEGATE_PATTERN).toString())); + } + if (additionalProperties.containsKey(SINGLE_CONTENT_TYPES)) { this.setSingleContentTypes(Boolean.valueOf(additionalProperties.get(SINGLE_CONTENT_TYPES).toString())); } + if (additionalProperties.containsKey(JAVA_8)) { + this.setJava8(Boolean.valueOf(additionalProperties.get(JAVA_8).toString())); + } + if (additionalProperties.containsKey(ASYNC)) { this.setAsync(Boolean.valueOf(additionalProperties.get(ASYNC).toString())); } @@ -133,9 +150,26 @@ public class SpringCodegen extends AbstractJavaCodegen { this.setResponseWrapper((String) additionalProperties.get(RESPONSE_WRAPPER)); } + if (additionalProperties.containsKey(USE_TAGS)) { + this.setUseTags(Boolean.valueOf(additionalProperties.get(USE_TAGS).toString())); + } + + if (additionalProperties.containsKey(USE_BEANVALIDATION)) { + this.setUseBeanValidation(convertPropertyToBoolean(USE_BEANVALIDATION)); + } + + if (useBeanValidation) { + writePropertyBack(USE_BEANVALIDATION, useBeanValidation); + } + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + if (this.interfaceOnly && this.delegatePattern) { + throw new IllegalArgumentException( + String.format("Can not generate code with `%s` and `%s` both true.", DELEGATE_PATTERN, INTERFACE_ONLY)); + } + if (!this.interfaceOnly) { if (library.equals(DEFAULT_LIBRARY)) { supportingFiles.add(new SupportingFile("homeController.mustache", @@ -194,6 +228,16 @@ public class SpringCodegen extends AbstractJavaCodegen { (sourceFolder + File.separator + configPackage).replace(".", java.io.File.separator), "JacksonConfiguration.java")); } } + + if (!this.delegatePattern && this.java8) { + additionalProperties.put("jdk8-no-delegate", true); + } + + + if (this.delegatePattern) { + additionalProperties.put("isDelegate", "true"); + apiTemplateFiles.put("apiDelegate.mustache", "Delegate.java"); + } if (this.java8) { additionalProperties.put("javaVersion", "1.8"); @@ -239,7 +283,7 @@ public class SpringCodegen extends AbstractJavaCodegen { @Override public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { - if(library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_MVC_LIBRARY)) { + if((library.equals(DEFAULT_LIBRARY) || library.equals(SPRING_MVC_LIBRARY)) && !useTags) { String basePath = resourcePath; if (basePath.startsWith("/")) { basePath = basePath.substring(1); @@ -408,6 +452,8 @@ public class SpringCodegen extends AbstractJavaCodegen { public void setInterfaceOnly(boolean interfaceOnly) { this.interfaceOnly = interfaceOnly; } + public void setDelegatePattern(boolean delegatePattern) { this.delegatePattern = delegatePattern; } + public void setSingleContentTypes(boolean singleContentTypes) { this.singleContentTypes = singleContentTypes; } @@ -418,6 +464,10 @@ public class SpringCodegen extends AbstractJavaCodegen { public void setResponseWrapper(String responseWrapper) { this.responseWrapper = responseWrapper; } + public void setUseTags(boolean useTags) { + this.useTags = useTags; + } + @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); @@ -462,5 +512,9 @@ public class SpringCodegen extends AbstractJavaCodegen { return objs; } + + public void setUseBeanValidation(boolean useBeanValidation) { + this.useBeanValidation = useBeanValidation; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java index 4251db48bbb..b2eb5e099b7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java @@ -77,7 +77,10 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java index 7a07ef8a58f..06c23075e8e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtml2Generator.java @@ -24,6 +24,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi protected String artifactVersion = "1.0.0"; protected String jsProjectName; protected String jsModuleName; + protected String perlModuleName = "WWW::SwaggerClient"; + protected String pythonPackageName = "swagger_client"; public StaticHtml2Generator() { super(); @@ -40,6 +42,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi cliOptions.add(new CliOption("licenseUrl", "a URL pointing to the full license")); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.PHP_INVOKER_PACKAGE, CodegenConstants.PHP_INVOKER_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.PERL_MODULE_NAME, CodegenConstants.PERL_MODULE_NAME_DESC)); + cliOptions.add(new CliOption(CodegenConstants.PYTHON_PACKAGE_NAME, CodegenConstants.PYTHON_PACKAGE_NAME_DESC)); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "C# package name")); cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); cliOptions.add(new CliOption(CodegenConstants.ARTIFACT_ID, CodegenConstants.ARTIFACT_ID_DESC)); @@ -53,6 +57,8 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.PHP_INVOKER_PACKAGE, phpInvokerPackage); + additionalProperties.put(CodegenConstants.PERL_MODULE_NAME, perlModuleName); + additionalProperties.put(CodegenConstants.PYTHON_PACKAGE_NAME, pythonPackageName); additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java index dd860291d34..79024765e1e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Swift3Codegen.java @@ -234,10 +234,13 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; // add an underscore to the name } - + @Override public String modelFileFolder() { return outputFolder + File.separator + sourceFolder + modelPackage().replace('.', File.separatorChar); @@ -450,14 +453,7 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - List parameters = operation.getParameters(); - parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { - @Override - public boolean apply(@Nullable Parameter parameter) { - return !(parameter instanceof HeaderParameter); - } - })); - operation.setParameters(parameters); + // issue 3914 - removed logic designed to remove any parameter of type HeaderParameter return super.fromOperation(path, httpMethod, operation, definitions, swagger); } @@ -512,6 +508,10 @@ public class Swift3Codegen extends DefaultCodegen implements CodegenConfig { @Override public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "empty"; + } + // for symbol, e.g. $, # if (getSymbolName(name) != null) { return camelize(WordUtils.capitalizeFully(getSymbolName(name).toUpperCase()), true); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 69c69f490a6..05e9e1a2d50 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -232,11 +232,14 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { protected boolean isReservedWord(String word) { return word != null && reservedWords.contains(word); //don't lowercase as super does } - + @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name - } + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "_" + name; // add an underscore to the name + } @Override public String modelFileFolder() { @@ -388,6 +391,10 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { @SuppressWarnings("static-method") public String toSwiftyEnumName(String value) { + if (value.length() == 0) { + return "Empty"; + } + if (value.matches("^-?\\d*\\.{0,1}\\d+.*")) { // starts with number value = "Number" + value; value = value.replaceAll("-", "Minus"); @@ -481,14 +488,7 @@ public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { @Override public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { path = normalizePath(path); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. - List parameters = operation.getParameters(); - parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { - @Override - public boolean apply(@Nullable Parameter parameter) { - return !(parameter instanceof HeaderParameter); - } - })); - operation.setParameters(parameters); + // issue 3914 - removed logic designed to remove any parameter of type HeaderParameter return super.fromOperation(path, httpMethod, operation, definitions, swagger); } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java index 3928a9316be..941a36a625c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java @@ -264,7 +264,10 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig } @Override - public String escapeReservedWord(String name) { + public String escapeReservedWord(String name) { + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } return "_" + name; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index 2853c1b379b..18c6f72e9cb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -3,6 +3,8 @@ package io.swagger.codegen.languages; import java.io.File; import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.CodegenParameter; +import io.swagger.models.properties.Property; public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCodegen { @@ -19,7 +21,10 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode @Override public void processOpts() { super.processOpts(); - supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage().replace('.', File.separatorChar), "api.d.ts")); + supportingFiles.add(new SupportingFile("models.mustache", modelPackage().replace('.', File.separatorChar), "models.ts")); + supportingFiles.add(new SupportingFile("apis.mustache", apiPackage().replace('.', File.separatorChar), "api.ts")); + supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts")); + supportingFiles.add(new SupportingFile("api.module.mustache", getIndexDirectory(), "api.module.ts")); supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); @@ -29,9 +34,56 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode super(); outputFolder = "generated-code/typescript-angular"; modelTemplateFiles.put("model.mustache", ".ts"); - apiTemplateFiles.put("api.mustache", ".ts"); + apiTemplateFiles.put("api.mustache", ".ts"); embeddedTemplateDir = templateDir = "typescript-angular"; - apiPackage = "API.Client"; - modelPackage = "API.Client"; + apiPackage = "api"; + modelPackage = "model"; } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + if(isLanguagePrimitive(swaggerType) || isLanguageGenericType(swaggerType)) { + return swaggerType; + } + return addModelPrefix(swaggerType); + } + + @Override + public void postProcessParameter(CodegenParameter parameter) { + super.postProcessParameter(parameter); + parameter.dataType = addModelPrefix(parameter.dataType); + } + + private String getIndexDirectory() { + String indexPackage = modelPackage.substring(0, Math.max(0, modelPackage.lastIndexOf('.'))); + return indexPackage.replace('.', File.separatorChar); + } + + private String addModelPrefix(String swaggerType) { + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + } else { + type = swaggerType; + } + + if (!isLanguagePrimitive(type) && !isLanguageGenericType(type)) { + type = "models." + swaggerType; + } + return type; + } + + private boolean isLanguagePrimitive(String type) { + return languageSpecificPrimitives.contains(type); + } + + private boolean isLanguageGenericType(String type) { + for (String genericType: languageGenericTypes) { + if (type.startsWith(genericType + "<")) { + return true; + } + } + return false; + } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ZendExpressivePathHandlerServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ZendExpressivePathHandlerServerCodegen.java new file mode 100644 index 00000000000..12328c64d58 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ZendExpressivePathHandlerServerCodegen.java @@ -0,0 +1,216 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.Operation; +import org.apache.commons.lang3.StringUtils; + + +import java.io.File; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ZendExpressivePathHandlerServerCodegen extends AbstractPhpCodegen { + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "ze-ph"; + } + + @Override + public String getHelp() { + return "Generates PHP server stub using Zend Expressive ( https://zendframework.github.io/zend-expressive ) and Path Handler ( https://github.com/Articus/PathHandler )."; + } + + public ZendExpressivePathHandlerServerCodegen() { + super(); + + embeddedTemplateDir = templateDir = "ze-ph"; + invokerPackage = "App"; + packagePath = ""; + srcBasePath = "src" + File.separator + "App"; + apiDirName = "Handler"; + modelDirName = "DTO"; + apiPackage = invokerPackage + "\\" + apiDirName; + modelPackage = invokerPackage + "\\" + modelDirName; + + apiTestTemplateFiles.clear(); + modelTestTemplateFiles.clear(); + apiDocTemplateFiles.clear(); + modelDocTemplateFiles.clear(); + + supportingFiles.add(new SupportingFile("README.md.mustache", packagePath, "README.md")); + supportingFiles.add(new SupportingFile("composer.json.mustache", packagePath, "composer.json")); + supportingFiles.add(new SupportingFile("index.php", packagePath + File.separator + "public", "index.php")); + supportingFiles.add(new SupportingFile("container.php", packagePath + File.separator + "application", "container.php")); + supportingFiles.add(new SupportingFile("config.yml", packagePath + File.separator + "application", "config.yml")); + supportingFiles.add(new SupportingFile("app.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "app.yml")); + supportingFiles.add(new SupportingFile("path_handler.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "path_handler.yml")); + supportingFiles.add(new SupportingFile("data_transfer.yml.mustache", packagePath + File.separator + "application" + File.separator + "config", "data_transfer.yml")); + supportingFiles.add(new SupportingFile("Date.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Strategy", "Date.php")); + supportingFiles.add(new SupportingFile("DateTime.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Strategy", "DateTime.php")); + supportingFiles.add(new SupportingFile("Type.php.mustache", packagePath + File.separator + srcBasePath + File.separator + "Validator", "Type.php")); + supportingFiles.add(new SupportingFile("ErrorMiddleware.php.mustache", packagePath + File.separator + srcBasePath, "ErrorMiddleware.php")); + + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, "1.0.0"); + } + + /** + * Add operation to group + * Override of default grouping - group by resource path, not tag + * + * @param tag name of the tag + * @param resourcePath path of the resource + * @param operation Swagger Operation object + * @param co Codegen Operation object + * @param operations map of Codegen operations + */ + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + List opList = operations.get(resourcePath); + if (opList == null) { + opList = new ArrayList(); + operations.put(resourcePath, opList); + } + //ignore duplicate operation ids - that means that operation has several tags + int counter = 0; + for (CodegenOperation op : opList) { + if (co.operationId.equals(op.operationId)) { + counter++; + } + } + if (counter == 0) { + co.operationIdLowerCase = co.operationId.toLowerCase(); + opList.add(co); + co.baseName = tag; + } + } + + /** + * 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); + } + + @Override + public Map postProcessOperations(Map objs) { + objs = super.postProcessOperations(objs); + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + String interfaceToImplement; + StringBuilder interfacesToImplement = new StringBuilder(); + String classMethod; + for (CodegenOperation op : operationList) { + switch (op.httpMethod) { + case "GET": + interfaceToImplement = "Operation\\GetInterface"; + classMethod = "handleGet"; + break; + case "POST": + interfaceToImplement = "Operation\\PostInterface"; + classMethod = "handlePost"; + break; + case "PATCH": + interfaceToImplement = "Operation\\PatchInterface"; + classMethod = "handlePatch"; + break; + case "PUT": + interfaceToImplement = "Operation\\PutInterface"; + classMethod = "handlePut"; + break; + case "DELETE": + interfaceToImplement = "Operation\\DeleteInterface"; + classMethod = "handleDelete"; + break; + default: + throw new RuntimeException("Unknown HTTP Method " + op.httpMethod + " not allowed"); + } + if (interfacesToImplement.length() > 0) { + interfacesToImplement.append(", "); + } + interfacesToImplement.append(interfaceToImplement); + op.httpMethod = classMethod; + } + operations.put("interfacesToImplement", interfacesToImplement.toString()); + + return objs; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + objs = super.postProcessSupportingFileData(objs); + + Map apiInfo = (Map) objs.get("apiInfo"); + List> apis = (List>) apiInfo.get("apis"); + + List> routes = new ArrayList>(); + for (Map api : apis) { + String handler = (String) api.get("classname"); + String url = (String) api.get("baseName"); + if (url.charAt(0) == '/') { + url = url.substring(1); + } + insertRoute(routes, url.split("/"), 0, handler); + } + + objs.put("routes", routes); + return objs; + } + + private void insertRoute(List> routes, String[] urlParts, int currentUrlPartIndex, String handler) { + if (urlParts.length > currentUrlPartIndex) { + String urlPart = urlParts[currentUrlPartIndex]; + //List> subRoutes = null; + Map currentRoute = null; + for (Map route : routes) { + if (urlPart.equals(route.get("name"))) { + currentRoute = route; + break; + } + } + if (currentRoute == null) { + currentRoute = new HashMap(); + + String routePart = urlPart.replaceAll("^\\{(\\w+)\\}$", ":$1"); + boolean isLastUrlPart = currentUrlPartIndex == urlParts.length - 1; + + currentRoute.put("name", urlPart); + currentRoute.put("route", "/" + routePart); + currentRoute.put("type", (urlPart == routePart) ? "Literal" : "Segment"); + currentRoute.put("handler", isLastUrlPart ? handler : null); + currentRoute.put("hasChildren", false); + currentRoute.put("children", new ArrayList>()); + currentRoute.put("padding", StringUtils.repeat(' ', 4 * currentUrlPartIndex)); + + routes.add(currentRoute); + } + List> subRoutes = (List>) currentRoute.get("children"); + insertRoute(subRoutes, urlParts, currentUrlPartIndex + 1, handler); + currentRoute.put("hasChildren", !subRoutes.isEmpty()); + } + } +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java index eaa012b987a..78e4f3decc9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/features/CXFServerFeatures.java @@ -15,10 +15,18 @@ public interface CXFServerFeatures public static final String ADD_CONSUMES_PRODUCES_JSON = "addConsumesProducesJson"; + public static final String USE_ANNOTATED_BASE_PATH = "useAnnotatedBasePath"; + + public static final String GENERATE_NON_SPRING_APPLICATION = "generateNonSpringApplication"; + public void setUseWadlFeature(boolean useWadlFeature); public void setUseMultipartFeature(boolean useMultipartFeature); public void setAddConsumesProducesJson(boolean addConsumesProducesJson); + public void setUseAnnotatedBasePath(boolean useAnnotatedBasePath); + + public void setGenerateNonSpringApplication(boolean generateNonSpringApplication); + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java index 52afb51c89c..27322b4554f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/utils/OptionUtils.java @@ -1,9 +1,10 @@ package io.swagger.codegen.utils; import org.apache.commons.lang3.tuple.Pair; - import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import joptsimple.internal.Strings; import static org.apache.commons.lang3.StringUtils.isNotEmpty; @@ -22,10 +23,10 @@ public class OptionUtils { results.add(pair); } } - + //Strings.isNullOrEmpty(input) return results; } - + public static List splitCommaSeparatedList(String input) { List results = new ArrayList(); @@ -39,5 +40,4 @@ public class OptionUtils { return results; } - } diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index a4267b78d97..8f5fb42cd7b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -116,6 +116,7 @@ public class ApiClient { * Build the Client used to make HTTP requests with the latest settings, * i.e. objectMapper and debugging. * TODO: better to use the Builder Pattern? + * @return API client */ public ApiClient rebuildHttpClient() { // Add the JSON serialization support to Jersey @@ -136,6 +137,7 @@ public class ApiClient { * Note: If you make changes to the object mapper, remember to set it back via * setObjectMapper in order to trigger HTTP client rebuilding. *

+ * @return Object mapper */ public ObjectMapper getObjectMapper() { return objectMapper; @@ -168,6 +170,7 @@ public class ApiClient { /** * Gets the status code of the previous request + * @return Status code */ public int getStatusCode() { return statusCode; @@ -175,6 +178,7 @@ public class ApiClient { /** * Gets the response headers of the previous request + * @return Response headers */ public Map> getResponseHeaders() { return responseHeaders; @@ -182,6 +186,7 @@ public class ApiClient { /** * Get authentications (key: authentication name, value: authentication). + * @return Map of authentication */ public Map getAuthentications() { return authentications; @@ -199,6 +204,7 @@ public class ApiClient { /** * Helper method to set username for the first HTTP basic authentication. + * @param username Username */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { @@ -212,6 +218,7 @@ public class ApiClient { /** * Helper method to set password for the first HTTP basic authentication. + * @param password Password */ public void setPassword(String password) { for (Authentication auth : authentications.values()) { @@ -225,6 +232,7 @@ public class ApiClient { /** * Helper method to set API key value for the first API key authentication. + * @param apiKey API key */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { @@ -238,6 +246,7 @@ public class ApiClient { /** * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix API key prefix */ public void setApiKeyPrefix(String apiKeyPrefix) { for (Authentication auth : authentications.values()) { @@ -251,6 +260,7 @@ public class ApiClient { /** * Helper method to set access token for the first OAuth2 authentication. + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for (Authentication auth : authentications.values()) { @@ -264,6 +274,8 @@ public class ApiClient { /** * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent User agent + * @return API client */ public ApiClient setUserAgent(String userAgent) { addDefaultHeader("User-Agent", userAgent); @@ -275,6 +287,7 @@ public class ApiClient { * * @param key The header's key * @param value The header's value + * @return API client */ public ApiClient addDefaultHeader(String key, String value) { defaultHeaderMap.put(key, value); @@ -283,6 +296,7 @@ public class ApiClient { /** * Check that whether debugging is enabled for this API client. + * @return True if debugging is on */ public boolean isDebugging() { return debugging; @@ -292,6 +306,7 @@ public class ApiClient { * Enable/disable debugging for this API client. * * @param debugging To enable (true) or disable (false) debugging + * @return API client */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; @@ -302,6 +317,7 @@ public class ApiClient { /** * Connect timeout (in milliseconds). + * @return Connection timeout */ public int getConnectTimeout() { return connectionTimeout; @@ -311,6 +327,8 @@ public class ApiClient { * Set the connect timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and * {@link Integer#MAX_VALUE}. + * @param connectionTimeout Connection timeout in milliseconds + * @return API client */ public ApiClient setConnectTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; @@ -320,6 +338,7 @@ public class ApiClient { /** * Get the date format used to parse/format date parameters. + * @return Date format */ public DateFormat getDateFormat() { return dateFormat; @@ -327,6 +346,8 @@ public class ApiClient { /** * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client */ public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; @@ -339,6 +360,8 @@ public class ApiClient { /** * Parse the given string into Date object. + * @param str String + * @return Date */ public Date parseDate(String str) { try { @@ -350,6 +373,8 @@ public class ApiClient { /** * Format the given Date object into string. + * @param date Date + * @return Date in string format */ public String formatDate(Date date) { return dateFormat.format(date); @@ -357,6 +382,8 @@ public class ApiClient { /** * Format the given parameter object into string. + * @param param Object + * @return Object in string format */ public String parameterToString(Object param) { if (param == null) { @@ -378,8 +405,12 @@ public class ApiClient { } /* - Format to {@code Pair} objects. - */ + * Format to {@code Pair} objects. + * @param collectionFormat Collection format + * @param name Name + * @param value Value + * @return List of pair + */ public List parameterToPairs(String collectionFormat, String name, Object value){ List params = new ArrayList(); @@ -439,6 +470,8 @@ public class ApiClient { * application/json * application/json; charset=UTF8 * APPLICATION/JSON + * @param mime MIME + * @return True if MIME type is boolean */ public boolean isJsonMime(String mime) { return mime != null && mime.matches("(?i)application\\/json(;.*)?"); @@ -488,6 +521,8 @@ public class ApiClient { /** * Escape the given string to be used as URL query value. + * @param str String + * @return Escaped string */ public String escapeString(String str) { try { @@ -500,6 +535,11 @@ public class ApiClient { /** * Serialize the given Java object into string according the given * Content-Type (only JSON is supported for now). + * @param obj Object + * @param contentType Content type + * @param formParams Form parameters + * @return Object + * @throws ApiException API exception */ public Object serialize(Object obj, String contentType, Map formParams) throws ApiException { if (contentType.startsWith("multipart/form-data")) { @@ -605,6 +645,7 @@ public class ApiClient { /** * Invoke API by sending HTTP request with the given options. * + * @param Type * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param queryParams The query parameters @@ -614,7 +655,9 @@ public class ApiClient { * @param accept The request's Accept header * @param contentType The request's Content-Type header * @param authNames The authentications to apply + * @param returnType Return type * @return The response body in type of string + * @throws ApiException API exception */ public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { @@ -653,6 +696,8 @@ public class ApiClient { * Update query and header parameters based on authentication settings. * * @param authNames The authentications to apply + * @param queryParams Query parameters + * @param headerParams Header parameters */ private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { for (String authName : authNames) { @@ -664,6 +709,8 @@ public class ApiClient { /** * Encode the given form parameters as request body. + * @param formParams Form parameters + * @return HTTP form encoded parameters */ private String getXWWWFormUrlencodedParams(Map formParams) { StringBuilder formParamBuilder = new StringBuilder(); diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 80db47354d0..5bf40a593f0 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -44,9 +44,13 @@ public class {{classname}} { {{#operation}} /** * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} - * @return {{{returnType}}}{{/returnType}} + * {{notes}} + {{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} + {{/allParams}} + {{#returnType}} + * @return {{returnType}} + {{/returnType}} * @throws ApiException if fails to make API call */ public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { diff --git a/modules/swagger-codegen/src/main/resources/Java/api_test.mustache b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache index 4ff7c577ac0..1d95ac2ed89 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api_test.mustache @@ -1,45 +1,45 @@ -{{>licenseInfo}} - -package {{package}}; - -import {{invokerPackage}}.ApiException; -{{#imports}}import {{import}}; -{{/imports}} -import org.junit.Test; -import org.junit.Ignore; - -{{^fullJavaUtil}} -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -{{/fullJavaUtil}} - -/** - * API tests for {{classname}} - */ -@Ignore -public class {{classname}}Test { - - private final {{classname}} api = new {{classname}}(); - - {{#operations}}{{#operation}} - /** - * {{summary}} - * - * {{notes}} - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void {{operationId}}Test() throws ApiException { - {{#allParams}} - {{{dataType}}} {{paramName}} = null; - {{/allParams}} - {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); - - // TODO: test validations - } - {{/operation}}{{/operations}} -} +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiException; +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Test; +import org.junit.Ignore; + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +@Ignore +public class {{classname}}Test { + + private final {{classname}} api = new {{classname}}(); + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void {{operationId}}Test() throws ApiException { + {{#allParams}} + {{{dataType}}} {{paramName}} = null; + {{/allParams}} + {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + // TODO: test validations + } + {{/operation}}{{/operations}} +} diff --git a/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache index 891a94b3ba1..079eab89d1a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/beanValidation.mustache @@ -32,21 +32,22 @@ {{^minItems}} {{#maxItems}} @Size(max={{maxItems}}) - {{/maxItems}} - {{/minItems}} +{{/maxItems}} +{{/minItems}} +{{! check for integer / number=decimal type}} +{{#isInteger}} {{#minimum}} - {{#isInteger}} @Min({{minimum}}) - {{/isInteger}} - {{#isLong}} - @Min({{minimum}}) - {{/isLong}} {{/minimum}} {{#maximum}} - {{#isInteger}} @Max({{maximum}}) - {{/isInteger}} - {{#isLong}} - @Max({{maximum}}) - {{/isLong}} {{/maximum}} +{{/isInteger}} +{{^isInteger}} +{{#minimum}} + @DecimalMin("{{minimum}}") +{{/minimum}} +{{#maximum}} + @DecimalMax("{{maximum}}") +{{/maximum}} +{{/isInteger}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache index 06c138c16cc..0b0ea0ff93d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache @@ -53,7 +53,7 @@ public class ApiClient { this(); for(String authName : authNames) { {{#hasAuthMethods}} RequestInterceptor auth; - {{#authMethods}}if (authName == "{{name}}") { {{#isBasic}} + {{#authMethods}}if ("{{name}}".equals(authName)) { {{#isBasic}} auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}} @@ -172,6 +172,9 @@ public class ApiClient { * apiClient.setBasePath("http://localhost:8080"); * XYZApi api = apiClient.buildClient(XYZApi.class); * XYZResponse response = api.someMethod(...); + * @param Type + * @param clientClass Client class + * @return The Client */ public T buildClient(Class clientClass) { return feignBuilder.target(clientClass, basePath); @@ -209,7 +212,7 @@ public class ApiClient { /** * Helper method to configure the first api key found - * @param apiKey + * @param apiKey API key */ public void setApiKey(String apiKey) { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -224,8 +227,8 @@ public class ApiClient { /** * Helper method to configure the username/password for basic auth or password OAuth - * @param username - * @param password + * @param username Username + * @param password Password */ public void setCredentials(String username, String password) { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -245,7 +248,7 @@ public class ApiClient { /** * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Token request builder */ public TokenRequestBuilder getTokenEndPoint() { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -259,7 +262,7 @@ public class ApiClient { /** * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Authentication request builder */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -273,8 +276,8 @@ public class ApiClient { /** * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken - * @param expiresIn : validity period in seconds + * @param accessToken Access Token + * @param expiresIn Validity period in seconds */ public void setAccessToken(String accessToken, Long expiresIn) { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -288,9 +291,9 @@ public class ApiClient { /** * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId - * @param clientSecret - * @param redirectURI + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -310,7 +313,7 @@ public class ApiClient { /** * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener + * @param accessTokenListener Acesss token listener */ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -322,14 +325,19 @@ public class ApiClient { } } + /** + * Gets request interceptor based on authentication name + * @param authName Authentiation name + * @return Request Interceptor + */ public RequestInterceptor getAuthorization(String authName) { return apiAuthorizations.get(authName); } /** * Adds an authorization to be used by the client - * @param authName - * @param authorization + * @param authName Authentication name + * @param authorization Request interceptor */ public void addAuthorization(String authName, RequestInterceptor authorization) { if (apiAuthorizations.containsKey(authName)) { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache index a72dac0496d..ce2c205ea9d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache @@ -23,8 +23,12 @@ public interface {{classname}} extends ApiClient.Api { /** * {{summary}} * {{notes}} -{{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} -{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} +{{/allParams}} +{{#returnType}} + * @return {{returnType}} +{{/returnType}} */ @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}") @Headers({ diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache index 5a2f4038df4..a9e2779b66a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -6,10 +6,12 @@ jar {{artifactId}} {{artifactVersion}} + {{artifactUrl}} + {{artifactDescription}} - scm:git:git@github.com:swagger-api/swagger-mustache.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen + {{scmConnection}} + {{scmDeveloperConnection}} + {{scmUrl}} 2.2.0 @@ -23,6 +25,15 @@ + + + {{developerName}} + {{developerEmail}} + {{developerOrganization}} + {{developerOrganizationUrl}} + + + @@ -107,9 +118,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index b81cd18d37f..5eecde91664 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -91,6 +91,7 @@ public class ApiClient { /** * Gets the JSON instance to do JSON serialization and deserialization. + * @return JSON */ public JSON getJSON() { return json; @@ -116,6 +117,7 @@ public class ApiClient { /** * Gets the status code of the previous request + * @return Status code */ public int getStatusCode() { return statusCode; @@ -123,6 +125,7 @@ public class ApiClient { /** * Gets the response headers of the previous request + * @return Response headers */ public Map> getResponseHeaders() { return responseHeaders; @@ -130,6 +133,7 @@ public class ApiClient { /** * Get authentications (key: authentication name, value: authentication). + * @return Map of authentication object */ public Map getAuthentications() { return authentications; @@ -147,6 +151,7 @@ public class ApiClient { /** * Helper method to set username for the first HTTP basic authentication. + * @param username Username */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { @@ -160,6 +165,7 @@ public class ApiClient { /** * Helper method to set password for the first HTTP basic authentication. + * @param password Password */ public void setPassword(String password) { for (Authentication auth : authentications.values()) { @@ -173,6 +179,7 @@ public class ApiClient { /** * Helper method to set API key value for the first API key authentication. + * @param apiKey API key */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { @@ -186,6 +193,7 @@ public class ApiClient { /** * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix API key prefix */ public void setApiKeyPrefix(String apiKeyPrefix) { for (Authentication auth : authentications.values()) { @@ -199,6 +207,7 @@ public class ApiClient { /** * Helper method to set access token for the first OAuth2 authentication. + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for (Authentication auth : authentications.values()) { @@ -212,6 +221,8 @@ public class ApiClient { /** * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent Http user agent + * @return API client */ public ApiClient setUserAgent(String userAgent) { addDefaultHeader("User-Agent", userAgent); @@ -223,6 +234,7 @@ public class ApiClient { * * @param key The header's key * @param value The header's value + * @return API client */ public ApiClient addDefaultHeader(String key, String value) { defaultHeaderMap.put(key, value); @@ -231,6 +243,7 @@ public class ApiClient { /** * Check that whether debugging is enabled for this API client. + * @return True if debugging is switched on */ public boolean isDebugging() { return debugging; @@ -240,6 +253,7 @@ public class ApiClient { * Enable/disable debugging for this API client. * * @param debugging To enable (true) or disable (false) debugging + * @return API client */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; @@ -253,12 +267,17 @@ public class ApiClient { * with file response. The default value is null, i.e. using * the system's default tempopary folder. * - * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) + * @return Temp folder path */ public String getTempFolderPath() { return tempFolderPath; } + /** + * Set temp folder path + * @param tempFolderPath Temp folder path + * @return API client + */ public ApiClient setTempFolderPath(String tempFolderPath) { this.tempFolderPath = tempFolderPath; return this; @@ -266,6 +285,7 @@ public class ApiClient { /** * Connect timeout (in milliseconds). + * @return Connection timeout */ public int getConnectTimeout() { return connectionTimeout; @@ -275,6 +295,8 @@ public class ApiClient { * Set the connect timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and * {@link Integer#MAX_VALUE}. + * @param connectionTimeout Connection timeout in milliseconds + * @return API client */ public ApiClient setConnectTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; @@ -284,6 +306,7 @@ public class ApiClient { /** * Get the date format used to parse/format date parameters. + * @return Date format */ public DateFormat getDateFormat() { return dateFormat; @@ -291,6 +314,8 @@ public class ApiClient { /** * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client */ public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; @@ -301,6 +326,8 @@ public class ApiClient { /** * Parse the given string into Date object. + * @param str String + * @return Date */ public Date parseDate(String str) { try { @@ -312,6 +339,8 @@ public class ApiClient { /** * Format the given Date object into string. + * @param date Date + * @return Date in string format */ public String formatDate(Date date) { return dateFormat.format(date); @@ -319,6 +348,8 @@ public class ApiClient { /** * Format the given parameter object into string. + * @param param Object + * @return Object in string format */ public String parameterToString(Object param) { if (param == null) { @@ -340,8 +371,12 @@ public class ApiClient { } /* - Format to {@code Pair} objects. - */ + * Format to {@code Pair} objects. + * @param collectionFormat Collection format + * @param name Name + * @param value Value + * @return List of pairs + */ public List parameterToPairs(String collectionFormat, String name, Object value){ List params = new ArrayList(); @@ -360,8 +395,8 @@ public class ApiClient { return params; } - // get the collection format - String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + // get the collection format (default: csv) + String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // create the params based on the collection format if ("multi".equals(format)) { @@ -401,6 +436,8 @@ public class ApiClient { * application/json * application/json; charset=UTF8 * APPLICATION/JSON + * @param mime MIME + * @return True if the MIME type is JSON */ public boolean isJsonMime(String mime) { return mime != null && mime.matches("(?i)application\\/json(;.*)?"); @@ -450,6 +487,8 @@ public class ApiClient { /** * Escape the given string to be used as URL query value. + * @param str String + * @return Escaped string */ public String escapeString(String str) { try { @@ -462,6 +501,11 @@ public class ApiClient { /** * Serialize the given Java object into string entity according the given * Content-Type (only JSON is supported for now). + * @param obj Object + * @param formParams Form parameters + * @param contentType Context type + * @return Entity + * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { Entity entity; @@ -494,6 +538,11 @@ public class ApiClient { /** * Deserialize response body to Java object according to the Content-Type. + * @param Type + * @param response Response + * @param returnType Return type + * @return Deserialize object + * @throws ApiException API exception */ @SuppressWarnings("unchecked") public T deserialize(Response response, GenericType returnType) throws ApiException { @@ -522,6 +571,8 @@ public class ApiClient { /** * Download file from the given response. + * @param response Response + * @return File * @throws ApiException If fail to read file content from response and write to disk */ public File downloadFileFromResponse(Response response) throws ApiException { @@ -578,6 +629,7 @@ public class ApiClient { /** * Invoke API by sending HTTP request with the given options. * + * @param Type * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param queryParams The query parameters @@ -589,6 +641,7 @@ public class ApiClient { * @param authNames The authentications to apply * @param returnType The return type into which to deserialize the response * @return The response body in type of string + * @throws ApiException API exception */ public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); @@ -673,6 +726,8 @@ public class ApiClient { /** * Build the Client used to make HTTP requests. + * @param debugging Debug setting + * @return Client */ private Client buildHttpClient(boolean debugging) { final ClientConfig clientConfig = new ClientConfig(); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache index 6edd703c092..b1c4e025ac9 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/JSON.mustache @@ -48,6 +48,7 @@ public class JSON implements ContextResolver { /** * Set the date format for JSON (de)serialization with Date properties. + * @param dateFormat Date format */ public void setDateFormat(DateFormat dateFormat) { mapper.setDateFormat(dateFormat); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache index 26cb9d7d946..531e56e6d4c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache @@ -41,9 +41,13 @@ public class {{classname}} { {{#operation}} /** * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} - * @return {{{returnType}}}{{/returnType}} + * {{notes}} + {{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} + {{/allParams}} + {{#returnType}} + * @return {{returnType}} + {{/returnType}} * @throws ApiException if fails to make API call */ public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache index 21f1b615eb1..cb3ba02a8a5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/pom.mustache @@ -6,10 +6,12 @@ jar {{artifactId}} {{artifactVersion}} + {{artifactUrl}} + {{artifactDescription}} - scm:git:git@github.com:swagger-api/swagger-mustache.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen + {{scmConnection}} + {{scmDeveloperConnection}} + {{scmUrl}} 2.2.0 @@ -22,7 +24,16 @@ repo - + + + + {{developerName}} + {{developerEmail}} + {{developerOrganization}} + {{developerOrganizationUrl}} + + + @@ -122,9 +133,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache index 04c3918f260..0cd19c24efa 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -1,221 +1,221 @@ -{{>licenseInfo}} - -package {{package}}; - -import {{invokerPackage}}.ApiCallback; -import {{invokerPackage}}.ApiClient; -import {{invokerPackage}}.ApiException; -import {{invokerPackage}}.ApiResponse; -import {{invokerPackage}}.Configuration; -import {{invokerPackage}}.Pair; -import {{invokerPackage}}.ProgressRequestBody; -import {{invokerPackage}}.ProgressResponseBody; -{{#performBeanValidation}} -import {{invokerPackage}}.BeanValidationException; -{{/performBeanValidation}} - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - -{{#useBeanValidation}} -import javax.validation.constraints.*; -{{/useBeanValidation}} -{{#performBeanValidation}} -import javax.validation.ConstraintViolation; -import javax.validation.Validation; -import javax.validation.ValidatorFactory; -import javax.validation.executable.ExecutableValidator; -import java.util.Set; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -{{/performBeanValidation}} - -{{#imports}}import {{import}}; -{{/imports}} - -import java.lang.reflect.Type; -{{^fullJavaUtil}} -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -{{/fullJavaUtil}} - -{{#operations}} -public class {{classname}} { - private ApiClient {{localVariablePrefix}}apiClient; - - public {{classname}}() { - this(Configuration.getDefaultApiClient()); - } - - public {{classname}}(ApiClient apiClient) { - this.{{localVariablePrefix}}apiClient = apiClient; - } - - public ApiClient getApiClient() { - return {{localVariablePrefix}}apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.{{localVariablePrefix}}apiClient = apiClient; - } - - {{#operation}} - /* Build call for {{operationId}} */ - private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - - // create path and map variables - String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}} - .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; - - {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} - - {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} - - {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}} - if ({{paramName}} != null) - {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}} - - final String[] {{localVariablePrefix}}localVarAccepts = { - {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} - }; - final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); - if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept); - - final String[] {{localVariablePrefix}}localVarContentTypes = { - {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} - }; - final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); - {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - {{^performBeanValidation}} - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) { - throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); - } - {{/required}}{{/allParams}} - - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); - return {{localVariablePrefix}}call; - - {{/performBeanValidation}} - {{#performBeanValidation}} - try { - ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); - ExecutableValidator executableValidator = factory.getValidator().forExecutables(); - - Object[] parameterValues = { {{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}} }; - Method method = this.getClass().getMethod("{{operationId}}WithHttpInfo"{{#allParams}}, {{#isListContainer}}java.util.List{{/isListContainer}}{{#isMapContainer}}java.util.Map{{/isMapContainer}}{{^isListContainer}}{{^isMapContainer}}{{{dataType}}}{{/isMapContainer}}{{/isListContainer}}.class{{/allParams}}); - Set> violations = executableValidator.validateParameters(this, method, - parameterValues); - - if (violations.size() == 0) { - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); - return {{localVariablePrefix}}call; - - } else { - throw new BeanValidationException((Set) violations); - } - } catch (NoSuchMethodException e) { - e.printStackTrace(); - throw new ApiException(e.getMessage()); - } catch (SecurityException e) { - e.printStackTrace(); - throw new ApiException(e.getMessage()); - } - - {{/performBeanValidation}} - - - - - } - - /** - * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} - * @return {{returnType}}{{/returnType}} - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} - return {{localVariablePrefix}}resp.getData();{{/returnType}} - } - - /** - * {{summary}} - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - * @return ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null); - {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); - return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} - } - - /** - * {{summary}} (asynchronously) - * {{notes}}{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); - {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); - {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} - return {{localVariablePrefix}}call; - } - {{/operation}} -} -{{/operations}} +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiCallback; +import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.ApiResponse; +import {{invokerPackage}}.Configuration; +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ProgressRequestBody; +import {{invokerPackage}}.ProgressResponseBody; +{{#performBeanValidation}} +import {{invokerPackage}}.BeanValidationException; +{{/performBeanValidation}} + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{#performBeanValidation}} +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.ValidatorFactory; +import javax.validation.executable.ExecutableValidator; +import java.util.Set; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +{{/performBeanValidation}} + +{{#imports}}import {{import}}; +{{/imports}} + +import java.lang.reflect.Type; +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{/fullJavaUtil}} + +{{#operations}} +public class {{classname}} { + private ApiClient {{localVariablePrefix}}apiClient; + + public {{classname}}() { + this(Configuration.getDefaultApiClient()); + } + + public {{classname}}(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + public ApiClient getApiClient() { + return {{localVariablePrefix}}apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + {{#operation}} + /* Build call for {{operationId}} */ + private com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + + // create path and map variables + String {{localVariablePrefix}}localVarPath = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}} + .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + {{javaUtilPrefix}}List {{localVariablePrefix}}localVarQueryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarQueryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} + + {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarHeaderParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarHeaderParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} + + {{javaUtilPrefix}}Map {{localVariablePrefix}}localVarFormParams = new {{javaUtilPrefix}}HashMap();{{#formParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}localVarFormParams.put("{{baseName}}", {{paramName}});{{/formParams}} + + final String[] {{localVariablePrefix}}localVarAccepts = { + {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + final String {{localVariablePrefix}}localVarAccept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}localVarAccepts); + if ({{localVariablePrefix}}localVarAccept != null) {{localVariablePrefix}}localVarHeaderParams.put("Accept", {{localVariablePrefix}}localVarAccept); + + final String[] {{localVariablePrefix}}localVarContentTypes = { + {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + final String {{localVariablePrefix}}localVarContentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}localVarContentTypes); + {{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] {{localVariablePrefix}}localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}localVarPath, "{{httpMethod}}", {{localVariablePrefix}}localVarQueryParams, {{localVariablePrefix}}localVarPostBody, {{localVariablePrefix}}localVarHeaderParams, {{localVariablePrefix}}localVarFormParams, {{localVariablePrefix}}localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + {{^performBeanValidation}} + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); + } + {{/required}}{{/allParams}} + + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); + return {{localVariablePrefix}}call; + + {{/performBeanValidation}} + {{#performBeanValidation}} + try { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + ExecutableValidator executableValidator = factory.getValidator().forExecutables(); + + Object[] parameterValues = { {{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}} }; + Method method = this.getClass().getMethod("{{operationId}}WithHttpInfo"{{#allParams}}, {{#isListContainer}}java.util.List{{/isListContainer}}{{#isMapContainer}}java.util.Map{{/isMapContainer}}{{^isListContainer}}{{^isMapContainer}}{{{dataType}}}{{/isMapContainer}}{{/isListContainer}}.class{{/allParams}}); + Set> violations = executableValidator.validateParameters(this, method, + parameterValues); + + if (violations.size() == 0) { + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); + return {{localVariablePrefix}}call; + + } else { + throw new BeanValidationException((Set) violations); + } + } catch (NoSuchMethodException e) { + e.printStackTrace(); + throw new ApiException(e.getMessage()); + } catch (SecurityException e) { + e.printStackTrace(); + throw new ApiException(e.getMessage()); + } + + {{/performBeanValidation}} + + + + + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}}{{#returnType}} + * @return {{returnType}}{{/returnType}} + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + {{#returnType}}ApiResponse<{{{returnType}}}> {{localVariablePrefix}}resp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + return {{localVariablePrefix}}resp.getData();{{/returnType}} + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + * @return ApiResponse<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null); + {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} + } + + /** + * {{summary}} (asynchronously) + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{/allParams}} + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener); + {{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} + return {{localVariablePrefix}}call; + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache index abec9ce20b7..40689882c2e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache @@ -6,10 +6,12 @@ jar {{artifactId}} {{artifactVersion}} + {{artifactUrl}} + {{artifactDescription}} - scm:git:git@github.com:swagger-api/swagger-mustache.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen + {{scmConnection}} + {{scmDeveloperConnection}} + {{scmUrl}} 2.2.0 @@ -22,7 +24,16 @@ repo - + + + + {{developerName}} + {{developerEmail}} + {{developerOrganization}} + {{developerOrganizationUrl}} + + + @@ -108,9 +119,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger @@ -166,7 +223,7 @@ javax.el el-api 2.2 - + {{/performBeanValidation}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache index ffbf93a48b4..30de5917a34 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache @@ -54,7 +54,7 @@ public class ApiClient { this(); for(String authName : authNames) { {{#hasAuthMethods}} Interceptor auth; - {{#authMethods}}if (authName == "{{name}}") { {{#isBasic}} + {{#authMethods}}if ("{{name}}".equals(authName)) { {{#isBasic}} auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}} @@ -68,7 +68,7 @@ public class ApiClient { /** * Basic constructor for single auth name - * @param authName + * @param authName Authentication name */ public ApiClient(String authName) { this(new String[]{authName}); @@ -76,8 +76,8 @@ public class ApiClient { /** * Helper constructor for single api key - * @param authName - * @param apiKey + * @param authName Authentication name + * @param apiKey API key */ public ApiClient(String authName, String apiKey) { this(authName); @@ -86,9 +86,9 @@ public class ApiClient { /** * Helper constructor for single basic auth or password oauth2 - * @param authName - * @param username - * @param password + * @param authName Authentication name + * @param username Username + * @param password Password */ public ApiClient(String authName, String username, String password) { this(authName); @@ -97,11 +97,11 @@ public class ApiClient { /** * Helper constructor for single password oauth2 - * @param authName - * @param clientId - * @param secret - * @param username - * @param password + * @param authName Authentication name + * @param clientId Client ID + * @param secret Client secret + * @param username Username + * @param password Password */ public ApiClient(String authName, String clientId, String secret, String username, String password) { this(authName); @@ -135,7 +135,7 @@ public class ApiClient { /** * Helper method to configure the first api key found - * @param apiKey + * @param apiKey API key */ private void setApiKey(String apiKey) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -149,8 +149,8 @@ public class ApiClient { /** * Helper method to configure the username/password for basic auth or password oauth - * @param username - * @param password + * @param username Username + * @param password Password */ private void setCredentials(String username, String password) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -169,7 +169,7 @@ public class ApiClient { /** * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Token request builder */ public TokenRequestBuilder getTokenEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -183,7 +183,7 @@ public class ApiClient { /** * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Authentication request builder */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -197,7 +197,7 @@ public class ApiClient { /** * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -211,9 +211,9 @@ public class ApiClient { /** * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId - * @param clientSecret - * @param redirectURI + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -233,7 +233,7 @@ public class ApiClient { /** * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener + * @param accessTokenListener Access token listener */ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -247,8 +247,8 @@ public class ApiClient { /** * Adds an authorization to be used by the client - * @param authName - * @param authorization + * @param authName Authentication name + * @param authorization Authorization */ public void addAuthorization(String authName, Interceptor authorization) { if (apiAuthorizations.containsKey(authName)) { @@ -286,7 +286,7 @@ public class ApiClient { /** * Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the RestAdapter - * @param okClient + * @param okClient OkHttp client */ public void configureFromOkclient(OkHttpClient okClient) { OkHttpClient clone = okClient.clone(); @@ -354,14 +354,15 @@ class GsonConverterWrapper implements Converter { */ class DateTimeTypeAdapter extends TypeAdapter { - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { - out.value(formatter.print(date)); + out.value(printFormatter.print(date)); } } @@ -373,7 +374,7 @@ class DateTimeTypeAdapter extends TypeAdapter { return null; default: String date = in.nextString(); - return formatter.parseDateTime(date); + return parseFormatter.parseDateTime(date); } } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache index e03801db6c2..9d2d003d4f4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache @@ -23,8 +23,12 @@ public interface {{classname}} { * {{summary}} * Sync method * {{notes}} -{{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} -{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} +{{/allParams}} +{{#returnType}} + * @return {{returnType}} +{{/returnType}} */ {{#formParams}}{{#-first}} {{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @@ -36,9 +40,10 @@ public interface {{classname}} { /** * {{summary}} * Async method -{{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} -{{/allParams}} * @param cb callback method - * @return void +{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} +{{/allParams}} + * @param cb callback method */ {{#formParams}}{{#-first}} {{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache index e38068e27b2..427cc514416 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache @@ -6,10 +6,12 @@ jar {{artifactId}} {{artifactVersion}} + {{artifactUrl}} + {{artifactDescription}} - scm:git:git@github.com:swagger-api/swagger-mustache.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen + {{scmConnection}} + {{scmDeveloperConnection}} + {{scmUrl}} 2.2.0 @@ -22,7 +24,16 @@ repo - + + + + {{developerName}} + {{developerEmail}} + {{developerOrganization}} + {{developerOrganizationUrl}} + + + @@ -116,9 +127,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache index e427e9fa8db..ffcccd22dcc 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/ApiClient.mustache @@ -53,7 +53,7 @@ public class ApiClient { this(); for(String authName : authNames) { {{#hasAuthMethods}} Interceptor auth; - {{#authMethods}}if (authName.equals("{{name}}")) { {{#isBasic}} + {{#authMethods}}if ("{{name}}".equals(authName)) { {{#isBasic}} auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}} @@ -401,3 +401,126 @@ class GsonCustomConverterFactory extends Converter.Factory } } +{{^java8}} +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(printFormatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return parseFormatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} +{{/java8}} +{{#java8}} +/** + * Gson TypeAdapter for jsr310 OffsetDateTime type + */ +class OffsetDateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + @Override + public void write(JsonWriter out, OffsetDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public OffsetDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + if (date.endsWith("+0000")) { + date = date.substring(0, date.length()-5) + "Z"; + } + + return OffsetDateTime.parse(date, formatter); + } + } +} + +/** + * Gson TypeAdapter for jsr310 LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE; + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return LocalDate.parse(date, formatter); + } + } +} +{{/java8}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache index 0296d4afb7a..b72af4f1703 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/api.mustache @@ -29,8 +29,10 @@ public interface {{classname}} { /** * {{summary}} * {{notes}} -{{#allParams}} * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} -{{/allParams}} * @return Call<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> +{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} +{{/allParams}} + * @return Call<{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object{{/returnType}}> */ {{#formParams}}{{#-first}} {{#isMultipart}}@retrofit2.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit2.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache index e5d402dee42..bc96393ef7d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -6,10 +6,12 @@ jar {{artifactId}} {{artifactVersion}} + {{artifactUrl}} + {{artifactDescription}} - scm:git:git@github.com:swagger-api/swagger-mustache.git - scm:git:git@github.com:swagger-api/swagger-codegen.git - https://github.com/swagger-api/swagger-codegen + {{scmConnection}} + {{scmDeveloperConnection}} + {{scmUrl}} 2.2.0 @@ -22,7 +24,16 @@ repo - + + + + {{developerName}} + {{developerEmail}} + {{developerOrganization}} + {{developerOrganizationUrl}} + + + @@ -108,9 +119,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger @@ -163,7 +220,7 @@ ${retrofit-version} {{/useRxJava}} - + {{#usePlay24WS}} @@ -185,7 +242,7 @@ com.fasterxml.jackson.core jackson-databind ${jackson-version} - + com.fasterxml.jackson.datatype jackson-datatype-{{^java8}}joda{{/java8}}{{#java8}}jsr310{{/java8}} diff --git a/modules/swagger-codegen/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache index 85890cfb190..e26feaf5d0a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -6,7 +6,13 @@ jar {{artifactId}} {{artifactVersion}} - + {{artifactUrl}} + {{artifactDescription}} + + {{scmConnection}} + {{scmDeveloperConnection}} + {{scmUrl}} + 2.2.0 @@ -19,6 +25,15 @@ + + + {{developerName}} + {{developerEmail}} + {{developerOrganization}} + {{developerOrganizationUrl}} + + + @@ -119,9 +134,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger diff --git a/modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache b/modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache index 6ef9431ff60..b3083e788d9 100644 --- a/modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/typeInfoAnnotation.mustache @@ -1,5 +1,7 @@ {{#jackson}} -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}" ) -@JsonSubTypes({ - {{#children}}@JsonSubTypes.Type(value = {{name}}.class, name = "{{name}}"),{{/children}} -}){{/jackson}} \ No newline at end of file +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}", visible = true ) +@JsonSubTypes({ + {{#children}} + @JsonSubTypes.Type(value = {{name}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), + {{/children}} +}){{/jackson}} diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache index f736844264b..56869755b79 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/pojo.mustache @@ -34,7 +34,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali return this; } - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") @JsonProperty("{{baseName}}") public {{{datatypeWithEnum}}} {{getter}}() { diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/typeInfoAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/typeInfoAnnotation.mustache new file mode 100644 index 00000000000..b3083e788d9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/typeInfoAnnotation.mustache @@ -0,0 +1,7 @@ +{{#jackson}} +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}", visible = true ) +@JsonSubTypes({ + {{#children}} + @JsonSubTypes.Type(value = {{name}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), + {{/children}} +}){{/jackson}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/StringUtil.mustache index 073966b0c21..b1b47ccc7f7 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/StringUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/StringUtil.mustache @@ -1,4 +1,4 @@ -package {{invokerPackage}}; +package {{apiPackage}}; {{>generatedAnnotation}} public class StringUtil { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index 59b71d2ba47..d70958346f2 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -22,6 +22,9 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} @Path("/{{baseName}}") {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache index 50e00e24497..eb8d9aaaa02 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache @@ -15,7 +15,9 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{>generatedAnnotation}} {{#operations}} public abstract class {{classname}}Service { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache index 3d3f4c6cbf7..bc577e6f609 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache @@ -15,7 +15,9 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{>generatedAnnotation}} {{#operations}} public class {{classname}}ServiceImpl extends {{classname}}Service { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache new file mode 100644 index 00000000000..079eab89d1a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidation.mustache @@ -0,0 +1,53 @@ +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minItems}} +{{#maxItems}} + @Size(min={{minItems}},max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{#minItems}} +{{^maxItems}} + @Size(min={{minItems}}) +{{/maxItems}} +{{/minItems}} +{{^minItems}} +{{#maxItems}} + @Size(max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{! check for integer / number=decimal type}} +{{#isInteger}} +{{#minimum}} + @Min({{minimum}}) +{{/minimum}} +{{#maximum}} + @Max({{maximum}}) +{{/maximum}} +{{/isInteger}} +{{^isInteger}} +{{#minimum}} + @DecimalMin("{{minimum}}") +{{/minimum}} +{{#maximum}} + @DecimalMax("{{maximum}}") +{{/maximum}} +{{/isInteger}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationPathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationPathParams.mustache new file mode 100644 index 00000000000..e3060fa6c6a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationQueryParams.mustache new file mode 100644 index 00000000000..52440b12218 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache index 5fabe593164..0586b6df351 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache @@ -12,11 +12,15 @@ import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import io.swagger.annotations.*; +import java.io.InputStream; import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; import java.util.List; - +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} @Path("/{{baseName}}") @RequestScoped @@ -48,7 +52,7 @@ public class {{classname}} { @ApiResponses(value = { {{#responses}} @ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}},{{/hasMore}}{{/responses}} }) public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - return delegate.{{nickname}}({{#allParams}}{{#isFile}}inputStream, fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}, {{/allParams}}securityContext); + return delegate.{{nickname}}({{#allParams}}{{#isFile}}{{paramName}}InputStream, {{paramName}}Detail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}, {{/allParams}}securityContext); } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache index 64eb6e38adb..4af44698b7c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache @@ -4,6 +4,7 @@ import {{package}}.*; import {{modelPackage}}.*; import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; {{#imports}}import {{import}}; {{/imports}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidation.mustache new file mode 100644 index 00000000000..c8c6946fef6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidation.mustache @@ -0,0 +1,4 @@ +{{#required}} + @NotNull +{{/required}} +{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationCore.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationCore.mustache new file mode 100644 index 00000000000..dc7a8392216 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationCore.mustache @@ -0,0 +1,20 @@ +{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{! +minLength && maxLength set +}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{! +minLength set, maxLength not +}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{! +minLength not set, maxLength set +}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{! +@Size: minItems && maxItems set +}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{! +@Size: minItems set, maxItems not +}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{! +@Size: minItems not set && maxItems set +}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{! +check for integer or long / all others=decimal type with @Decimal* +isInteger set +}}{{#isInteger}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}{{/isInteger}}{{! +isLong set +}}{{#isLong}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}}{{/isLong}}{{! +Not Integer, not Long => we have a decimal value! +}}{{^isInteger}}{{^isLong}}{{#minimum}} @DecimalMin("{{minimum}}"){{/minimum}}{{#maximum}} @DecimalMax("{{maximum}}"){{/maximum}}{{/isLong}}{{/isInteger}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationPathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationPathParams.mustache new file mode 100644 index 00000000000..051bd53c0a5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationQueryParams.mustache new file mode 100644 index 00000000000..f8eef8f94c7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/enumClass.mustache index 1ef4a61efbe..10bb9d0f4e0 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/enumClass.mustache @@ -1,16 +1,33 @@ -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlType; +@XmlType(name="{{datatypeWithEnum}}") +@XmlEnum({{datatype}}.class) +public enum {{datatypeWithEnum}} { + + {{#allowableValues}} + {{#enumVars}}@XmlEnumValue({{{value}}}) {{name}}({{datatype}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{/allowableValues}} + + + private {{datatype}} value; + + {{datatypeWithEnum}} ({{datatype}} v) { + value = v; + } -@XmlType(name="{{classname}}") -@XmlEnum -public enum {{classname}} { - {{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/allowableValues}} - public String value() { - return name(); + return value; } - public static {{classname}} fromValue(String v) { - return valueOf(v); + @Override + public String toString() { + return String.valueOf(value); } -} \ No newline at end of file + + public static {{datatypeWithEnum}} fromValue(String v) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/generatedAnnotation.mustache index 49110fc1ad9..a47b6faa85b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/generatedAnnotation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/generatedAnnotation.mustache @@ -1 +1 @@ -@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file +{{^hideGenerationTimestamp}}@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}"){{/hideGenerationTimestamp}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache index 2c383a41a28..225cfd719cc 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache @@ -2,7 +2,9 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} - +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#models}} {{#model}}{{#description}} /** diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pathParams.mustache index 8d80210b4b4..4e21dd6091e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache index f1d68d014e7..93f920d4d12 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache @@ -1,5 +1,8 @@ import io.swagger.annotations.*; import java.util.Objects; + +import javax.xml.bind.annotation.*; + {{#description}}@ApiModel(description = "{{{description}}}"){{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { @@ -21,10 +24,10 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali return this; } - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") @JsonProperty("{{baseName}}") - public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache index a5a683b9748..eba993f83fc 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache @@ -76,6 +76,16 @@ swagger-annotations [1.5.3,2) + +{{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/queryParams.mustache index 6bff4a4b82d..c1c9e8b45cb 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf-cdi/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{#defaultValue}}@DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{#defaultValue}}@DefaultValue("{{{defaultValue}}}"){{/defaultValue}} @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache index 47062c394d2..b15a8797154 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/api.mustache @@ -1,44 +1,45 @@ -package {{package}}; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import javax.ws.rs.*; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.MediaType; -import org.apache.cxf.jaxrs.ext.multipart.*; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -{{#useBeanValidation}} -import javax.validation.constraints.*; -{{/useBeanValidation}} - -@Path("/") -@Api(value = "/", description = "{{description}}") -{{#addConsumesProducesJson}} -@Consumes(MediaType.APPLICATION_JSON) -@Produces(MediaType.APPLICATION_JSON) -{{/addConsumesProducesJson}} -public interface {{classname}} { -{{#operations}} -{{#operation}} - - @{{httpMethod}} - {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} -{{#hasConsumes}} - @Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }) -{{/hasConsumes}} -{{#hasProduces}} - @Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }) -{{/hasProduces}} - @ApiOperation(value = "{{summary}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) - public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); -{{/operation}} -} -{{/operations}} - +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.jaxrs.PATCH; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} + +@Path("{{^useAnnotatedBasePath}}/{{/useAnnotatedBasePath}}{{#useAnnotatedBasePath}}{{contextPath}}{{/useAnnotatedBasePath}}") +@Api(value = "/", description = "{{description}}") +{{#addConsumesProducesJson}} +@Consumes(MediaType.APPLICATION_JSON) +@Produces(MediaType.APPLICATION_JSON) +{{/addConsumesProducesJson}} +public interface {{classname}} { +{{#operations}} +{{#operation}} + + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} +{{#hasConsumes}} + @Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }) +{{/hasConsumes}} +{{#hasProduces}} + @Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }) +{{/hasProduces}} + @ApiOperation(value = "{{{summary}}}", tags={ {{#vendorExtensions.x-tags}}"{{tag}}"{{#hasMore}}, {{/hasMore}}{{/vendorExtensions.x-tags}} }) + public {{>returnTypes}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); +{{/operation}} +} +{{/operations}} + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidation.mustache index f13ed596859..079eab89d1a 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/beanValidation.mustache @@ -32,11 +32,22 @@ {{^minItems}} {{#maxItems}} @Size(max={{maxItems}}) - {{/maxItems}} - {{/minItems}} +{{/maxItems}} +{{/minItems}} +{{! check for integer / number=decimal type}} +{{#isInteger}} {{#minimum}} @Min({{minimum}}) {{/minimum}} {{#maximum}} @Max({{maximum}}) -{{/maximum}} \ No newline at end of file +{{/maximum}} +{{/isInteger}} +{{^isInteger}} +{{#minimum}} + @DecimalMin("{{minimum}}") +{{/minimum}} +{{#maximum}} + @DecimalMax("{{maximum}}") +{{/maximum}} +{{/isInteger}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache index 10bb9d0f4e0..d5a92dd3e74 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/enumClass.mustache @@ -3,7 +3,7 @@ public enum {{datatypeWithEnum}} { {{#allowableValues}} - {{#enumVars}}@XmlEnumValue({{{value}}}) {{name}}({{datatype}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} +{{#enumVars}}@XmlEnumValue({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) {{name}}({{datatype}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} {{/allowableValues}} @@ -13,7 +13,7 @@ public enum {{datatypeWithEnum}} { value = v; } - public String value() { + public {{datatype}} value() { return value; } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache index b959ce17c15..09c8fc1fecc 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -19,14 +19,14 @@ import javax.xml.bind.annotation.XmlEnumValue; @ApiModel(description="{{{description}}}") {{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { - {{#vars}}{{#isEnum}} + {{#vars}}{{#isEnum}}{{^isContainer}} -{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} +{{>enumClass}}{{/isContainer}}{{/isEnum}}{{#items.isEnum}}{{#items}} -{{>enumClass}}{{/items}}{{/items.isEnum}} +{{^isContainer}}{{>enumClass}}{{/isContainer}}{{/items}}{{/items.isEnum}} {{#useJaxbAnnotations}} - @XmlElement(name="{{baseName}}") -{{/useJaxbAnnotations}} + @XmlElement(name="{{baseName}}"{{#required}}, required = {{required}}{{/required}}) +{{/useJaxbAnnotations}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} @@ -47,14 +47,37 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { * @return {{name}} **/ {{#vendorExtensions.extraAnnotation}} - {{vendorExtensions.extraAnnotation}} + {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} {{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } + + {{^isReadOnly}} public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { this.{{name}} = {{name}}; } + + public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + return this; + } + {{#isListContainer}} + + public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.add({{name}}Item); + return this; + } + {{/isListContainer}} + {{#isMapContainer}} + + public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + this.{{name}}.put(key, {{name}}Item); + return this; + } + {{/isMapContainer}} + {{/isReadOnly}} + {{/vars}} @Override diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/nonspring-web.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/nonspring-web.mustache new file mode 100644 index 00000000000..4542e024b87 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/nonspring-web.mustache @@ -0,0 +1,26 @@ + + + + + CXF Non-Spring Jaxrs Servlet + CXFNonSpringJaxrsServlet + org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet +{{#apiInfo}} + + jaxrs.serviceClasses + {{#apis}}{{package}}.impl.{{classname}}ServiceImpl{{^-last}},{{/-last}}{{/apis}} + +{{/apiInfo}} + + jaxrs.providers + com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider + + + + + CXFNonSpringJaxrsServlet + /rest/* + + + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/swagger-codegen-ignore.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/swagger-codegen-ignore.mustache index ec46bbd69c0..70b88e71039 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/swagger-codegen-ignore.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/cxf/server/swagger-codegen-ignore.mustache @@ -1,25 +1,25 @@ -# Swagger Codegen Ignore -# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen - -# 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 Swagger Codgen 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 - +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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 + **/impl/* \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache index 59074d1af13..e77215600f0 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/api.mustache @@ -8,6 +8,9 @@ import io.swagger.annotations.ApiParam; import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#imports}}import {{import}}; {{/imports}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache index 2cc7b8c1fec..0d3ab0ebe17 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache @@ -18,7 +18,9 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{>generatedAnnotation}} {{#operations}} public abstract class {{classname}}Service { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache index f4c558e7b11..abe789f1cbf 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache @@ -18,7 +18,9 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{>generatedAnnotation}} {{#operations}} public class {{classname}}ServiceImpl extends {{classname}}Service { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache index d21444dda26..26b934f2722 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/libraries/jersey1/pom.mustache @@ -158,6 +158,15 @@ +{{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache index b84bfee6a85..1d4785dda12 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -13,6 +13,9 @@ import org.apache.commons.lang3.ObjectUtils; {{#serializableModel}} import java.io.Serializable; {{/serializableModel}} +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#models}} {{#model}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache index f3a36ecc387..1eb2c684f0c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pojo.mustache @@ -64,10 +64,13 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * @return {{name}} **/ {{#vendorExtensions.extraAnnotation}} - {{vendorExtensions.extraAnnotation}} + {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} + {{#jackson}} + @JsonProperty("{{baseName}}") + {{/jackson}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } {{^isReadOnly}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index 19cbd0a95ad..d5ff9b0055a 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -153,6 +153,16 @@ ${commons_io_version} {{/supportJava6}} + +{{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache index 1acd56c60fc..af53a9aa4b1 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/api.mustache @@ -4,6 +4,9 @@ import {{modelPackage}}.*; import {{package}}.{{classname}}Service; import {{package}}.factories.{{classname}}ServiceFactory; +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + {{#imports}}import {{import}}; {{/imports}} @@ -16,6 +19,9 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#operations}}{{#operation}}{{#isMultipart}}import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; {{/isMultipart}}{{/operation}}{{/operations}} @Path("/{{baseName}}") @@ -33,9 +39,9 @@ public class {{classname}} { {{#hasConsumes}}@Consumes({ {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { - {{#authMethods}}@io.swagger.annotations.Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { + {{#authMethods}}@io.swagger.annotations.Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { {{#scopes}}@io.swagger.annotations.AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, - {{/hasMore}}{{/scopes}} + {{/hasMore}}{{/scopes}} }{{/isOAuth}}){{#hasMore}}, {{/hasMore}}{{/authMethods}} }{{/hasAuthMethods}}, tags={ {{#vendorExtensions.x-tags}}"{{tag}}",{{/vendorExtensions.x-tags}} }) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidation.mustache new file mode 100644 index 00000000000..079eab89d1a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidation.mustache @@ -0,0 +1,53 @@ +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minItems}} +{{#maxItems}} + @Size(min={{minItems}},max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{#minItems}} +{{^maxItems}} + @Size(min={{minItems}}) +{{/maxItems}} +{{/minItems}} +{{^minItems}} +{{#maxItems}} + @Size(max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{! check for integer / number=decimal type}} +{{#isInteger}} +{{#minimum}} + @Min({{minimum}}) +{{/minimum}} +{{#maximum}} + @Max({{maximum}}) +{{/maximum}} +{{/isInteger}} +{{^isInteger}} +{{#minimum}} + @DecimalMin("{{minimum}}") +{{/minimum}} +{{#maximum}} + @DecimalMax("{{maximum}}") +{{/maximum}} +{{/isInteger}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationPathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationPathParams.mustache new file mode 100644 index 00000000000..e3060fa6c6a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationQueryParams.mustache new file mode 100644 index 00000000000..52440b12218 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/bodyParams.mustache index bb1d6ff4ef0..2b28441d3d0 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/bodyParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}} {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/formParams.mustache index 7494e6a00ad..09c149b8ade 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/formParams.mustache @@ -1 +1 @@ -{{#isFormParam}}{{#notFile}}@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/headerParams.mustache index 25d690c90ed..1360d796826 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@HeaderParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}}{{#allowableValues}}, {{> allowableValues }}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache index 916d909c546..2ff294581f5 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/model.mustache @@ -7,7 +7,9 @@ import java.util.ArrayList; {{#serializableModel}} import java.io.Serializable; {{/serializableModel}} - +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#models}} {{#model}} {{#isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pathParams.mustache index 39116c805cb..0cd6809df54 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}} @PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}} @PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache index 63578d8bc73..4c84bc6e6a0 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pojo.mustache @@ -1,10 +1,13 @@ +import io.swagger.annotations.*; + +{{#description}}@ApiModel(description="{{{description}}}"){{/description}} {{>generatedAnnotation}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { - {{#vars}}{{#isEnum}} + {{#vars}}{{#isEnum}}{{^isContainer}} -{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} +{{>enumClass}}{{/isContainer}}{{/isEnum}}{{#items.isEnum}}{{#items}} -{{>enumClass}}{{/items}}{{/items.isEnum}} +{{^isContainer}}{{>enumClass}}{{/isContainer}}{{/items}}{{/items.isEnum}} private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} {{#vars}} @@ -13,9 +16,10 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} **/ - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} + @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") @JsonProperty("{{baseName}}") - public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache index 3986f8fbed1..c6d1011af1f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/pom.mustache @@ -143,6 +143,16 @@ +{{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache index 458b8de7c3b..5a9a4398a03 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/resteasy/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}} @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}} @QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache index 6829cf8c7a6..07b519cba5e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache index ff79730471d..e3fd6c6ce76 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/api.mustache index 5ffd9c2a6d3..088e254300b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/api.mustache @@ -9,6 +9,9 @@ import javax.ws.rs.core.Response; import io.swagger.annotations.*; import java.util.List; +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} @Path("/{{baseName}}") diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidation.mustache new file mode 100644 index 00000000000..079eab89d1a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidation.mustache @@ -0,0 +1,53 @@ +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minItems}} +{{#maxItems}} + @Size(min={{minItems}},max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{#minItems}} +{{^maxItems}} + @Size(min={{minItems}}) +{{/maxItems}} +{{/minItems}} +{{^minItems}} +{{#maxItems}} + @Size(max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{! check for integer / number=decimal type}} +{{#isInteger}} +{{#minimum}} + @Min({{minimum}}) +{{/minimum}} +{{#maximum}} + @Max({{maximum}}) +{{/maximum}} +{{/isInteger}} +{{^isInteger}} +{{#minimum}} + @DecimalMin("{{minimum}}") +{{/minimum}} +{{#maximum}} + @DecimalMax("{{maximum}}") +{{/maximum}} +{{/isInteger}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationPathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationPathParams.mustache new file mode 100644 index 00000000000..e3060fa6c6a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationQueryParams.mustache new file mode 100644 index 00000000000..52440b12218 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumClass.mustache index 1ef4a61efbe..a9d67c0471e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumClass.mustache @@ -1,16 +1,31 @@ -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlType; +public enum {{datatypeWithEnum}} { + + {{#allowableValues}} + {{#enumVars}}{{name}}({{datatype}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{/allowableValues}} + + + private {{datatype}} value; + + {{datatypeWithEnum}} ({{datatype}} v) { + value = v; + } -@XmlType(name="{{classname}}") -@XmlEnum -public enum {{classname}} { - {{#allowableValues}}{{.}}{{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/allowableValues}} - public String value() { - return name(); + return value; } - public static {{classname}} fromValue(String v) { - return valueOf(v); + @Override + public String toString() { + return String.valueOf(value); } -} \ No newline at end of file + + public static {{datatypeWithEnum}} fromValue(String v) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumOuterClass.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumOuterClass.mustache new file mode 100644 index 00000000000..85de81431b6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/enumOuterClass.mustache @@ -0,0 +1,43 @@ +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +{{/jackson}} + +/** + * {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + */ +public enum {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#gson}} + {{#allowableValues}}{{#enumVars}} + @SerializedName({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + {{^gson}} + {{#allowableValues}}{{#enumVars}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{/gson}} + + private {{{dataType}}} value; + + {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue(String text) { + for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/formParams.mustache index b1036ceeb54..e88e3022aa7 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/formParams.mustache @@ -1,2 +1,2 @@ -{{#isFormParam}}{{#notFile}}@FormParam(value = "{{paramName}}"{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @FormParam(value = "{{paramName}}"{{^required}}, required = false{{/required}}) InputStream {{paramName}}InputStream, - @FormParam(value = "{{paramName}}" {{^required}}, required = false{{/required}}) Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file +{{#isFormParam}}{{#notFile}}@FormParam(value = "{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}} @FormParam(value = "{{paramName}}") InputStream {{paramName}}InputStream, + @FormParam(value = "{{paramName}}") Attachment {{paramName}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/generatedAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/generatedAnnotation.mustache index 49110fc1ad9..ad17a426e96 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/generatedAnnotation.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/generatedAnnotation.mustache @@ -1 +1,3 @@ -@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") \ No newline at end of file +{{^hideGenerationTimestamp}} +@javax.annotation.Generated(value = "{{generatorClass}}", date = "{{generatedDate}}") +{{/hideGenerationTimestamp}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/model.mustache index 2c383a41a28..a93761806d2 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/model.mustache @@ -2,13 +2,18 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#models}} {{#model}}{{#description}} /** * {{description}} **/{{/description}} -{{#isEnum}}{{>enumClass}}{{/isEnum}} +{{#isEnum}} +{{>enumOuterClass}} +{{/isEnum}} {{^isEnum}}{{>pojo}}{{/isEnum}} {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pathParams.mustache index ba153467a65..f01e18d3523 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}@PathParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}@PathParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}{{#description}} @ApiParam("{{description}}"){{/description}} {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache index f5657c2d33f..51090c995e1 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pojo.mustache @@ -3,11 +3,11 @@ import java.util.Objects; {{#description}}@ApiModel(description = "{{{description}}}"){{/description}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { - {{#vars}}{{#isEnum}} + {{#vars}}{{#isEnum}}{{^isContainer}} -{{>enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} +{{>enumClass}}{{/isContainer}}{{/isEnum}}{{#items.isEnum}}{{#items}} -{{>enumClass}}{{/items}}{{/items.isEnum}} +{{^isContainer}}{{>enumClass}}{{/isContainer}}{{/items}}{{/items.isEnum}} private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/vars}} {{#vars}} @@ -21,9 +21,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali return this; } - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - public {{{datatypeWithEnum}}} {{getter}}() { +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pom.mustache index e65d27f8db4..cb92ea54823 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/pom.mustache @@ -69,6 +69,15 @@ + {{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} 4.8.1 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/queryParams.mustache index be8cee8dfe1..11f78ddd90f 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/spec/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@QueryParam("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@QueryParam("{{baseName}}"){{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}} {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/typeInfoAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/typeInfoAnnotation.mustache new file mode 100644 index 00000000000..b3083e788d9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/typeInfoAnnotation.mustache @@ -0,0 +1,7 @@ +{{#jackson}} +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}", visible = true ) +@JsonSubTypes({ + {{#children}} + @JsonSubTypes.Type(value = {{name}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), + {{/children}} +}){{/jackson}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache index 4a97c5d5f33..5df0cdee1b4 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/api.mustache @@ -21,7 +21,9 @@ import java.util.List; {{#async}} import java.util.concurrent.{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture{{/jdk8}}; {{/async}} - +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{>generatedAnnotation}} @Api(value = "{{{baseName}}}", description = "the {{{baseName}}} API") {{#operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache index 456176a05c2..d4ab09b71fe 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/apiController.mustache @@ -1,6 +1,6 @@ package {{package}}; -{{^jdk8}} +{{^jdk8-no-delegate}} {{#imports}}import {{import}}; {{/imports}} @@ -8,9 +8,9 @@ import io.swagger.annotations.*; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -{{/jdk8}} +{{/jdk8-no-delegate}} import org.springframework.stereotype.Controller; -{{^jdk8}} +{{^jdk8-no-delegate}} import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -21,24 +21,35 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; {{#async}} import java.util.concurrent.Callable; -{{/async}}{{/jdk8}} - +{{/async}}{{/jdk8-no-delegate}} +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{>generatedAnnotation}} @Controller {{#operations}} public class {{classname}}Controller implements {{classname}} { -{{^jdk8}}{{#operation}} +{{#isDelegate}} + private final {{classname}}Delegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + {{classname}}Controller({{classname}}Delegate delegate) { + this.delegate = delegate; + }{{/isDelegate}} + +{{^jdk8-no-delegate}}{{#operation}} public {{#async}}Callable<{{/async}}ResponseEntity<{{>returnTypes}}>{{#async}}>{{/async}} {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - // do some magic!{{^async}} + // do some magic!{{^isDelegate}}{{^async}} return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK);{{/async}}{{#async}} return new CallablereturnTypes}}>>() { @Override public ResponseEntity<{{>returnTypes}}> call() throws Exception { return new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK); } - };{{/async}} + };{{/async}}{{/isDelegate}}{{#isDelegate}} + return delegate.{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{/isDelegate}} } -{{/operation}}{{/jdk8}} +{{/operation}}{{/jdk8-no-delegate}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/apiDelegate.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/apiDelegate.mustache new file mode 100644 index 00000000000..eed583ea916 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/apiDelegate.mustache @@ -0,0 +1,37 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import io.swagger.annotations.*;{{#jdk8}} +import org.springframework.http.HttpStatus;{{/jdk8}} +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +{{#async}} +import java.util.concurrent.{{^jdk8}}Callable{{/jdk8}}{{#jdk8}}CompletableFuture{{/jdk8}}; +{{/async}} + +{{#operations}} +/** + * A delegate to be called by the {@link {{classname}}Controller}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link {{classname}}Controller}. + */ +{{>generatedAnnotation}} +public interface {{classname}}Delegate { + +{{#operation}} + /** + * @see {{classname}}#{{operationId}} + */ + {{#jdk8}}default {{/jdk8}}{{#responseWrapper}}{{.}}<{{/responseWrapper}}ResponseEntity<{{>returnTypes}}>{{#responseWrapper}}>{{/responseWrapper}} {{operationId}}({{#allParams}}{{^isFile}}{{{dataType}}}{{/isFile}}{{#isFile}}MultipartFile{{/isFile}} {{paramName}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}){{^jdk8}};{{/jdk8}}{{#jdk8}} { + // do some magic! + return {{#async}}CompletableFuture.completedFuture({{/async}}new ResponseEntity<{{>returnTypes}}>(HttpStatus.OK){{#async}}){{/async}}; + }{{/jdk8}} + +{{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidation.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidation.mustache new file mode 100644 index 00000000000..079eab89d1a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidation.mustache @@ -0,0 +1,53 @@ +{{#required}} + @NotNull +{{/required}} +{{#pattern}} + @Pattern(regexp="{{pattern}}") +{{/pattern}} +{{#minLength}} +{{#maxLength}} + @Size(min={{minLength}},max={{maxLength}}) +{{/maxLength}} +{{/minLength}} +{{#minLength}} +{{^maxLength}} + @Size(min={{minLength}}) +{{/maxLength}} +{{/minLength}} +{{^minLength}} +{{#maxLength}} + @Size(max={{maxLength}}) + {{/maxLength}} + {{/minLength}} +{{#minItems}} +{{#maxItems}} + @Size(min={{minItems}},max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{#minItems}} +{{^maxItems}} + @Size(min={{minItems}}) +{{/maxItems}} +{{/minItems}} +{{^minItems}} +{{#maxItems}} + @Size(max={{maxItems}}) +{{/maxItems}} +{{/minItems}} +{{! check for integer / number=decimal type}} +{{#isInteger}} +{{#minimum}} + @Min({{minimum}}) +{{/minimum}} +{{#maximum}} + @Max({{maximum}}) +{{/maximum}} +{{/isInteger}} +{{^isInteger}} +{{#minimum}} + @DecimalMin("{{minimum}}") +{{/minimum}} +{{#maximum}} + @DecimalMax("{{maximum}}") +{{/maximum}} +{{/isInteger}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationPathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationPathParams.mustache new file mode 100644 index 00000000000..e3060fa6c6a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationPathParams.mustache @@ -0,0 +1 @@ +{{! PathParam is always required, no @NotNull necessary }}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationQueryParams.mustache new file mode 100644 index 00000000000..52440b12218 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/beanValidationQueryParams.mustache @@ -0,0 +1 @@ +{{#required}} @NotNull{{/required}}{{#pattern}} @Pattern(regexp="{{pattern}}"){{/pattern}}{{#minLength}}{{#maxLength}} @Size(min={{minLength}},max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} @Size(min={{minLength}}){{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} @Size(max={{maxLength}}){{/maxLength}}{{/minLength}}{{#minItems}}{{#maxItems}} @Size(min={{minItems}},max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minItems}}{{^maxItems}} @Size(min={{minItems}}){{/maxItems}}{{/minItems}}{{^minItems}}{{#maxItems}} @Size(max={{maxItems}}){{/maxItems}}{{/minItems}}{{#minimum}} @Min({{minimum}}){{/minimum}}{{#maximum}} @Max({{maximum}}){{/maximum}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache index d58586a5db6..0e1f386a2dd 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-boot/pom.mustache @@ -77,5 +77,14 @@ 2.6.4 {{/threetenbp}} +{{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} - \ No newline at end of file + diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache index 961f45260a5..362fa5099d6 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-cloud/pom.mustache @@ -72,10 +72,19 @@ 2.6.4 {{/threetenbp}} +{{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} org.springframework.boot spring-boot-starter-test test - \ No newline at end of file + diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/pom.mustache index e2d80297da6..04a355b1b8d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/libraries/spring-mvc/pom.mustache @@ -141,6 +141,15 @@ servlet-api ${servlet-api-version} +{{#useBeanValidation}} + + + javax.validation + validation-api + 1.1.0.Final + provided + +{{/useBeanValidation}} {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/model.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/model.mustache index d52b90c8bec..a3d4e232757 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/model.mustache @@ -6,7 +6,9 @@ import java.util.Objects; {{#serializableModel}} import java.io.Serializable; {{/serializableModel}} - +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} {{#models}} {{#model}} {{#isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/pathParams.mustache index 4a6f7dfc922..aab5fd8ef42 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/pathParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathVariable("{{paramName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathVariable("{{paramName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache index 06c8e3048a0..4eb1ff91d17 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/pojo.mustache @@ -2,7 +2,7 @@ * {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} */{{#description}} @ApiModel(description = "{{{description}}}"){{/description}} -{{>generatedAnnotation}} +{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { {{#vars}} {{#isEnum}} @@ -62,10 +62,10 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * @return {{name}} **/ {{#vendorExtensions.extraAnnotation}} - {{vendorExtensions.extraAnnotation}} + {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} - @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - public {{{datatypeWithEnum}}} {{getter}}() { + @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}") +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/queryParams.mustache index 0c7987be560..792c265aacb 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpring/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#enumVars}}{{{name}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/enumVars}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#enumVars}}{{{name}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/enumVars}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpring/typeInfoAnnotation.mustache b/modules/swagger-codegen/src/main/resources/JavaSpring/typeInfoAnnotation.mustache new file mode 100644 index 00000000000..b3083e788d9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaSpring/typeInfoAnnotation.mustache @@ -0,0 +1,7 @@ +{{#jackson}} +@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "{{discriminator}}", visible = true ) +@JsonSubTypes({ + {{#children}} + @JsonSubTypes.Type(value = {{name}}.class, name = "{{^vendorExtensions.x-discriminator-value}}{{name}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{vendorExtensions.x-discriminator-value}}}{{/vendorExtensions.x-discriminator-value}}"), + {{/children}} +}){{/jackson}} diff --git a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache index e15e87d24f0..ff8ace4e74b 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache @@ -311,13 +311,13 @@ * @returns A value of the specified type. */ {{/emitJSDoc}} exports.prototype.deserialize = function deserialize(response, returnType) { - if (response == null || returnType == null) { + if (response == null || returnType == null || response.status == 204) { return null; } // Rely on SuperAgent for parsing response body. // See http://visionmedia.github.io/superagent/#parsing-response-bodies var data = response.body; - if (data == null || !Object.keys(data).length) { + if (data == null || (typeof data === 'object' && typeof data.length === 'undefined' && !Object.keys(data).length)) { // SuperAgent does not always produce a body; use the unparsed response as a fallback data = response.text; } @@ -430,8 +430,12 @@ if (error) { reject(error); } else { - var data = _this.deserialize(response, returnType); - resolve(data); + try { + var data = _this.deserialize(response, returnType); + resolve(data); + } catch (err) { + reject(err); + } } }); });{{/usePromises}} @@ -439,7 +443,11 @@ if (callback) { var data = null; if (!error) { - data = _this.deserialize(response, returnType); + try { + data = _this.deserialize(response, returnType); + } catch (err) { + error = err; + } } callback(error, data, response); } diff --git a/modules/swagger-codegen/src/main/resources/Javascript/api_test.mustache b/modules/swagger-codegen/src/main/resources/Javascript/api_test.mustache index 181c114ca96..e37cb1162ee 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/api_test.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/api_test.mustache @@ -41,7 +41,7 @@ describe('{{operationId}}', function() { it('should call {{operationId}} successfully', function(done) { //uncomment below and update the code to test {{operationId}} - //instance.{{operationId}}(pet, function(error) { + //instance.{{operationId}}(function(error) { // if (error) throw error; //expect().to.be(); //}); diff --git a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache index 39d34639916..f72afdd14d7 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_enum_class.mustache @@ -26,7 +26,7 @@ * @return {{=< >=}}{module:<#invokerPackage>/<#modelPackage>/}<={{ }}=> The enum {{classname}} value. */ exports.constructFromObject = function(object) { - return exports[object]; + return object; } return exports; diff --git a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache index f08a5c7f5b5..e955fda3869 100644 --- a/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/Javascript/partial_model_generic.mustache @@ -39,7 +39,7 @@ exports.constructFromObject = function(data, obj) { if (data){{! TODO: support polymorphism: discriminator property on data determines class to instantiate.}} { obj = obj || new exports(); -{{#parent}}{{^parentModel}} ApiClient.constructFromObject(data, obj, {{vendorExtensions.x-itemType}}); +{{#parent}}{{^parentModel}} ApiClient.constructFromObject(data, obj, '{{vendorExtensions.x-itemType}}'); {{/parentModel}}{{/parent}}{{#useInheritance}}{{#parentModel}} {{classname}}.constructFromObject(data, obj);{{/parentModel}} {{#interfaces}} {{.}}.constructFromObject(data, obj); {{/interfaces}}{{/useInheritance}}{{#vars}} if (data.hasOwnProperty('{{baseName}}')) { diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 02f5ce9c05d..876409b50b4 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -2,10 +2,12 @@ io.swagger.codegen.languages.AndroidClientCodegen io.swagger.codegen.languages.AspNet5ServerCodegen io.swagger.codegen.languages.AspNetCoreServerCodegen io.swagger.codegen.languages.AsyncScalaClientCodegen +io.swagger.codegen.languages.BashClientCodegen io.swagger.codegen.languages.ConfluenceWikiGenerator io.swagger.codegen.languages.CSharpClientCodegen io.swagger.codegen.languages.CppRestClientCodegen io.swagger.codegen.languages.DartClientCodegen +io.swagger.codegen.languages.ElixirClientCodegen io.swagger.codegen.languages.FlashClientCodegen io.swagger.codegen.languages.FlaskConnexionCodegen io.swagger.codegen.languages.GoClientCodegen @@ -32,6 +34,7 @@ io.swagger.codegen.languages.Qt5CPPGenerator io.swagger.codegen.languages.RubyClientCodegen io.swagger.codegen.languages.ScalaClientCodegen io.swagger.codegen.languages.ScalatraServerCodegen +io.swagger.codegen.languages.FinchServerCodegen io.swagger.codegen.languages.SilexServerCodegen io.swagger.codegen.languages.SinatraServerCodegen io.swagger.codegen.languages.Rails5ServerCodegen @@ -58,3 +61,4 @@ io.swagger.codegen.languages.GoServerCodegen io.swagger.codegen.languages.ErlangServerCodegen io.swagger.codegen.languages.UndertowCodegen io.swagger.codegen.languages.JavaMSF4JServerCodegen +io.swagger.codegen.languages.ZendExpressivePathHandlerServerCodegen \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/MSF4J/pojo.mustache b/modules/swagger-codegen/src/main/resources/MSF4J/pojo.mustache index 6e5c1b74115..7545ad82098 100644 --- a/modules/swagger-codegen/src/main/resources/MSF4J/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/MSF4J/pojo.mustache @@ -64,7 +64,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * @return {{name}} **/ {{#vendorExtensions.extraAnnotation}} - {{vendorExtensions.extraAnnotation}} + {{{vendorExtensions.extraAnnotation}}} {{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") public {{{datatypeWithEnum}}} {{getter}}() { diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index 4f022d22292..3417ccb7f19 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -95,7 +95,7 @@ export const {{classname}}FetchParamCreator = { {{/hasQueryParams}} let fetchOptions: RequestInit = {{#supportsES6}}Object.{{/supportsES6}}assign({}, { method: "{{httpMethod}}" }, options); - let contentTypeHeader: Dictionary; + let contentTypeHeader: Dictionary = {}; {{#hasFormParams}} contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; fetchOptions.body = querystring.stringify({ diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache index 3b8c6ec5fe3..6267b425ba1 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache @@ -85,10 +85,10 @@ object ApiInvoker { case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { case JString(s) => - ISODateTimeFormat.dateTimeParser().parseDateTime(s) + ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(s) }, { case d: DateTime => - JString(ISODateTimeFormat.dateTimeParser().print(d)) + JString(ISODateTimeFormat.dateTime().print(d)) })) } diff --git a/modules/swagger-codegen/src/main/resources/aspnetcore/enumClass.mustache b/modules/swagger-codegen/src/main/resources/aspnetcore/enumClass.mustache new file mode 100644 index 00000000000..1a5850e28a9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/aspnetcore/enumClass.mustache @@ -0,0 +1,14 @@ + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{#description}} + /// {{{description}}}{{/description}} + public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + { + {{#allowableValues}}{{#enumVars}} + /// + /// Enum {{name}} for {{{value}}} + /// + [EnumMember(Value = {{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isFloat}}"{{/isFloat}}{{#isDouble}}"{{/isDouble}}{{{value}}}{{#isLong}}"{{/isLong}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isFloat}}"{{/isFloat}})] + {{name}}{{#isLong}} = {{{value}}}{{/isLong}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{^-last}}, + {{/-last}}{{/enumVars}}{{/allowableValues}} + } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/aspnetcore/global.json b/modules/swagger-codegen/src/main/resources/aspnetcore/global.json index e5360d025ec..175b2d57e38 100644 --- a/modules/swagger-codegen/src/main/resources/aspnetcore/global.json +++ b/modules/swagger-codegen/src/main/resources/aspnetcore/global.json @@ -1,5 +1,5 @@ { - "projects": [ "src", "test" ], + "projects": [ "src" ], "sdk": { "version": "1.0.0-preview2-003121", "runtime": "coreclr" diff --git a/modules/swagger-codegen/src/main/resources/aspnetcore/model.mustache b/modules/swagger-codegen/src/main/resources/aspnetcore/model.mustache index 58325e8fe24..101f85ce13f 100644 --- a/modules/swagger-codegen/src/main/resources/aspnetcore/model.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnetcore/model.mustache @@ -13,18 +13,40 @@ using Newtonsoft.Json; {{#model}} namespace {{packageName}}.Models { +{{#isEnum}}{{>enumClass}}{{/isEnum}}{{^isEnum}} /// /// {{description}} /// [DataContract] public partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}} IEquatable<{{classname}}> { + {{#vars}} + {{#isEnum}} + {{>enumClass}} + {{/isEnum}} + {{#items.isEnum}} + {{#items}} + {{>enumClass}} + {{/items}} + {{/items.isEnum}} + {{/vars}} + {{#vars}} + {{#isEnum}} + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{#description}} + /// {{{description}}}{{/description}} + [DataMember(Name="{{baseName}}")] + public {{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}} {{name}} { get; set; } + {{/isEnum}} + {{/vars}} + /// /// Initializes a new instance of the class. /// {{#vars}} /// {{#description}}{{description}}{{/description}}{{^description}}{{name}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{defaultValue}}){{/defaultValue}}. {{/vars}} - public {{classname}}({{#vars}}{{{datatype}}} {{name}} = null{{#hasMore}}, {{/hasMore}}{{/vars}}) + public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}} {{name}} = {{#defaultValue}}{{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}default({{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}?{{/isContainer}}{{/isEnum}}){{/defaultValue}}{{^-last}}, {{/-last}}{{/readWriteVars}}) { {{#vars}}{{#required}}// to ensure "{{name}}" is required (not null) if ({{name}} == null) @@ -49,13 +71,14 @@ namespace {{packageName}}.Models } {{#vars}} + {{^isEnum}} /// - /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{{description}}}{{/description}} + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} /// {{#description}} - /// {{{description}}}{{/description}} + /// {{description}}{{/description}} [DataMember(Name="{{baseName}}")] - public {{{datatype}}} {{name}} { get; set; } - + public {{{datatype}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } + {{/isEnum}} {{/vars}} /// @@ -153,6 +176,7 @@ namespace {{packageName}}.Models #endregion Operators } +{{/isEnum}} {{/model}} {{/models}} } diff --git a/modules/swagger-codegen/src/main/resources/aspnetcore/project.json.mustache b/modules/swagger-codegen/src/main/resources/aspnetcore/project.json.mustache index 432ba86d5a9..46a9071fde4 100644 --- a/modules/swagger-codegen/src/main/resources/aspnetcore/project.json.mustache +++ b/modules/swagger-codegen/src/main/resources/aspnetcore/project.json.mustache @@ -22,7 +22,8 @@ "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", "Microsoft.EntityFrameworkCore": "1.0.0", "Swashbuckle.SwaggerGen": "6.0.0-beta901", - "Swashbuckle.SwaggerUi": "6.0.0-beta901" + "Swashbuckle.SwaggerUi": "6.0.0-beta901", + "Newtonsoft.Json": "9.0.1" }, "tools": { diff --git a/modules/swagger-codegen/src/main/resources/bash/Dockerfile.mustache b/modules/swagger-codegen/src/main/resources/bash/Dockerfile.mustache new file mode 100644 index 00000000000..9af7d224f6f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/Dockerfile.mustache @@ -0,0 +1,69 @@ +FROM ubuntu:16.10 + +RUN apt-get update -y && apt-get full-upgrade -y +RUN apt-get install -y bash-completion zsh curl cowsay git vim bsdmainutils + +ADD {{scriptName}} /usr/bin/{{scriptName}} +ADD _{{scriptName}} /usr/local/share/zsh/site-functions/_{{scriptName}} +ADD {{scriptName}}.bash-completion /etc/bash-completion.d/{{scriptName}} + + +# +# Install oh-my-zsh +# +RUN sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" || true + +# +# Enable bash completion +# +RUN echo '\n\ +. /etc/bash_completion\n\ +source /etc/bash-completion.d/{{scriptName}}\n\ +' >> ~/.bashrc + +# +# Setup prompt +# +RUN echo 'export PS1="[{{appName}}] \$ "' >> ~/.bashrc +RUN echo 'export PROMPT="[{{appName}}] \$ "' >> ~/.zshrc + +# +# Setup a welcome message with basic instruction +# +RUN echo 'cat << EOF\n\ +\n\ +This Docker provides preconfigured environment for running the command\n\ +line REST client for $(tput setaf 6){{appName}}$(tput sgr0).\n\ +\n\ +For convenience, you can export the following environment variables:\n\ +\n\ +{{#x-codegen-host-env}}$(tput setaf 3){{x-codegen-host-env}}$(tput sgr0) - server URL, e.g. https://example.com:8080\n\{{/x-codegen-host-env}} +{{#hasAuthMethods}} +{{#authMethods}} +{{#isBasic}} +{{#x-codegen-basicauth-env}}$(tput setaf 3){{x-codegen-basicauth-env}}$(tput sgr0) - basic authentication credentials, e.g.: "username:password"\n\{{/x-codegen-basicauth-env}} +{{/isBasic}} +{{#isApiKey}} +{{#x-codegen-apikey-env}}$(tput setaf 3){{x-codegen-apikey-env}}$(tput sgr0) - access token, e.g. "ASDASHJDG63456asdASSD"\n\{{/x-codegen-apikey-env}} +{{/isApiKey}} +{{/authMethods}} +{{/hasAuthMethods}} +\n\ +$(tput setaf 7)Basic usage:$(tput sgr0)\n\ +\n\ +$(tput setaf 3)Print the list of operations available on the service$(tput sgr0)\n\ +$ {{scriptName}} -h\n\ +\n\ +$(tput setaf 3)Print the service description$(tput sgr0)\n\ +$ {{scriptName}} --about\n\ +\n\ +$(tput setaf 3)Print detailed information about specific operation$(tput sgr0)\n\ +$ {{scriptName}} -h\n\ +\n\ +By default you are logged into Zsh with full autocompletion for your REST API,\n\ +but you can switch to Bash, where basic autocompletion is also supported.\n\ +\n\ +EOF\n\ +' | tee -a ~/.bashrc ~/.zshrc + +ENTRYPOINT ["zsh"] diff --git a/modules/swagger-codegen/src/main/resources/bash/README.md b/modules/swagger-codegen/src/main/resources/bash/README.md new file mode 100644 index 00000000000..da35f04ae67 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/README.md @@ -0,0 +1,220 @@ +# Bash script generator for Swagger Codegen + +## Overview +This is a Bash client script codegen. + +The codegen creates a standalone, single-file Bash script client to quickly test and access Swagger annotated REST services. The generated script uses underneath [cURL](https://curl.haxx.se) to make actual REST calls. + +The generated Bash script has only 2 dependencies: +- Bash (>= 4.3) +- cURL + +## Features +- Fully automatic generation of a client Bash script to access any Swagger-defined REST service +- Generation of Bash and Zsh completion scripts +- All valid cURL options can be passed directly +- Preview of cURL commands to execute each operation using `--dry-run` option +- Complete help for entire service as well as for each operation +- No external dependencies besides Bash and cURL + +## Usage + +### Generating Bash client for REST service + +Get the sources: +```shell +$ git clone https://github.com/swagger-api/swagger-codegen +``` + +Build the codegen: +```shell +$ mvn assembly:assembly -DdescriptorId=jar-with-dependencies +``` + +Define custom codegen properties in a Json file, e.g.: +```shell +{ + "processMarkdown": true, + "curlOptions": "-sS --tlsv1.2", + "scriptName": "petstore-cli", + "generateBashCompletion": true, + "generateZshCompletion": true, + "hostEnvironmentVariable": "PETSTORE_HOST", + "basicAuthEnvironmentVariable": "PETSTORE_BASIC_AUTH", + "apiKeyAuthEnvironmentVariable": "PETSTORE_API_KEY" +} +``` + +Generate the client: +```shell +$ java -cp target/bash-swagger-codegen-1.0.0.jar io.swagger.codegen.SwaggerCodegen generate -l bash -i http://petstore.swagger.io/v2/swagger.json -o output -c resources/example-config.json + +$ chmod +x output/petstore-cli +``` + +Enjoy: +```shell +$ output/petstore-cli -h + +Swagger Petstore command line client (API version 1.0.0) + +Usage + + petstore-cli [-h|--help] [-V|--version] [--about] [] + [-ac|--accept ] [-ct,--content-type ] + [--host ] [--dry-run] [-h|--help] [] + [] [] + + - - endpoint of the REST service without basepath + Can also be specified in PETSTORE_HOST environment variable. + - - any valid cURL options can be passed before + - - either full mime-type or one of supported abbreviations: + (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, + rdf, jpg, png, gif, bmp, tiff) + - - HTTP headers can be passed in the form HEADER:VALUE + - - REST operation parameters can be passed in the following + forms: + * KEY=VALUE - path or query parameters + - - simple JSON body content (first level only) can be build + using the following arguments: + * KEY==VALUE - body parameters which will be added to body + JSON as '{ ..., "KEY": "VALUE", ... }' + * KEY:=VALUE - body parameters which will be added to body + JSON as '{ ..., "KEY": VALUE, ... }' + +Authentication methods + + - Api-key - add 'api_key:' after + or export PETSTORE_API_KEY='' + - OAuth2 (flow: implicit) + Authorization URL: + * http://petstore.swagger.io/oauth/dialog + Scopes: + * write:pets - modify pets in your account + * read:pets - read your pets + +Operations (grouped by tags) + +[pet] + addPet Add a new pet to the store + deletePet Deletes a pet + findPetsByStatus Finds Pets by status + findPetsByTags Finds Pets by tags + getPetById Find pet by ID + updatePet Update an existing pet + updatePetWithForm Updates a pet in the store with form data + uploadFile uploads an image + +[store] + deleteOrder Delete purchase order by ID + getInventory Returns pet inventories by status + getOrderById Find purchase order by ID + placeOrder Place an order for a pet + +[user] + createUser Create user + createUsersWithArrayInput Creates list of users with given input array + createUsersWithListInput Creates list of users with given input array + deleteUser Delete user + getUserByName Get user by user name + loginUser Logs user into the system + logoutUser Logs out current logged in user session + updateUser Updated user + +Options + -h,--help Print this help + -V,--version Print API version + --about Print the information about service + --host Specify the host URL + (e.g. 'https://petstore.swagger.io') + --force Force command invocation in spite of missing + required parameters or wrong content type + --dry-run Print out the cURL command without + executing it + -ac,--accept Set the 'Accept' header in the request + -ct,--content-type Set the 'Content-type' header in + the request +``` + +Client generator takes several specific configuration options: +* *processMarkdown* - [boolean] if set to `true`, all text (descriptions) in the Swagger specification will be treated as Markdown and converted to terminal formatting commands, +* *curlOptions* - [string] a list of default cURL options that will be added to each command +* *scriptName* - [string] the name of the target script, necessary when building Bash completion script +* *generateBashCompletion* - [boolean] if set to `true` the Bash completion script will be generated +* *generateZshCompletion* - [boolean] if set to `true` the Bash completion script will be generated +* *hostEnvironmentVariable* - [string] the name of environment variable to search for default host +* *basicAuthEnvironmentVariable* - [string] the name of environment variable to search for default basic auth credentials +* *apiKeyAuthEnvironmentVariable* - [string] the name of environment variable to search for default api key + +These options can be specified in a Json file used when running the codegen using option `-c` (see [example](resources/example-config.json)). + +### Using the generated Bash script + +```shell +# Print the list of operations available on the service +$ petstore-cli --help + +# Print the service description +$ petstore-cli --about + +# Print detailed information about specific operation +$ petstore-cli addPet --help + +# Call REST API operation +$ echo '{"id":891,"name":"lucky","status":"available"}' | petstore-cli --host http://petstore.swagger.io --content-type json addPet - + +{"id":891,"name":"lucky","photoUrls":[],"tags":[],"status":"available"} + +# The above is equivalent to +$ petstore-cli --host http://petstore.swagger.io --content-type json --accept xml addPet id:=891 name==lucky status==available + +891luckyavailable + + +# Preview the cURL command without actually executing it +# The above is equivalent to +$ petstore-cli --host http://petstore.swagger.io --content-type json --dry-run addPet id:=891 name==lucky status==available + +curl -sS --tlsv1.2 -H 'Content-type: application/json' -X POST -d '{"name": "lucky", "status": "available", "id": 891}' "http://petstore.swagger.io/v2/pet" +``` + +## Shell completion + +### Bash +The generated bash-completion script can be either directly loaded to the current Bash session using: + +```shell +source output/petstore-cli.bash-completion +``` + +Alternatively, the script can be copied to the `/etc/bash-completion.d` (or on OSX with Homebrew to `/usr/local/etc/bash-completion.d`): + +```shell +sudo cp output/petstore-cli.bash-completion /etc/bash-completion.d/petstore-cli +``` + +#### OS X +On OSX you might need to install bash-completion using Homebrew: +```shell +brew install bash-completion +``` +and add the following to the `~/.bashrc`: + +```shell +if [ -f $(brew --prefix)/etc/bash_completion ]; then + . $(brew --prefix)/etc/bash_completion +fi +``` + +### Zsh +In Zsh, the generated `_{{scriptName}}` file (e.g. _petstore-cli) must be copied to one of the folders under `$fpath` variable. + + +## TODO +- [ ] Add enum values for parameters shell completion +- [ ] Wrap handling of errors returned by the service, using comments defined in the Swagger specification +- [ ] Improve `--help` and `--about` formatting +- [ ] Add support to bash 4.0-4.2 (currently must be >= 4.3) +- [ ] Add manpage generation +- [ ] Add support for form data +- [ ] Move todos to Github issues diff --git a/modules/swagger-codegen/src/main/resources/bash/README.mustache b/modules/swagger-codegen/src/main/resources/bash/README.mustache new file mode 100644 index 00000000000..bbb85fb225b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/README.mustache @@ -0,0 +1,88 @@ +# {{appName}} Bash client + +## Overview +This is a Bash client script for accessing {{appName}} service. + +The script uses cURL underneath for making all REST calls. + +## Usage + +```shell +# Make sure the script has executable rights +$ chmod u+x {{scriptName}} + +# Print the list of operations available on the service +$ ./{{scriptName}} -h + +# Print the service description +$ ./{{scriptName}} --about + +# Print detailed information about specific operation +$ ./{{scriptName}} -h + +# Make GET request +./{{scriptName}} --host http://: --accept xml = : + +# Make GET request using arbitrary curl options (must be passed before ) to an SSL service using username:password +{{scriptName}} -k -sS --tlsv1.2 --host https:// -u : --accept xml = : + +# Make POST request +$ echo '' | {{scriptName}} --host --content-type json - + +# Make POST request with simple JSON content, e.g.: +# { +# "key1": "value1", +# "key2": "value2", +# "key3": 23 +# } +$ echo '' | {{scriptName}} --host --content-type json key1==value1 key2=value2 key3:=23 - + +# Preview the cURL command without actually executing it +$ {{scriptName}} --host http://: --dry-run + +``` + +## Docker image +You can easily create a Docker image containing a preconfigured environment +for using the REST Bash client including working autocompletion and short +welcome message with basic instructions, using the generated Dockerfile: + +```shell +docker build -t my-rest-client . +docker run -it my-rest-client +``` + +By default you will be logged into a Zsh environment which has much more +advanced auto completion, but you can switch to Bash, where basic autocompletion +is also available. + +## Shell completion + +### Bash +The generated bash-completion script can be either directly loaded to the current Bash session using: + +```shell +source {{scriptName}}.bash-completion +``` + +Alternatively, the script can be copied to the `/etc/bash-completion.d` (or on OSX with Homebrew to `/usr/local/etc/bash-completion.d`): + +```shell +sudo cp {{scriptName}}.bash-completion /etc/bash-completion.d/{{scriptName}} +``` + +#### OS X +On OSX you might need to install bash-completion using Homebrew: +```shell +brew install bash-completion +``` +and add the following to the `~/.bashrc`: + +```shell +if [ -f $(brew --prefix)/etc/bash_completion ]; then + . $(brew --prefix)/etc/bash_completion +fi +``` + +### Zsh +In Zsh, the generated `_{{scriptName}}` Zsh completion file must be copied to one of the folders under `$FPATH` variable. diff --git a/modules/swagger-codegen/src/main/resources/bash/bash-completion.mustache b/modules/swagger-codegen/src/main/resources/bash/bash-completion.mustache new file mode 100644 index 00000000000..83b907259ad --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/bash-completion.mustache @@ -0,0 +1,287 @@ +# {{scriptName}} completion -*- shell-script -*- + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Generated on: {{generatedDate}} +# ! +# ! +# ! System wide installation: +# ! +# ! $ sudo cp {{scriptName}}.bash-completion /etc/bash-completion.d/{{scriptName}} +# ! +# ! +# ! User home installation (add this line to .bash_profile): +# ! +# ! [ -r ~/{{scriptName}}.bash-completion ] && source ~/{{scriptName}}.bash-completion +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +declare -A mime_type_abbreviations +# text/* +mime_type_abbreviations["text"]="text/plain" +mime_type_abbreviations["html"]="text/html" +mime_type_abbreviations["md"]="text/x-markdown" +mime_type_abbreviations["csv"]="text/csv" +mime_type_abbreviations["css"]="text/css" +mime_type_abbreviations["rtf"]="text/rtf" +# application/* +mime_type_abbreviations["json"]="application/json" +mime_type_abbreviations["xml"]="application/xml" +mime_type_abbreviations["yaml"]="application/yaml" +mime_type_abbreviations["js"]="application/javascript" +mime_type_abbreviations["bin"]="application/octet-stream" +mime_type_abbreviations["rdf"]="application/rdf+xml" +# image/* +mime_type_abbreviations["jpg"]="image/jpeg" +mime_type_abbreviations["png"]="image/png" +mime_type_abbreviations["gif"]="image/gif" +mime_type_abbreviations["bmp"]="image/bmp" +mime_type_abbreviations["tiff"]="image/tiff" + + +# +# Check if this is OSX, if so defined custom init_completion +# +if [[ `uname` =~ "Darwin" ]]; then + __osx_init_completion() + { + COMPREPLY=() + _get_comp_words_by_ref cur prev words cword + } +fi + +_{{scriptName}}() +{ + local cur + local prev + local words + local cword + + # The reference of currently selected REST operation + local operation="" + + # The list of available operation in the REST service + # It's modelled as an associative array for efficient key lookup + declare -A operations +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + operations["{{operationId}}"]=1 +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + # An associative array of operations to their parameters + # Only include path, query and header parameters + declare -A operation_parameters +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + operation_parameters["{{operationId}}"]="{{#pathParams}}{{baseName}}= {{/pathParams}}{{#queryParams}}{{baseName}}= {{/queryParams}}{{#headerParams}}{{baseName}}: {{/headerParams}}" +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + # An associative array of possible values for enum parameters + declare -A operation_parameters_enum_values +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#allParams}} +{{#pathParams}} +{{#isBoolean}} + operation_parameters_enum_values["{{operationId}}::{{baseName}}"]="true false" +{{/isBoolean}} +{{#isEnum}} + operation_parameters_enum_values["{{operationId}}::{{baseName}}"]="" +{{/isEnum}} +{{/pathParams}} +{{#queryParams}} +{{#isBoolean}} + operation_parameters_enum_values["{{operationId}}::{{baseName}}"]="true false" +{{/isBoolean}} +{{/queryParams}} +{{#headerParams}} +{{#isBoolean}} + operation_parameters_enum_values["{{operationId}}::{{baseName}}"]="true false" +{{/isBoolean}} +{{/headerParams}} +{{/allParams}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + # + # Check if this is OSX and use special __osx_init_completion function + # + if [[ `uname` =~ "Darwin" ]]; then + __osx_init_completion || return + else + _init_completion -s || return + fi + + + # Check if operation is already in the command line provided + for word in "${words[@]}"; do + if [[ -n $word && ${operations[$word]} ]]; then + operation="${word}" + fi + done + + if [[ -z $operation ]]; then + case $prev in + --ciphers|--connect-timeout|-C|--continue-at|-F|--form|--form-string|\ + --ftp-account|--ftp-alternative-to-user|-P|--ftp-port|-H|--header|-h|\ + --help|--hostpubmd5|--keepalive-time|--krb|--limit-rate|--local-port|\ + --mail-from|--mail-rcpt|--max-filesize|--max-redirs|-m|--max-time|\ + --pass|--proto|--proto-redir|--proxy-user|--proxy1.0|-Q|--quote|-r|\ + --range|-X|--request|--retry|--retry-delay|--retry-max-time|\ + --socks5-gssapi-service|-t|--telnet-option|--tftp-blksize|-z|\ + --time-cond|--url|-u|--user|-A|--user-agent|-V|--version|-w|\ + --write-out|--resolve|--tlsuser|--tlspassword|--about) + return + ;; + -K|--config|-b|--cookie|-c|--cookie-jar|-D|--dump-header|--egd-file|\ + --key|--libcurl|-o|--output|--random-file|-T|--upload-file|--trace|\ + --trace-ascii|--netrc-file) + _filedir + return + ;; + --cacert|-E|--cert) + _filedir '@(c?(e)rt|cer|pem|der)' + return + ;; + --capath) + _filedir -d + return + ;; + --cert-type|--key-type) + COMPREPLY=( $( compgen -W 'DER PEM ENG' -- "$cur" ) ) + return + ;; + --crlfile) + _filedir crl + return + ;; + -d|--data|--data-ascii|--data-binary|--data-urlencode) + if [[ $cur == \@* ]]; then + cur=${cur:1} + _filedir + COMPREPLY=( "${COMPREPLY[@]/#/@}" ) + fi + return + ;; + --delegation) + COMPREPLY=( $( compgen -W 'none policy always' -- "$cur" ) ) + return + ;; + --engine) + COMPREPLY=( $( compgen -W 'list' -- "$cur" ) ) + return + ;; + --ftp-method) + COMPREPLY=( $( compgen -W 'multicwd nocwd singlecwd' -- "$cur" ) ) + return + ;; + --ftp-ssl-ccc-mode) + COMPREPLY=( $( compgen -W 'active passive' -- "$cur" ) ) + return + ;; + --interface) + _available_interfaces -a + return + ;; + -x|--proxy|--socks4|--socks4a|--socks5|--socks5-hostname) + _known_hosts_real + return + ;; + --pubkey) + _filedir pub + return + ;; + --stderr) + COMPREPLY=( $( compgen -W '-' -- "$cur" ) ) + _filedir + return + ;; + --tlsauthtype) + COMPREPLY=( $( compgen -W 'SRP' -- "$cur" ) ) + return + ;; + --host) + COMPREPLY=( $( compgen -W 'http:// https://' -- "$cur" ) ) + return + ;; + -ct|--content-type|-ac|--accept) + COMPREPLY=( $( compgen -W '${!mime_type_abbreviations[*]}' -- "$cur" ) ) + return + ;; + esac + fi + + # + # Complete the server address based on ~/.ssh/known_hosts + # and ~/.ssh/config + # + local prefix=${COMP_WORDS[COMP_CWORD-2]} + local colon=${COMP_WORDS[COMP_CWORD-1]} + if [[ "$colon" == ":" && ( $prefix == "https" || $prefix == "http" ) ]]; then + COMPREPLY=() + local comp_ssh_hosts=`[[ -f ~/.ssh/known_hosts ]] && \ + ( cat ~/.ssh/known_hosts | \ + grep '^[a-zA-Z0-9]' | \ + cut -f 1 -d ' ' | \ + sed -e s/,.*//g | \ + grep -v ^# | \ + uniq | \ + grep -v "\[" ) ; + [[ -f ~/.ssh/config ]] && \ + ( cat ~/.ssh/config | \ + grep "^Host " | \ + awk '{print $2}' )` + COMPREPLY=( $( compgen -P '//' -W '${comp_ssh_hosts}' -- "${cur:2}") ) + return + fi + + # + # Complete the {{scriptName}} and cURL's arguments + # + if [[ $cur == -* ]]; then + COMPREPLY=( $( compgen -W '$(_parse_help curl) $(_parse_help $1)' -- "$cur" ) ) + return + fi + + # + # If the argument starts with a letter this could be either an operation + # or an operation parameter + # When $cur is empty, suggest the list of operations by default + # + if [[ $cur =~ ^[A-Za-z_0-9]* ]]; then + # If operation has not been yet selected, suggest the list of operations + # otherwise suggest arguments of this operation as declared in the + # Swagger specification + if [[ -z $operation ]]; then + COMPREPLY=( $(compgen -W '${!operations[*]}' -- ${cur}) ) + else + COMPREPLY=( $(compgen -W '${operation_parameters[$operation]}' -- ${cur}) ) + compopt -o nospace + fi + return + fi + +} && +complete -F _{{scriptName}} {{scriptName}} + +# ex: ts=4 sw=4 et filetype=sh diff --git a/modules/swagger-codegen/src/main/resources/bash/client.mustache b/modules/swagger-codegen/src/main/resources/bash/client.mustache new file mode 100644 index 00000000000..e1e3aad1cfd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/client.mustache @@ -0,0 +1,1111 @@ +#!/usr/bin/env bash + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Generated on: {{generatedDate}} +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +# +# This is a Bash client for {{appName}}. +# +# LICENSE: +# {{licenseUrl}} +# +# CONTACT: +# {{infoEmail}} +# +# MORE INFORMATION: +# {{#externalDocs}}{{url}}{{/externalDocs}} +# + +############################################################################### +# +# Make sure Bash is at least in version 4.3 +# +############################################################################### +if ! ( (("${BASH_VERSION:0:1}" == "4")) && (("${BASH_VERSION:2:1}" >= "3")) ) \ + && ! (("${BASH_VERSION:0:1}" >= "5")); then + echo "" + echo "Sorry - your Bash version is ${BASH_VERSION}" + echo "" + echo "You need at least Bash 4.3 to run this script." + echo "" + exit 1 +fi + +############################################################################### +# +# Global variables +# +############################################################################### + +## +# The filename of this script for help messages +script_name=`basename "$0"` + +## +# Map for headers passed after operation as KEY:VALUE +declare -A header_arguments + + +## +# Map for operation parameters passed after operation as PARAMETER=VALUE +# These will be mapped to appropriate path or query parameters +# The values in operation_parameters are arrays, so that multiple values +# can be provided for the same parameter if allowed by API specification +declare -A operation_parameters + +## +# This array stores the minimum number of required occurences for parameter +# 0 - optional +# 1 - required +declare -A operation_parameters_minimum_occurences +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#allParams}} +operation_parameters_minimum_occurences["{{operationId}}:::{{baseName}}"]={{#required}}{{#vendorExtensions}}{{#x-codegen-collection-min-items}}{{x-codegen-collection-min-items}}{{/x-codegen-collection-min-items}}{{^x-codegen-collection-min-items}}1{{/x-codegen-collection-min-items}}{{/vendorExtensions}}{{^vendorExtensions}}1{{/vendorExtensions}}{{/required}}{{^required}}0{{/required}} +{{/allParams}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +## +# This array stores the maximum number of allowed occurences for parameter +# 1 - single value +# 2 - 2 values +# N - N values +# 0 - unlimited +declare -A operation_parameters_maximum_occurences +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#allParams}} +operation_parameters_maximum_occurences["{{operationId}}:::{{baseName}}"]={{#vendorExtensions}}{{#x-codegen-collection-max-items}}{{x-codegen-collection-max-items}}{{/x-codegen-collection-max-items}}{{^x-codegen-collection-max-items}}0{{/x-codegen-collection-max-items}}{{/vendorExtensions}}{{^vendorExtensions}}0{{/vendorExtensions}} +{{/allParams}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + +## +# The type of collection for specifying multiple values for parameter: +# - multi, csv, ssv, tsv +declare -A operation_parameters_collection_type +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} +{{#allParams}} +operation_parameters_collection_type["{{operationId}}:::{{baseName}}"]={{#isContainer}}{{#vendorExtensions}}{{#x-codegen-collection-multi}}"multi"{{/x-codegen-collection-multi}}{{#x-codegen-collection-csv}}"csv"{{/x-codegen-collection-csv}}{{#x-codegen-collection-tsv}}"tsv"{{/x-codegen-collection-tsv}}{{#x-codegen-collection-ssv}}"ssv"{{/x-codegen-collection-ssv}}{{/vendorExtensions}}{{^vendorExtensions}}""{{/vendorExtensions}}{{/isContainer}}{{^isContainer}}""{{/isContainer}} +{{/allParams}} +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + + +## +# Map for body parameters passed after operation as +# PARAMETER==STRING_VALUE or PARAMETER:=NUMERIC_VALUE +# These will be mapped to top level json keys ( { "PARAMETER": "VALUE" }) +declare -A body_parameters + +## +# These arguments will be directly passed to cURL +curl_arguments="{{x-codegen-curl-options}}" + +## +# The host for making the request +host="{{#x-codegen-host-env}}${{x-codegen-host-env}}{{/x-codegen-host-env}}" + +## +# The user credentials for basic authentication +basic_auth_credential="{{#x-codegen-basicauth-env}}${{x-codegen-basicauth-env}}{{/x-codegen-basicauth-env}}" + +## +# The user API key +apikey_auth_credential="{{#x-codegen-apikey-env}}${{x-codegen-apikey-env}}{{/x-codegen-apikey-env}}" + +## +# If true, the script will only output the actual cURL command that would be +# used +print_curl=false + +## +# The operation ID passed on the command line +operation="" + +## +# The provided Accept header value +header_accept="" + +## +# The provided Content-type header value +header_content_type="" + +## +# If there is any body content on the stdin pass it to the body of the request +body_content_temp_file="" + +## +# If this variable is set to true, the request will be performed even +# if parameters for required query, header or body values are not provided +# (path parameters are still required). +force=false + +## +# Declare some mime types abbreviations for easier content-type and accepts +# headers specification +declare -A mime_type_abbreviations +# text/* +mime_type_abbreviations["text"]="text/plain" +mime_type_abbreviations["html"]="text/html" +mime_type_abbreviations["md"]="text/x-markdown" +mime_type_abbreviations["csv"]="text/csv" +mime_type_abbreviations["css"]="text/css" +mime_type_abbreviations["rtf"]="text/rtf" +# application/* +mime_type_abbreviations["json"]="application/json" +mime_type_abbreviations["xml"]="application/xml" +mime_type_abbreviations["yaml"]="application/yaml" +mime_type_abbreviations["js"]="application/javascript" +mime_type_abbreviations["bin"]="application/octet-stream" +mime_type_abbreviations["rdf"]="application/rdf+xml" +# image/* +mime_type_abbreviations["jpg"]="image/jpeg" +mime_type_abbreviations["png"]="image/png" +mime_type_abbreviations["gif"]="image/gif" +mime_type_abbreviations["bmp"]="image/bmp" +mime_type_abbreviations["tiff"]="image/tiff" + + +############################################################################## +# +# Escape special URL characters +# Based on table at http://www.w3schools.com/tags/ref_urlencode.asp +# +############################################################################## +url_escape() { + local raw_url="$1" + + value=$(sed -e 's/ /%20/g' \ + -e 's/!/%21/g' \ + -e 's/"/%22/g' \ + -e 's/#/%23/g' \ + -e 's/\&/%26/g' \ + -e 's/'\''/%28/g' \ + -e 's/(/%28/g' \ + -e 's/)/%29/g' \ + -e 's/:/%3A/g' \ + -e 's/?/%3F/g' <<<$raw_url); + + echo $value +} + +############################################################################## +# +# Lookup the mime type abbreviation in the mime_type_abbreviations array. +# If not present assume the user provided a valid mime type +# +############################################################################## +lookup_mime_type() { + local mime_type=$1 + + if [[ ${mime_type_abbreviations[$mime_type]} ]]; then + echo ${mime_type_abbreviations[$mime_type]} + else + echo $1 + fi +} + +############################################################################## +# +# Converts an associative array into a list of cURL header +# arguments (-H "KEY: VALUE") +# +############################################################################## +header_arguments_to_curl() { + local headers_curl="" + local api_key_header="" + local api_key_header_in_cli="" +{{#hasAuthMethods}} +{{#authMethods}} +{{#isApiKey}} +{{#isKeyInHeader}} + api_key_header="{{keyParamName}}" +{{/isKeyInHeader}} +{{/isApiKey}} +{{/authMethods}} +{{/hasAuthMethods}} + + for key in "${!header_arguments[@]}"; do + headers_curl+="-H \"${key}: ${header_arguments[${key}]}\" " + if [[ "${key}XX" == "${api_key_header}XX" ]]; then + api_key_header_in_cli="YES" + fi + done +{{#hasAuthMethods}} +{{#authMethods}} +{{#isApiKey}} +{{#isKeyInHeader}} + # + # If the api_key was not provided in the header, try one from the + # environment variable + # + if [[ -z $api_key_header_in_cli && -n $apikey_auth_credential ]]; then + headers_curl+="-H \"${api_key_header}: ${apikey_auth_credential}\"" + fi +{{/isKeyInHeader}} +{{/isApiKey}} +{{/authMethods}} +{{/hasAuthMethods}} + headers_curl+=" " + + echo "${headers_curl}" +} + +############################################################################## +# +# Converts an associative array into a simple JSON with keys as top +# level object attributes +# +# \todo Add convertion of more complex attributes using paths +# +############################################################################## +body_parameters_to_json() { + local body_json="-d '{" + local body_parameter_count=${#body_parameters[@]} + local count=0 + for key in "${!body_parameters[@]}"; do + body_json+="\"${key}\": ${body_parameters[${key}]}" + if [[ $count -lt $body_parameter_count-1 ]]; then + body_json+=", " + fi + count+=1 + done + body_json+="}'" + + if [[ "${#body_parameters[@]}" -eq 0 ]]; then + echo "" + else + echo "${body_json}" + fi +} + +############################################################################## +# +# Check if provided parameters match specification requirements +# +############################################################################## +validate_request_parameters() { + local path_template=$1 + local -n path_params=$2 + local -n query_params=$3 + + # First replace all path parameters in the path + for pparam in "${path_params[@]}"; do + regexp="(.*)(\{$pparam\})(.*)" + if [[ $path_template =~ $regexp ]]; then + path_template=${BASH_REMATCH[1]}${operation_parameters[$pparam]}${BASH_REMATCH[3]} + fi + done + + # Now append query parameters - if any + if [[ ${#query_params[@]} -gt 0 ]]; then + path_template+="?" + fi + + local query_parameter_count=${#query_params[@]} + local count=0 + for qparam in "${query_params[@]}"; do + # Get the array of parameter values + local parameter_values=($(echo "${operation_parameters[$qparam]}" | sed -e 's/'":::"'/\n/g' | while read line; do echo $line | sed 's/[\t ]/'":::"'/g'; done)) + + # + # Check if the number of provided values is not less than minimum + # required + # + if [[ "$force" = false ]]; then + if [[ ${#parameter_values[@]} -lt ${operation_parameters_minimum_occurences["${operation}:::${qparam}"]} ]]; then + echo "Error: Too few values provided for '${qparam}' parameter" + exit 1 + fi + + # + # Check if the number of provided values is not more than maximum + # + if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + if [[ "$force" = false ]]; then + echo "Error: Too many values provided for '${qparam}' parameter" + exit 1 + fi + fi + fi + + if [[ "${operation_parameters_collection_type[${operation}:::${qparam}]}" == "" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="&" + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "multi" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="&" + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "csv" ]]; then + path_template+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="," + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "ssv" ]]; then + path_template+="${qparam}=" + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+=" " + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "tsv" ]]; then + path_template+="${qparam}=" + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="\t" + fi + vcount+=1 + done + else + echo -e "" + echo -e "Error: Unsupported collection format " + echo -e "" + exit 1 + fi + + + if [[ $count -lt $query_parameter_count-1 ]]; then + path_template+="&" + fi + count+=1 + done + +} + + + +############################################################################## +# +# Build request path including query parameters +# +############################################################################## +build_request_path() { + local path_template=$1 + local -n path_params=$2 + local -n query_params=$3 + + + # First replace all path parameters in the path + for pparam in "${path_params[@]}"; do + regexp="(.*)(\{$pparam\})(.*)" + if [[ $path_template =~ $regexp ]]; then + path_template=${BASH_REMATCH[1]}${operation_parameters[$pparam]}${BASH_REMATCH[3]} + fi + done + + local query_request_part="" + + local query_parameter_count=${#query_params[@]} + local count=0 + for qparam in "${query_params[@]}"; do + # Get the array of parameter values + local parameter_values=($(echo "${operation_parameters[$qparam]}" | sed -e 's/'":::"'/\n/g' | while read line; do echo $line | sed 's/[\t ]/'":::"'/g'; done)) + local parameter_value="" + + # + # Check if the number of provided values is not less than minimum + # required + # + if [[ "$force" = false ]]; then + if [[ ${#parameter_values[@]} -lt ${operation_parameters_minimum_occurences["${operation}:::${qparam}"]} ]]; then + echo "Error: Too few values provided for '${qparam}' parameter" + exit 1 + fi + + # + # Check if the number of provided values is not more than maximum + # + if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + if [[ "$force" = false ]]; then + echo "Error: Too many values provided for '${qparam}' parameter" + exit 1 + fi + fi + fi + + # + # Append parameters without specific cardinality + # + if [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="&" + fi + vcount+=1 + done + # + # Append parameters specified as 'mutli' collections i.e. param=value1¶m=value2&... + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "multi" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="&" + fi + vcount+=1 + done + # + # Append parameters specified as 'csv' collections i.e. param=value1,value2,... + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "csv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="," + fi + vcount+=1 + done + # + # Append parameters specified as 'ssv' collections i.e. param="value1 value2 ..." + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "ssv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+=" " + fi + vcount+=1 + done + # + # Append parameters specified as 'tsv' collections i.e. param="value1\tvalue2\t..." + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "tsv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="\t" + fi + vcount+=1 + done + fi + + if [[ -n "${parameter_value}" ]]; then + query_request_part+="${parameter_value}" + fi + + if [[ $count -lt $query_parameter_count-1 && -n "${parameter_value}" ]]; then + query_request_part+="&" + fi + + count+=1 + + done + + + # Now append query parameters - if any + if [[ -n "${query_request_part}" ]]; then + path_template+="?$(echo ${query_request_part} | sed s'/&$//')" + fi + + echo $path_template +} + + + +############################################################################### +# +# Print main help message +# +############################################################################### +print_help() { +cat <$(tput sgr0)] + [-ac|--accept $(tput setaf 2)$(tput sgr0)] [-ct,--content-type $(tput setaf 2)$(tput sgr0)] + [--host $(tput setaf 6)$(tput sgr0)] [--dry-run] $(tput setaf 3)$(tput sgr0) [-h|--help] [$(tput setaf 4)$(tput sgr0)] + [$(tput setaf 5)$(tput sgr0)] [$(tput setaf 5)$(tput sgr0)] + + - $(tput setaf 6)$(tput sgr0) - endpoint of the REST service without basepath +{{#x-codegen-host-env}} Can also be specified in {{x-codegen-host-env}} environment variable.{{/x-codegen-host-env}} + - $(tput setaf 1)$(tput sgr0) - any valid cURL options can be passed before $(tput setaf 3)$(tput sgr0) + - $(tput setaf 2)$(tput sgr0) - either full mime-type or one of supported abbreviations: + (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, + rdf, jpg, png, gif, bmp, tiff) + - $(tput setaf 4)$(tput sgr0) - HTTP headers can be passed in the form $(tput setaf 3)HEADER$(tput sgr0):$(tput setaf 4)VALUE$(tput sgr0) + - $(tput setaf 5)$(tput sgr0) - REST operation parameters can be passed in the following + forms: + * $(tput setaf 3)KEY$(tput sgr0)=$(tput setaf 4)VALUE$(tput sgr0) - path or query parameters + - $(tput setaf 5)$(tput sgr0) - simple JSON body content (first level only) can be build + using the following arguments: + * $(tput setaf 3)KEY$(tput sgr0)==$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": "$(tput setaf 4)VALUE$(tput sgr0)", ... }' + * $(tput setaf 3)KEY$(tput sgr0):=$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": $(tput setaf 4)VALUE$(tput sgr0), ... }' + +EOF +{{#hasAuthMethods}} + echo -e "$(tput bold)$(tput setaf 7)Authentication methods$(tput sgr0)" + echo -e "" +{{#authMethods}} +{{#isBasic}} + echo -e " - $(tput setaf 4)Basic AUTH$(tput sgr0) - add '-u :' before $(tput setaf 3)$(tput sgr0)" + {{#x-codegen-basicauth-env}}echo -e " or export $(tput setaf 1){{x-codegen-basicauth-env}}=':'$(tput sgr0)"{{/x-codegen-basicauth-env}} +{{/isBasic}} +{{#isApiKey}} +{{#isKeyInHeader}} + echo -e " - $(tput setaf 4)Api-key$(tput sgr0) - add '$(tput setaf 1){{keyParamName}}:$(tput sgr0)' after $(tput setaf 3)$(tput sgr0)" +{{/isKeyInHeader}} +{{#isKeyInQuery}} + echo -e " - $(tput setaf 4)Api-key$(tput sgr0) - add '$(tput setaf 1){{keyParamName}}=$(tput sgr0)' after $(tput setaf 3)$(tput sgr0)" +{{/isKeyInQuery}} + {{#x-codegen-apikey-env}}echo -e " or export $(tput setaf 1){{x-codegen-apikey-env}}=''$(tput sgr0)"{{/x-codegen-apikey-env}} +{{/isApiKey}} +{{#isOAuth}} + echo -e " - $(tput setaf 5)OAuth2 (flow: {{flow}})$(tput sgr0)" + echo -e " Authorization URL: " + echo -e " * {{authorizationUrl}}" + echo -e " Scopes:" +{{#scopes}} + echo -e " * {{scope}} - {{description}}" +{{/scopes}} +{{/isOAuth}} +{{/authMethods}} + echo "" +{{/hasAuthMethods}} + echo -e "$(tput bold)$(tput setaf 7)Operations (grouped by tags)$(tput sgr0)" +{{#apiInfo}} +{{#apis}} + echo "" + echo -e "$(tput bold)$(tput setaf 7)[{{classVarName}}]$(tput sgr0)" +read -d '' ops <$(tput sgr0)\t\t\t\tSpecify the host URL " +{{#swagger}} +{{#host}}echo -e " \t\t\t\t(e.g. 'https://{{host}}')"{{/host}} +{{^host}}echo -e " \t\t\t\t(e.g. 'https://127.0.0.1:8080')"{{/host}} +{{/swagger}} + echo -e " --force\t\t\t\tForce command invocation in spite of missing" + echo -e " \t\t\t\trequired parameters or wrong content type" + echo -e " --dry-run\t\t\t\tPrint out the cURL command without" + echo -e " \t\t\t\texecuting it" + echo -e " -ac,--accept $(tput setaf 3)$(tput sgr0)\t\tSet the 'Accept' header in the request" + echo -e " -ct,--content-type $(tput setaf 3)$(tput sgr0)\tSet the 'Content-type' header in " + echo -e " \tthe request" + echo "" +} + + +############################################################################## +# +# Print REST service description +# +############################################################################## +print_about() { + echo "" + echo -e "$(tput bold)$(tput setaf 7){{appName}} command line client (API version {{#swagger}}{{#info}}{{version}}{{/info}}{{/swagger}})$(tput sgr0)" + echo "" + echo -e "License: {{#swagger}}{{#info}}{{#license}}{{name}}{{/license}}{{/info}}{{/swagger}}" + echo -e "Contact: {{#swagger}}{{#info}}{{#contact}}{{email}}{{/contact}}{{/info}}{{/swagger}}" + echo "" +read -d '' appdescription </dev/null 2>&1 || { echo >&2 "Error: You do not have 'cURL' installed."; exit 1; } +type sed >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'sed' installed."; exit 1; } +type column >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'bsdmainutils' installed."; exit 1; } + +# +# Process command line +# +# Pass all arguemnts before 'operation' to cURL except the ones we override +# +take_user=false +take_host=false +take_accept_header=false +take_contenttype_header=false + +for key in "$@"; do +# Take the value of -u|--user argument +if [[ "$take_user" = true ]]; then + basic_auth_credential="$key" + take_user=false + continue +fi +# Take the value of --host argument +if [[ "$take_host" = true ]]; then + host="$key" + take_host=false + continue +fi +# Take the value of --accept argument +if [[ "$take_accept_header" = true ]]; then + header_accept=$(lookup_mime_type "$key") + take_accept_header=false + continue +fi +# Take the value of --content-type argument +if [[ "$take_contenttype_header" = true ]]; then + header_content_type=$(lookup_mime_type "$key") + take_contenttype_header=false + continue +fi +case $key in + -h|--help) + if [[ "x$operation" == "x" ]]; then + print_help + exit 0 + else + eval "print_${operation}_help" + exit 0 + fi + ;; + -V|--version) + print_version + exit 0 + ;; + --about) + print_about + exit 0 + ;; + -u|--user) + take_user=true + ;; + --host) + take_host=true + ;; + --force) + force=true + ;; + -ac|--accept) + take_accept_header=true + ;; + -ct|--content-type) + take_contenttype_header=true + ;; + --dry-run) + print_curl=true + ;; +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{operationId}}) + operation="{{operationId}}" + ;; +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + *==*) + # Parse body arguments and convert them into top level + # JSON properties passed in the body content as strings + if [[ "$operation" ]]; then + IFS='==' read body_key sep body_value <<< "$key" + body_parameters[${body_key}]="\"${body_value}\"" + fi + ;; + *:=*) + # Parse body arguments and convert them into top level + # JSON properties passed in the body content without qoutes + if [[ "$operation" ]]; then + IFS=':=' read body_key sep body_value <<< "$key" + body_parameters[${body_key}]=${body_value} + fi + ;; + *:*) + # Parse header arguments and convert them into curl + # only after the operation argument + if [[ "$operation" ]]; then + IFS=':' read header_name header_value <<< "$key" +{{#hasAuthMethods}} +{{#authMethods}} +{{#isApiKey}} +{{#isKeyInHeader}} + # + # If the header key is the same as the api_key expected by API in the + # header, override the ${apikey_auth_credential} variable + # + if [[ $header_name == "{{keyParamName}}" ]]; then + apikey_auth_credential=$header_value + fi +{{/isKeyInHeader}} +{{/isApiKey}} +{{/authMethods}} +{{/hasAuthMethods}} + header_arguments[$header_name]=$header_value + else + curl_arguments+=" $key" + fi + ;; + -) + body_content_temp_file=$(mktemp) + cat - > $body_content_temp_file + ;; + *=*) + # Parse operation arguments and convert them into curl + # only after the operation argument + if [[ "$operation" ]]; then + IFS='=' read parameter_name parameter_value <<< "$key" + if [[ -z "${operation_parameters[$parameter_name]+foo}" ]]; then + operation_parameters[$parameter_name]=$(url_escape "${parameter_value}") + else + operation_parameters[$parameter_name]+=":::"$(url_escape "${parameter_value}") + fi + else + curl_arguments+=" $key" + fi + ;; + *) + # If we are before the operation, treat the arguments as cURL arguments + if [[ "x$operation" == "x" ]]; then + # Maintain quotes around cURL arguments if necessary + space_regexp="[[:space:]]" + if [[ $key =~ $space_regexp ]]; then + curl_arguments+=" \"$key\"" + else + curl_arguments+=" $key" + fi + fi + ;; +esac +done + + +# Check if user provided host name +if [[ -z "$host" ]]; then + echo "Error: No hostname provided!!!" + echo "Check usage: '${script_name} --help'" + exit 1 +fi + +# Check if user specified operation ID +if [[ -z "$operation" ]]; then + echo "Error: No operation specified!" + echo "Check available operations: '${script_name} --help'" + exit 1 +fi + + +# Run cURL command based on the operation ID +case $operation in +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{operationId}}) + call_{{operationId}} + ;; +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + *) + echo "Error: Unknown operation: $operation" + echo "" + print_help + exit 1 +esac diff --git a/modules/swagger-codegen/src/main/resources/bash/zsh-completion.mustache b/modules/swagger-codegen/src/main/resources/bash/zsh-completion.mustache new file mode 100644 index 00000000000..064b9a01fe0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/bash/zsh-completion.mustache @@ -0,0 +1,338 @@ +#compdef {{scriptName}} + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Based on: https://github.com/Valodim/zsh-curl-completion/blob/master/_curl +# ! +# ! Generated on: {{generatedDate}} +# ! +# ! +# ! Installation: +# ! +# ! Copy the _{{scriptName}} file to any directory under FPATH +# ! environment variable (echo $FPATH) +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + +local curcontext="$curcontext" state line ret=1 +typeset -A opt_args + +typeset -A mime_type_abbreviations +# text/* +mime_type_abbreviations[text]="text/plain" +mime_type_abbreviations[html]="text/html" +mime_type_abbreviations[md]="text/x-markdown" +mime_type_abbreviations[csv]="text/csv" +mime_type_abbreviations[css]="text/css" +mime_type_abbreviations[rtf]="text/rtf" +# application/* +mime_type_abbreviations[json]="application/json" +mime_type_abbreviations[xml]="application/xml" +mime_type_abbreviations[yaml]="application/yaml" +mime_type_abbreviations[js]="application/javascript" +mime_type_abbreviations[bin]="application/octet-stream" +mime_type_abbreviations[rdf]="application/rdf+xml" +# image/* +mime_type_abbreviations[jpg]="image/jpeg" +mime_type_abbreviations[png]="image/png" +mime_type_abbreviations[gif]="image/gif" +mime_type_abbreviations[bmp]="image/bmp" +mime_type_abbreviations[tiff]="image/tiff" + +# +# Generate zsh completion string list for abbreviated mime types +# +get_mime_type_completions() { + typeset -a result + result=() + for k in "${(@k)mime_type_abbreviations}"; do + value=$mime_type_abbreviations[${k}] + #echo $value + result+=( "${k}[${value}]" ) + #echo $result + done + echo "$result" +} + +# +# cURL crypto engines completion function +# +_curl_crypto_engine() { + local vals + vals=( ${${(f)"$(curl --engine list)":gs/ /}[2,$]} ) + _describe -t outputs 'engines' vals && return 0 +} + +# +# cURL post data completion functions= +# +_curl_post_data() { + + # don't do anything further if this is raw content + compset -P '=' && _message 'raw content' && return 0 + + # complete filename or stdin for @ syntax + compset -P '*@' && { + local expl + _description files expl stdin + compadd "$expl[@]" - "-" + _files + return 0 + } + + # got a name already? expecting data. + compset -P '*=' && _message 'data value' && return 0 + + # otherwise, name (or @ or =) should be specified + _message 'data name' && return 0 + +} + + +local arg_http arg_ftp arg_other arg_proxy arg_crypto arg_connection arg_auth arg_input arg_output + +# HTTP Arguments +arg_http=(''\ + {-0,--http1.0}'[force use of use http 1.0 instead of 1.1]' \ + {-b,--cookie}'[pass data to http server as cookie]:data or file' \ + {-c,--cookie-jar}'[specify cookie file]:file name:_files' \ + {-d,--data}'[send specified data as HTTP POST data]:data:{_curl_post_data}' \ + '--data-binary[post HTTP POST data without any processing]:data:{_curl_post_data}' \ + '--data-urlencode[post HTTP POST data, with url encoding]:data:{_curl_post_data}' \ + {-f,--fail}'[enable failfast behavior for server errors]' \ + '*'{-F,--form}'[add POST form data]:name=content' \ + {-G,--get}'[use HTTP GET even with data (-d, --data, --data-binary)]' \ + '*'{-H,--header}'[specify an extra header]:header' \ + '--ignore-content-length[ignore Content-Length header]' \ + {-i,--include}'[include HTTP header in the output]' \ + {-j,--junk-session-cookies}'[discard all session cookies]' \ + {-e,--referer}'[send url as referer]:referer url:_urls' \ + {-L,--location}'[follow Location headers on http 3XX response]' \ + '--location-trusted[like --location, but allows sending of auth data to redirected hosts]' \ + '--max-redirs[set maximum number of redirection followings allowed]:number' \ + {-J,--remote-header-name}'[use Content-Disposition for output file name]' \ + {-O,--remote-name}'[write to filename parsed from url instead of stdout]' \ + '--post301[do not convert POST to GET after following 301 Location response (follow RFC 2616/10.3.2)]' \ + '--post302[do not convert POST to GET after following 302 Location response (follow RFC 2616/10.3.2)]' \ + ) + +# FTP arguments +arg_ftp=(\ + {-a,--append}'[append to target file instead of overwriting (FTP/SFTP)]' \ + '--crlf[convert LF to CRLF in upload]' \ + '--disable-eprt[disable use of EPRT and LPRT for active FTP transfers]' \ + '--disable-epsv[disable use of EPSV for passive FTP transfers]' \ + '--ftp-account[account data (FTP)]:data' \ + '--ftp-alternative-to-user[command to send when USER and PASS commands fail (FTP)]:command' \ + '--ftp-create-dirs[create paths remotely if it does not exist]' \ + '--ftp-method[ftp method to use to reach a file (FTP)]:method:(multicwd ocwd singlecwd)' \ + '--ftp-pasv[use passive mode for the data connection (FTP)]' \ + '--ftp-skip-pasv-ip[do not use the ip the server suggests for PASV]' \ + '--form-string[like --form, but do not parse content]:name=string' \ + '--ftp-pret[send PRET before PASV]' \ + '--ftp-ssl-ccc[use clear command channel (CCC) after authentication (FTP)]' \ + '--ftp-ssl-ccc-mode[sets the CCC mode (FTP)]:mode:(active passive)' \ + '--ftp-ssl-control[require SSL/TLS for FTP login, clear for transfer]' \ + {-l,--list-only}'[list names only when listing directories (FTP)]' \ + {-P,--ftp-port}'[use active mode, tell server to connect to specified address or interface (FTP]:address' \ + '*'{-Q,--quote}'[send arbitrary command to the remote server before transfer (FTP/SFTP)]:command' \ + ) + +# Other Protocol arguments +arg_other=(\ + '--mail-from[specify From: address]:address' \ + '--mail-rcpt[specify email recipient for SMTP, may be given multiple times]:address' \ + {-t,--telnet-option}'[pass options to telnet protocol]:opt=val' \ + '--tftp-blksize[set tftp BLKSIZE option]:value' \ + ) + +# Proxy arguments +arg_proxy=(\ + '--noproxy[list of hosts to connect directly to instead of through proxy]:no-proxy-list' \ + {-p,--proxytunnel}'[tunnel non-http protocols through http proxy]' \ + {-U,--proxy-user}'[specify the user name and password to use for proxy authentication]:user:password' \ + '--proxy-anyauth[use any authentication method for proxy, default to most secure]' \ + '--proxy-basic[use HTTP Basic authentication for proxy]' \ + '--proxy-digest[use http digest authentication for proxy]' \ + '--proxy-negotiate[enable GSS-Negotiate authentication for proxy]' \ + '--proxy-ntlm[enable ntlm authentication for proxy]' \ + '--proxy1.0[use http 1.0 proxy]:proxy url' \ + {-x,--proxy}'[use specified proxy]:proxy url' \ + '--socks5-gssapi-service[change service name for socks server]:servicename' \ + '--socks5-gssapi-nec[allow unprotected exchange of protection mode negotiation]' \ + ) + +# Crypto arguments +arg_crypto=(\ + {-1,--tlsv1}'[Forces curl to use TLS version 1 when negotiating with a remote TLS server.]' \ + {-2,--sslv2}'[Forces curl to use SSL version 2 when negotiating with a remote SSL server.]' \ + {-3,--sslv3}'[Forces curl to use SSL version 3 when negotiating with a remote SSL server.]' \ + '--ciphers[specifies which cipher to use for the ssl connection]:list of ciphers' \ + '--crlfile[specify file with revoked certificates]:file' \ + '--delegation[set delegation policy to use with GSS/kerberos]:delegation policy:(none policy always)' \ + {-E,--cert}'[use specified client certificate]:certificate file:_files' \ + '--engine[use selected OpenSSL crypto engine]:ssl crypto engine:{_curl_crypto_engine}' \ + '--egd-file[set ssl entropy gathering daemon socket]:entropy socket:_files' \ + '--cert-type[specify certificate type (PEM, DER, ENG)]:certificate type:(PEM DER ENG)' \ + '--cacert[specify certificate file to verify the peer with]:CA certificate:_files' \ + '--capath[specify a search path for certificate files]:CA certificate directory:_directories' \ + '--hostpubmd5[check remote hosts public key]:md5 hash' \ + {-k,--insecure}'[allow ssl to perform insecure ssl connections (ie, ignore certificate)]' \ + '--key[ssl/ssh private key file name]:key file:_files' \ + '--key-type[ssl/ssh private key file type]:file type:(PEM DER ENG)' \ + '--pubkey[ssh public key file]:pubkey file:_files' \ + '--random-file[set source of random data for ssl]:random source:_files' \ + '--no-sessionid[disable caching of ssl session ids]' \ + '--pass:phrase[passphrase for ssl/ssh private key]' \ + '--ssl[try to use ssl/tls for connection, if available]' \ + '--ssl-reqd[try to use ssl/tls for connection, fail if unavailable]' \ + '--tlsauthtype[set TLS authentication type (only SRP supported!)]:authtype' \ + '--tlsuser[set username for TLS authentication]:user' \ + '--tlspassword[set password for TLS authentication]:password' \ + ) + +# Connection arguments +arg_connection=(\ + {-4,--ipv4}'[prefer ipv4]' \ + {-6,--ipv6}'[prefer ipv6, if available]' \ + {-B,--use-ascii}'[use ascii mode]' \ + '--compressed[request a compressed transfer]' \ + '--connect-timeout[timeout for connection phase]:seconds' \ + {-I,--head}'[fetch http HEAD only (HTTP/FTP/FILE]' \ + '--interface[work on a specific interface]:name' \ + '--keepalive-time[set time to wait before sending keepalive probes]:seconds' \ + '--limit-rate[specify maximum transfer rate]:speed' \ + '--local-port[set preferred number or range of local ports to use]:num' \ + {-N,--no-buffer}'[disable buffering of the output stream]' \ + '--no-keepalive[disable use of keepalive messages in TCP connections]' \ + '--raw[disable all http decoding and pass raw data]' \ + '--resolve[provide a custom address for a specific host and port pair]:host\:port\:address' \ + '--retry[specify maximum number of retries for transient errors]:num' \ + '--retry-delay[specify delay between retries]:seconds' \ + '--retry-max-time[maximum time to spend on retries]:seconds' \ + '--tcp-nodelay[turn on TCP_NODELAY option]' \ + {-y,--speed-time}'[specify time to abort after if download is slower than speed-limit]:time' \ + {-Y,--speed-limit}'[specify minimum speed for --speed-time]:speed' \ + ) + +# Authentication arguments +arg_auth=(\ + '--anyauth[use any authentication method, default to most secure]' \ + '--basic[use HTTP Basic authentication]' \ + '--ntlm[enable ntlm authentication]' \ + '--digest[use http digest authentication]' \ + '--krb[use kerberos authentication]:auth:(clear safe confidential private)' \ + '--negotiate[enable GSS-Negotiate authentication]' \ + {-n,--netrc}'[scan ~/.netrc for login data]' \ + '--netrc-optional[like --netrc, but does not make .netrc usage mandatory]' \ + '--netrc-file[like --netrc, but specify file to use]:netrc file:_files' \ + '--tr-encoding[request compressed transfer-encoding]' \ + {-u,--user}'[specify user name and password for server authentication]:user\:password' \ + ) + +# Input arguments +arg_input=(\ + {-C,--continue-at}'[resume at offset ]:offset' \ + {-g,--globoff}'[do not glob {}\[\] letters]' \ + '--max-filesize[maximum filesize to download, fail for bigger files]:bytes' \ + '--proto[specify allowed protocols for transfer]:protocols' \ + '--proto-redir[specify allowed protocols for transfer after a redirect]:protocols' \ + {-r,--range}'[set range of bytes to request (HTTP/FTP/SFTP/FILE)]:range' \ + {-R,--remote-time}'[use timestamp of remote file for local file]' \ + {-T,--upload-file}'[transfer file to remote url (using PUT for HTTP)]:file to upload:_files' \ + '--url[specify a URL to fetch (multi)]:url:_urls' \ + {-z,--time-cond}'[request downloaded file to be newer than date or given reference file]:date expression' \ + ) + +# Output arguments +arg_output=(\ + '--create-dirs[create local directory hierarchy as needed]' \ + {-D,--dump-header}'[write protocol headers to file]:dump file:_files' \ + {-o,--output}'[write to specified file instead of stdout]:output file:_files' \ + {--progress-bar,-\#}'[display progress as a simple progress bar]' \ + {-\#,--progress-bar}'[Make curl display progress as a simple progress bar instead of the standard, more informational, meter.]' \ + {-R,--remote-time}'[use timestamp of remote file for local file]' \ + '--raw[disable all http decoding and pass raw data]' \ + {-s,--silent}'[silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[show errors in silent mode]' \ + '--stderr[redirect stderr to specified file]:output file:_files' \ + '--trace[enable full trace dump of all incoming and outgoing data]:trace file:_files' \ + '--trace-ascii[enable full trace dump of all incoming and outgoing data, without hex data]:trace file:_files' \ + '--trace-time[prepends a time stamp to each trace or verbose line that curl displays]' \ + {-v,--verbose}'[output debug info]' \ + {-w,--write-out}'[specify message to output on successful operation]:format string' \ + '--xattr[store some file metadata in extended file attributes]' \ + {-X,--request}'[specifies request method for HTTP server]:method:(GET POST PUT DELETE HEAD OPTIONS TRACE CONNECT PATCH LINK UNLINK)' \ + ) + +_arguments -C -s $arg_http $arg_ftp $arg_other $arg_crypto $arg_connection $arg_auth $arg_input $arg_output \ + {-M,--manual}'[Print manual]' \ + '*'{-K,--config}'[Use other config file to read arguments from]:config file:_files' \ + '--libcurl[output libcurl code for the operation to file]:output file:_files' \ + {-m,--max-time}'[Limit total time of operation]:seconds' \ + {-s,--silent}'[Silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[Show errors in silent mode]' \ + '--stderr[Redirect stderr to specified file]:output file:_files' \ + '-q[Do not read settings from .curlrc (must be first option)]' \ + {-h,--help}'[Print help and list of operations]' \ + {-V,--version}'[Print service API version]' \ + '--about[Print the information about service]' \ + '--host[Specify the host URL]':URL:_urls \ + '--dry-run[Print out the cURL command without executing it]' \ + {-ac,--accept}'[Set the Accept header in the request]: :{_values "Accept mime type" $(get_mime_type_completions)}' \ + {-ct,--content-type}'[Set the Content-type header in request]: :{_values "Content mime type" $(get_mime_type_completions)}' \ + '1: :->ops' \ + '*:: :->args' \ + && ret=0 + + +case $state in + ops) + # Operations + _values "Operations" \ +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + "{{operationId}}[{{{summary}}}]" {{#hasMore}}\ +{{/hasMore}}{{/operation}}{{/operations}}{{/apis}}{{#hasMore}}\ +{{/hasMore}} +{{/apiInfo}} + + _arguments "(--help)--help[Print information about operation]" + + ret=0 + ;; + args) + case $line[1] in +{{#apiInfo}} +{{#apis}} +{{#operations}} +{{#operation}} + {{operationId}}) + local -a _op_arguments + _op_arguments=( + {{#pathParams}}"{{baseName}}=:[PATH] {{description}}" +{{/pathParams}} {{#queryParams}}{{#isBoolean}}"{{baseName}}=true:[QUERY] {{description}}" + "{{baseName}}=false:[QUERY] {{description}}"{{/isBoolean}}{{^isBoolean}}"{{baseName}}=:[QUERY] {{description}}"{{/isBoolean}} +{{/queryParams}} {{#headerParams}}"{{baseName}}\::[HEADER] {{description}}" +{{/headerParams}}) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; +{{/operation}} +{{/operations}} +{{/apis}} +{{/apiInfo}} + esac + ;; + +esac + +return ret diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache index 466f914d4a9..91400f163aa 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-header.mustache @@ -38,6 +38,7 @@ public: static utility::string_t parameterToString(utility::string_t value); static utility::string_t parameterToString(int32_t value); static utility::string_t parameterToString(int64_t value); + static utility::string_t parameterToString(const utility::datetime &value); template static utility::string_t parameterToArrayString(std::vector value) diff --git a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache index e9a3810c7bd..4f86ad40540 100644 --- a/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache +++ b/modules/swagger-codegen/src/main/resources/cpprest/apiclient-source.mustache @@ -40,6 +40,11 @@ utility::string_t ApiClient::parameterToString(int32_t value) return utility::conversions::to_string_t(std::to_string(value)); } +utility::string_t ApiClient::parameterToString(const utility::datetime &value) +{ + return utility::conversions::to_string_t(value.to_string(utility::datetime::ISO_8601)); +} + pplx::task ApiClient::callApi( const utility::string_t& path, const utility::string_t& method, diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 33b631280c2..8960ccfe59e 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -19,7 +19,7 @@ namespace {{packageName}}.Client /// /// API client is mainly responsible for making the HTTP call to the API backend. /// - public partial class ApiClient + {{>visibility}} partial class ApiClient { private JsonSerializerSettings serializerSettings = new JsonSerializerSettings { diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache index ad7c2264d78..ca8044580f2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache @@ -6,7 +6,7 @@ namespace {{packageName}}.Client /// /// API Exception /// - public class ApiException : Exception + {{>visibility}} class ApiException : Exception { /// /// Gets or sets the error code (HTTP status code) diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache index d8c1b79e545..d04575d7ad9 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache @@ -7,7 +7,7 @@ namespace {{packageName}}.Client /// /// API Response /// - public class ApiResponse + {{>visibility}} class ApiResponse { /// /// Gets or sets the status code (HTTP status code) diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 108b85e48f8..904b689e45e 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -11,7 +11,7 @@ namespace {{packageName}}.Client /// /// Represents a set of configuration settings /// - public class Configuration + {{>visibility}} class Configuration { /// /// Initializes a new instance of the Configuration class with different settings @@ -234,7 +234,7 @@ namespace {{packageName}}.Client return apiKeyValue; } - private string _tempFolderPath = Path.GetTempPath(); + private string _tempFolderPath; /// /// Gets or sets the temporary folder path to store the files downloaded from the server. @@ -242,7 +242,15 @@ namespace {{packageName}}.Client /// Folder path. public String TempFolderPath { - get { return _tempFolderPath; } + get + { + // default to Path.GetTempPath() if _tempFolderPath is not set + if (String.IsNullOrEmpty(_tempFolderPath)) + { + _tempFolderPath = Path.GetTempPath(); + } + return _tempFolderPath; + } set { diff --git a/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache b/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache index c25b88ee614..f0ebb0b31ce 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ExceptionFactory.mustache @@ -10,6 +10,6 @@ namespace {{packageName}}.Client /// /// Method name /// Response - /// Exceptions - public delegate Exception ExceptionFactory(string methodName, IRestResponse response); + /// Exceptions + {{>visibility}} delegate Exception ExceptionFactory(string methodName, IRestResponse response); } diff --git a/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache index df236b8f8c8..290c9b6ffdc 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/IApiAccessor.mustache @@ -11,7 +11,7 @@ namespace {{packageName}}.Client /// /// Represents configuration aspects required to interact with the API endpoints. /// - public interface IApiAccessor + {{>visibility}} interface IApiAccessor { /// /// Gets or sets the configuration object diff --git a/modules/swagger-codegen/src/main/resources/csharp/README.mustache b/modules/swagger-codegen/src/main/resources/csharp/README.mustache index bb228814338..8c08c0e8667 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/README.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/README.mustache @@ -51,6 +51,20 @@ using {{packageName}}.{{apiPackage}}; using {{packageName}}.Client; using {{packageName}}.{{modelPackage}}; ``` + + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out {{packageName}}.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + ## Getting Started diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index f62cabe42e0..c3d73306149 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -14,7 +14,7 @@ namespace {{packageName}}.{{apiPackage}} /// /// Represents a collection of functions to interact with the API endpoints /// - public interface I{{classname}} : IApiAccessor + {{>visibility}} interface {{interfacePrefix}}{{classname}} : IApiAccessor { #region Synchronous Operations {{#operation}} @@ -73,7 +73,7 @@ namespace {{packageName}}.{{apiPackage}} /// /// Represents a collection of functions to interact with the API endpoints /// - public partial class {{classname}} : I{{classname}} + {{>visibility}} partial class {{classname}} : {{interfacePrefix}}{{classname}} { private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; diff --git a/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache b/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache index 5249d754577..b11d14cdfc0 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/enumClass.mustache @@ -3,7 +3,7 @@ /// {{#description}} /// {{{description}}}{{/description}} [JsonConverter(typeof(StringEnumConverter))] - public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { {{#allowableValues}}{{#enumVars}} /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache index ff007904f46..b0dfa881eb2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelEnum.mustache @@ -3,7 +3,7 @@ /// {{#description}} /// {{{description}}}{{/description}} [JsonConverter(typeof(StringEnumConverter))] - public enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { {{#allowableValues}}{{#enumVars}} /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache index 5e1d0721dc2..09c232acefd 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelGeneric.mustache @@ -5,7 +5,7 @@ {{#generatePropertyChanged}} [ImplementPropertyChanged] {{/generatePropertyChanged}} - public partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}} IEquatable<{{classname}}>, IValidatableObject + {{>visibility}} partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}} IEquatable<{{classname}}>, IValidatableObject { {{#vars}} {{#isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache b/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache index 855a710c7ed..d851a2dddc6 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/modelInnerEnum.mustache @@ -4,7 +4,7 @@ /// {{#description}} /// {{{description}}}{{/description}} [JsonConverter(typeof(StringEnumConverter))] - public enum {{#datatypeWithEnum}}{{&.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} + {{>visibility}} enum {{#datatypeWithEnum}}{{&.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { {{#allowableValues}}{{#enumVars}} /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/nuspec.mustache b/modules/swagger-codegen/src/main/resources/csharp/nuspec.mustache new file mode 100644 index 00000000000..eaf4b0e3381 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/nuspec.mustache @@ -0,0 +1,45 @@ + + + + + $id$ + {{packageTitle}} + + + $version$ + + + $author$ + + + $author$ + false + false + + + {{packageDescription}}{{#termsOfService}} + {{termsOfService}}{{/termsOfService}}{{#licenseUrl}} + {{licenseUrl}}{{/licenseUrl}} + + + + + + {{#generatePropertyChanged}} + + {{/generatePropertyChanged}} + + + + + + + + {{#generatePropertyChanged}} + + {{/generatePropertyChanged}} + + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/csharp/visibility.mustache b/modules/swagger-codegen/src/main/resources/csharp/visibility.mustache new file mode 100644 index 00000000000..a1d1f4163d4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/visibility.mustache @@ -0,0 +1 @@ +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/elixir/README.md.mustache b/modules/swagger-codegen/src/main/resources/elixir/README.md.mustache new file mode 100644 index 00000000000..65c56e0ca61 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/elixir/README.md.mustache @@ -0,0 +1,18 @@ +# {{#modulized}}{{appName}}{{/modulized}} + +**TODO: Add description** + +## Installation + +If [available in Hex](https://hex.pm/docs/publish), the package can be installed +by adding `{{#underscored}}{{appName}}{{/underscored}}` to your list of dependencies in `mix.exs`: + +```elixir +def deps do + [{:{{#underscored}}{{appName}}{{/underscored}}, "~> 0.1.0"}] +end +``` + +Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) +and published on [HexDocs](https://hexdocs.pm). Once published, the docs can +be found at [https://hexdocs.pm/{{#underscored}}{{appName}}{{/underscored}}](https://hexdocs.pm/{{#underscored}}{{appName}}{{/underscored}}). diff --git a/modules/swagger-codegen/src/main/resources/elixir/api.mustache b/modules/swagger-codegen/src/main/resources/elixir/api.mustache new file mode 100644 index 00000000000..0e1a5fb9a5d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/elixir/api.mustache @@ -0,0 +1,28 @@ +defmodule {{#modulized}}{{appName}}{{/modulized}}.Api.{{classname}} do + @moduledoc """ + Documentation for {{#modulized}}{{appName}}{{/modulized}}.Api.{{classname}}. + """ + + use Tesla + + plug Tesla.Middleware.BaseUrl, "{{basePath}}" + plug Tesla.Middleware.JSON +{{#operations}} + {{#operation}} + + def {{#underscored}}{{operationId}}{{/underscored}}({{#allParams}}{{^-first}}, {{/-first}}{{#underscored}}{{paramName}}{{/underscored}}{{/allParams}}) do + method = [method: :{{#underscored}}{{httpMethod}}{{/underscored}}] + url = [url: "{{replacedPathName}}"] + query_params = [{{^queryParams.isEmpty}}query: [{{#queryParams}}{{^-first}}, {{/-first}}{:"{{paramName}}", {{#underscored}}{{paramName}}{{/underscored}}}{{/queryParams}}]{{/queryParams.isEmpty}}] + header_params = [{{^headerParams.isEmpty}}header: [{{#headerParams}}{{^-first}}, {{/-first}}{:"{{paramName}}", {{#underscored}}{{paramName}}{{/underscored}}}{{/headerParams}}]{{/headerParams.isEmpty}}] + body_params = [{{^bodyParams.isEmpty}}body: {{#bodyParams}}{{#underscored}}{{paramName}}{{/underscored}}{{/bodyParams}}{{/bodyParams.isEmpty}}] + form_params = [{{^formParams.isEmpty}}body: Enum.map_join([{{#formParams}}{{^-first}}, {{/-first}}{:"{{paramName}}", {{#underscored}}{{paramName}}{{/underscored}}}{{/formParams}}], "&", &("#{elem(&1, 0)}=#{elem(&1, 1)}")){{/formParams.isEmpty}}] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + {{/operation}} +{{/operations}} +end diff --git a/modules/swagger-codegen/src/main/resources/elixir/config.exs.mustache b/modules/swagger-codegen/src/main/resources/elixir/config.exs.mustache new file mode 100644 index 00000000000..810281e039a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/elixir/config.exs.mustache @@ -0,0 +1,30 @@ +# This file is responsible for configuring your application +# and its dependencies with the aid of the Mix.Config module. +use Mix.Config + +# This configuration is loaded before any dependency and is restricted +# to this project. If another project depends on this project, this +# file won't be loaded nor affect the parent project. For this reason, +# if you want to provide default values for your application for +# 3rd-party users, it should be done in your "mix.exs" file. + +# You can configure for your application as: +# +# config :{{#underscored}}{{appName}}{{/underscored}}, key: :value +# +# And access this configuration in your application as: +# +# Application.get_env(:{{#underscored}}{{appName}}{{/underscored}}, :key) +# +# Or configure a 3rd-party app: +# +# config :logger, level: :info +# + +# It is also possible to import configuration files, relative to this +# directory. For example, you can emulate configuration per environment +# by uncommenting the line below and defining dev.exs, test.exs and such. +# Configuration from the imported file will override the ones defined +# here (which is why it is important to import them last). +# +# import_config "#{Mix.env}.exs" diff --git a/modules/swagger-codegen/src/main/resources/elixir/mix.exs.mustache b/modules/swagger-codegen/src/main/resources/elixir/mix.exs.mustache new file mode 100644 index 00000000000..f2b467f77cc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/elixir/mix.exs.mustache @@ -0,0 +1,37 @@ +defmodule {{#modulized}}{{appName}}{{/modulized}}.Mixfile do + use Mix.Project + + def project do + [app: :{{#underscored}}{{appName}}{{/underscored}}, + version: "0.1.0", + elixir: "~> {{supportedElixirVersion}}", + build_embedded: Mix.env == :prod, + start_permanent: Mix.env == :prod, + deps: deps()] + end + + # Configuration for the OTP application + # + # Type "mix help compile.app" for more information + def application do + # Specify extra applications you'll use from Erlang/Elixir + [extra_applications: [{{extraApplications}}]] + end + + # Dependencies can be Hex packages: + # + # {:my_dep, "~> 0.3.0"} + # + # Or git/path repositories: + # + # {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} + # + # Type "mix help deps" for more examples and options + defp deps do + [ +{{#deps}} + {{{this}}}{{^-last}},{{/-last}} +{{/deps}} + ] + end +end diff --git a/modules/swagger-codegen/src/main/resources/elixir/model.mustache b/modules/swagger-codegen/src/main/resources/elixir/model.mustache new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/elixir/test_helper.exs.mustache b/modules/swagger-codegen/src/main/resources/elixir/test_helper.exs.mustache new file mode 100644 index 00000000000..869559e709e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/elixir/test_helper.exs.mustache @@ -0,0 +1 @@ +ExUnit.start() diff --git a/modules/swagger-codegen/src/main/resources/finch/DataAccessor.mustache b/modules/swagger-codegen/src/main/resources/finch/DataAccessor.mustache new file mode 100644 index 00000000000..e9700efc726 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/DataAccessor.mustache @@ -0,0 +1,27 @@ +package {{packageName}} + +// TODO: properly handle custom imports +import java.io._ +import java.util.Date + +import {{modelPackage}}._ + +trait DataAccessor { + // TODO: apiInfo -> apis -> operations = ??? + // NOTE: ??? throws a not implemented exception + +{{#apiInfo}} + {{#apis}} +{{#operations}} + {{#operation}} + /** + * {{{description}}} + * @return A {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} + */ + def {{baseName}}_{{operationId}}({{#allParams}}{{paramName}}: {{{dataType}}}{{^-last}}, {{/-last}}{{/allParams}}): {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} = ??? + + {{/operation}} +{{/operations}} + {{/apis}} +{{/apiInfo}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/JsonUtil.scala b/modules/swagger-codegen/src/main/resources/finch/JsonUtil.scala new file mode 100644 index 00000000000..691a82f563b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/JsonUtil.scala @@ -0,0 +1,12 @@ +package json + +import com.fasterxml.jackson.module.scala.DefaultScalaModule +import com.fasterxml.jackson.core.JsonGenerator.Feature +import com.fasterxml.jackson.databind._ + +object JsonUtil { + val mapper = new ObjectMapper() + mapper.registerModule(new DefaultScalaModule()) + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/README.mustache b/modules/swagger-codegen/src/main/resources/finch/README.mustache new file mode 100644 index 00000000000..327870827fd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/README.mustache @@ -0,0 +1,10 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled scalatra server. + +This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: + +[README](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/Server.mustache b/modules/swagger-codegen/src/main/resources/finch/Server.mustache new file mode 100644 index 00000000000..97f0fb79a09 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/Server.mustache @@ -0,0 +1,39 @@ +package {{packageName}} + +import io.finch._ +import io.finch.circe._ +import io.circe.{Decoder, ObjectEncoder} +import io.circe.generic.auto._ +import io.circe.generic.semiauto +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import com.twitter.finagle.Http +import com.twitter.finagle.util.LoadService +import com.twitter.util.{Await, Future} + +{{#imports}}import {{import}} +{{/imports}} + +class Server { + + // Loads implementation defined in resources/META-INF/services/{{packageName}}.DataAccessor + val db = LoadService[DataAccessor]() match { + case accessor :: _ => accessor + case _ => new DataAccessor { } + } + + val service = endpoint.makeService(db) + + val server = Http.serve(":8080", service) //creates service + + def close(): Future[Unit] = { + Await.ready(server.close()) + } +} + +/** + * Launches the PetstoreAPI service when the system is ready. + */ +object Server extends Server with App { + Await.ready(server) +} diff --git a/modules/swagger-codegen/src/main/resources/finch/api.mustache b/modules/swagger-codegen/src/main/resources/finch/api.mustache new file mode 100644 index 00000000000..8758174f6d3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/api.mustache @@ -0,0 +1,74 @@ +package {{apiPackage}} + +import java.io._ +import java.util.Date +import {{packageName}}._ +import {{modelPackage}}._ +{{#imports}}import {{import}} +{{/imports}} +import io.finch.circe._ +import io.circe.generic.semiauto._ +import com.twitter.concurrent.AsyncStream +import com.twitter.finagle.Service +import com.twitter.finagle.Http +import com.twitter.finagle.http.{Request, Response} +import com.twitter.finagle.http.exp.Multipart.{FileUpload, InMemoryFileUpload, OnDiskFileUpload} +import com.twitter.util.Future +import com.twitter.io.Buf +import io.finch._, items._ +import java.io.File + +object {{classname}} { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + def endpoints(da: DataAccessor) = + {{#operations}} + {{#operation}} + {{{operationId}}}(da){{^-last}} :+:{{/-last}} + {{/operation}} + {{/operations}} + + {{#operations}} + {{#operation}} + /** + * {{{description}}} + * @return And endpoint representing a {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} + */ + private def {{operationId}}(da: DataAccessor): Endpoint[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}] = + {{httpMethod}}({{{vendorExtensions.x-codegen-path}}} {{#allParams}}{{^isPathParam}} :: {{& vendorExtensions.x-codegen-normalized-path-type}}{{/isPathParam}}{{/allParams}}) { {{#hasParams}}({{#allParams}}{{paramName}}: {{{vendorExtensions.x-codegen-normalized-input-type}}}{{^-last}}, {{/-last}}{{/allParams}}) => {{/hasParams}} + {{#returnType}} + Ok(da.{{baseName}}_{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}})) + {{/returnType}} + {{^returnType}} + da.{{baseName}}_{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) + NoContent[Unit] + {{/returnType}} + } handle { + case e: Exception => BadRequest(e) + } + + {{/operation}} + {{/operations}} + + implicit private def fileUploadToFile(fileUpload: FileUpload) : File = { + fileUpload match { + case upload: InMemoryFileUpload => + bytesToFile(Buf.ByteArray.Owned.extract(upload.content)) + case upload: OnDiskFileUpload => + upload.content + case _ => null + } + } + + private def bytesToFile(input: Array[Byte]): java.io.File = { + val file = File.createTempFile("tmp{{classname}}", null) + val output = new FileOutputStream(file) + output.write(input) + file + } + + // This assists in params(string) application (which must be Seq[A] in parameter list) when the param is used as a List[A] elsewhere. + implicit def seqList[A](input: Seq[A]): List[A] = input.toList +} diff --git a/modules/swagger-codegen/src/main/resources/finch/bodyParam.mustache b/modules/swagger-codegen/src/main/resources/finch/bodyParam.mustache new file mode 100644 index 00000000000..07a90aa23cb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/bodyParam.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}bodyParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/bodyParamOperation.mustache b/modules/swagger-codegen/src/main/resources/finch/bodyParamOperation.mustache new file mode 100644 index 00000000000..cfb2bf49d23 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/bodyParamOperation.mustache @@ -0,0 +1,3 @@ + {{#isBodyParam}} + val {{paramName}} = parsedBody.extract[{{dataType}}] + {{/isBodyParam}} diff --git a/modules/swagger-codegen/src/main/resources/finch/build.sbt b/modules/swagger-codegen/src/main/resources/finch/build.sbt new file mode 100644 index 00000000000..b58544b46bd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/build.sbt @@ -0,0 +1,61 @@ +scalariformSettings + +organization := "io.swagger" + +name := "finch-sample" + +version := "0.1.0-SNAPSHOT" + +scalaVersion := "2.11.8" + +resolvers += Resolver.sonatypeRepo("snapshots") + +resolvers += "TM" at "http://maven.twttr.com" + +resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository" + +resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/" + +resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/" + +Defaults.itSettings + +scalacOptions ++= Seq( + "-deprecation", + "-encoding", "UTF-8", + "-feature", + "-language:existentials", + "-language:higherKinds", + "-language:implicitConversions", + "-unchecked", + "-Yno-adapted-args", + "-Ywarn-dead-code", + "-Ywarn-numeric-widen", + "-Xfuture", + "-Xlint", +// "-Ywarn-unused-import", + "-language:postfixOps" +) + +lazy val `it-config-sbt-project` = project.in(file(".")).configs(IntegrationTest) + +libraryDependencies ++= Seq( + "com.github.finagle" %% "finch-core" % "0.12.0", + "com.github.finagle" %% "finch-circe" % "0.12.0", + "io.circe" %% "circe-generic" % "0.7.0", + "io.circe" %% "circe-java8" % "0.7.0", + "com.twitter" %% "util-core" % "6.40.0", + "com.github.finagle" %% "finch-test" % "0.12.0" % "test", + "org.scalacheck" %% "scalacheck" % "1.13.4" % "test", + "org.scalatest" %% "scalatest" % "3.0.0" % "test" +) + +assemblyMergeStrategy in assembly := { + case "application.conf" => MergeStrategy.concat + case "about.html" => MergeStrategy.discard + case x => + val oldStrategy = (assemblyMergeStrategy in assembly).value + oldStrategy(x) +} + +addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full) diff --git a/modules/swagger-codegen/src/main/resources/finch/endpoint.mustache b/modules/swagger-codegen/src/main/resources/finch/endpoint.mustache new file mode 100644 index 00000000000..bb66defbe4f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/endpoint.mustache @@ -0,0 +1,50 @@ +package {{packageName}} + +import com.twitter.finagle.Service +import com.twitter.finagle.http.{Request, Response} +import com.twitter.finagle.http.exp.Multipart.FileUpload +import com.twitter.util.Future +import io.finch._, items._ +import io.circe.{Encoder, Json} +import io.finch.circe._ +import io.circe.generic.semiauto._ + +import {{apiPackage}}._ + +/** + * Provides the paths and endpoints for all the API's public service methods. + */ +object endpoint { + + def errorToJson(e: Exception): Json = e match { + case Error.NotPresent(_) => + Json.obj("error" -> Json.fromString("something_not_present")) + case Error.NotParsed(_, _, _) => + Json.obj("error" -> Json.fromString("something_not_parsed")) + case Error.NotValid(_, _) => + Json.obj("error" -> Json.fromString("something_not_valid")) + case error: PetstoreError => + Json.obj("error" -> Json.fromString(error.message)) + } + + implicit val ee: Encoder[Exception] = Encoder.instance { + case e: Error => errorToJson(e) + case Errors(nel) => Json.arr(nel.toList.map(errorToJson): _*) + } + + /** + * Compiles together all the endpoints relating to public service methods. + * + * @return A service that contains all provided endpoints of the API. + */ + def makeService(da: DataAccessor): Service[Request, Response] = ( + {{#apiInfo}} + {{#apis}} + {{classname}}.endpoints(da) {{^-last}} :+:{{/-last}} + {{/apis}} + {{/apiInfo}} + ).handle({ + case e: PetstoreError => NotFound(e) + }).toService + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/errors.mustache b/modules/swagger-codegen/src/main/resources/finch/errors.mustache new file mode 100644 index 00000000000..eb90b48052a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/errors.mustache @@ -0,0 +1,27 @@ +package {{packageName}} + +/** + * The parent error from which most PetstoreAPI errors extend. Thrown whenever something in the api goes wrong. + */ +abstract class PetstoreError(msg: String) extends Exception(msg) { + def message: String +} + +/** + * Thrown when the object given is invalid + * @param message An error message + */ +case class InvalidInput(message: String) extends PetstoreError(message) + +/** + * Thrown when the given object is missing a unique ID. + * @param message An error message + */ +case class MissingIdentifier(message: String) extends PetstoreError(message) + +/** + * Thrown when the given record does not exist in the database. + * @param message An error message + */ +case class RecordNotFound(message: String) extends PetstoreError(message) + diff --git a/modules/swagger-codegen/src/main/resources/finch/formParam.mustache b/modules/swagger-codegen/src/main/resources/finch/formParam.mustache new file mode 100644 index 00000000000..1afcf12ccc6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/formParam.mustache @@ -0,0 +1 @@ +{{#isFormParam}}formParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/formParamMustache.mustache b/modules/swagger-codegen/src/main/resources/finch/formParamMustache.mustache new file mode 100644 index 00000000000..29c571ee2ef --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/formParamMustache.mustache @@ -0,0 +1,3 @@ + {{#isFormParam}} + val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}") + {{/isFormParam}} diff --git a/modules/swagger-codegen/src/main/resources/finch/headerParam.mustache b/modules/swagger-codegen/src/main/resources/finch/headerParam.mustache new file mode 100644 index 00000000000..798bb0fe6d5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/headerParam.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}headerParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/headerParamOperation.mustache b/modules/swagger-codegen/src/main/resources/finch/headerParamOperation.mustache new file mode 100644 index 00000000000..7f8f5286392 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/headerParamOperation.mustache @@ -0,0 +1,3 @@ + {{#isHeaderParam}} + val {{paramName}} = request.getHeader("{{paramName}}") + {{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/model.mustache b/modules/swagger-codegen/src/main/resources/finch/model.mustache new file mode 100644 index 00000000000..dbb1489b3af --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/model.mustache @@ -0,0 +1,30 @@ +package {{modelPackage}} + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import {{packageName}}._ +{{#imports}}import {{import}} +{{/imports}} + +{{#models}} +{{#model}} +/** + * {{{description}}} +{{#vars}} + * @param {{name}} {{{description}}} +{{/vars}} + */ +case class {{classname}}({{#vars}}{{name}}: {{^required}}Option[{{{datatype}}}]{{/required}}{{#required}}{{{datatype}}}{{/required}}{{^-last}},{{/-last}} + {{/vars}}) + +object {{classname}} { + /** + * Creates the codec for converting {{classname}} from and to JSON. + */ + implicit val decoder: Decoder[{{classname}}] = deriveDecoder + implicit val encoder: ObjectEncoder[{{classname}}] = deriveEncoder +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/finch/pathParam.mustache b/modules/swagger-codegen/src/main/resources/finch/pathParam.mustache new file mode 100644 index 00000000000..ae72aa8ec74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/pathParam.mustache @@ -0,0 +1 @@ +{{#isPathParam}}pathParam[{{dataType}}]("{{paramName}}").description(""){{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/project/build.properties b/modules/swagger-codegen/src/main/resources/finch/project/build.properties new file mode 100644 index 00000000000..27e88aa115a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.13.13 diff --git a/modules/swagger-codegen/src/main/resources/finch/project/plugins.sbt b/modules/swagger-codegen/src/main/resources/finch/project/plugins.sbt new file mode 100644 index 00000000000..761afa5688e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/project/plugins.sbt @@ -0,0 +1,7 @@ +resolvers += Resolver.typesafeRepo("releases") + +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.3") + +// addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.1.4") + +addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.6.0") diff --git a/modules/swagger-codegen/src/main/resources/finch/queryParam.mustache b/modules/swagger-codegen/src/main/resources/finch/queryParam.mustache new file mode 100644 index 00000000000..79af702d0f0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/queryParam.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}queryParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/queryParamOperation.mustache b/modules/swagger-codegen/src/main/resources/finch/queryParamOperation.mustache new file mode 100644 index 00000000000..832bbed2030 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/queryParamOperation.mustache @@ -0,0 +1,13 @@ + {{#isQueryParam}} + {{#collectionFormat}}val {{paramName}}String = params.getAs[String]("{{paramName}}") + val {{paramName}} = if("{{collectionFormat}}".equals("default")) { + {{paramName}}String match { + case Some(str) => str.split(",") + case None => List() + } + } + else + List() + {{/collectionFormat}} + {{^collectionFormat}}val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}"){{/collectionFormat}} + {{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/sbt b/modules/swagger-codegen/src/main/resources/finch/sbt new file mode 100755 index 00000000000..08e58821219 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/sbt @@ -0,0 +1,525 @@ +#!/usr/bin/env bash +# +# A more capable sbt runner, coincidentally also called sbt. +# Author: Paul Phillips + +# todo - make this dynamic +declare -r sbt_release_version="0.13.6" +declare -r sbt_unreleased_version="0.13.6" +declare -r buildProps="project/build.properties" + +declare sbt_jar sbt_dir sbt_create sbt_version +declare scala_version sbt_explicit_version +declare verbose noshare batch trace_level log_level +declare sbt_saved_stty debugUs + +echoerr () { echo >&2 "$@"; } +vlog () { [[ -n "$verbose" ]] && echoerr "$@"; } + +# spaces are possible, e.g. sbt.version = 0.13.0 +build_props_sbt () { + [[ -r "$buildProps" ]] && \ + grep '^sbt\.version' "$buildProps" | tr '=' ' ' | awk '{ print $2; }' +} + +update_build_props_sbt () { + local ver="$1" + local old="$(build_props_sbt)" + + [[ -r "$buildProps" ]] && [[ "$ver" != "$old" ]] && { + perl -pi -e "s/^sbt\.version\b.*\$/sbt.version=${ver}/" "$buildProps" + grep -q '^sbt.version[ =]' "$buildProps" || printf "\nsbt.version=%s\n" "$ver" >> "$buildProps" + + vlog "!!!" + vlog "!!! Updated file $buildProps setting sbt.version to: $ver" + vlog "!!! Previous value was: $old" + vlog "!!!" + } +} + +set_sbt_version () { + sbt_version="${sbt_explicit_version:-$(build_props_sbt)}" + [[ -n "$sbt_version" ]] || sbt_version=$sbt_release_version + export sbt_version +} + +# restore stty settings (echo in particular) +onSbtRunnerExit() { + [[ -n "$sbt_saved_stty" ]] || return + vlog "" + vlog "restoring stty: $sbt_saved_stty" + stty "$sbt_saved_stty" + unset sbt_saved_stty +} + +# save stty and trap exit, to ensure echo is reenabled if we are interrupted. +trap onSbtRunnerExit EXIT +sbt_saved_stty="$(stty -g 2>/dev/null)" +vlog "Saved stty: $sbt_saved_stty" + +# this seems to cover the bases on OSX, and someone will +# have to tell me about the others. +get_script_path () { + local path="$1" + [[ -L "$path" ]] || { echo "$path" ; return; } + + local target="$(readlink "$path")" + if [[ "${target:0:1}" == "/" ]]; then + echo "$target" + else + echo "${path%/*}/$target" + fi +} + +die() { + echo "Aborting: $@" + exit 1 +} + +make_url () { + version="$1" + + case "$version" in + 0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;; + 0.10.* ) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + 0.11.[12]) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + *) echo "$sbt_launch_repo/org.scala-sbt/sbt-launch/$version/sbt-launch.jar" ;; + esac +} + +init_default_option_file () { + local overriding_var="${!1}" + local default_file="$2" + if [[ ! -r "$default_file" && "$overriding_var" =~ ^@(.*)$ ]]; then + local envvar_file="${BASH_REMATCH[1]}" + if [[ -r "$envvar_file" ]]; then + default_file="$envvar_file" + fi + fi + echo "$default_file" +} + +declare -r cms_opts="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC" +declare -r jit_opts="-XX:ReservedCodeCacheSize=256m -XX:+TieredCompilation" +declare -r default_jvm_opts_common="-Xms512m -Xmx1536m -Xss2m $jit_opts $cms_opts" +declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" +declare -r latest_28="2.8.2" +declare -r latest_29="2.9.3" +declare -r latest_210="2.10.4" +declare -r latest_211="2.11.2" + +declare -r script_path="$(get_script_path "$BASH_SOURCE")" +declare -r script_name="${script_path##*/}" + +# some non-read-onlies set with defaults +declare java_cmd="java" +declare sbt_opts_file="$(init_default_option_file SBT_OPTS .sbtopts)" +declare jvm_opts_file="$(init_default_option_file JVM_OPTS .jvmopts)" +declare sbt_launch_repo="http://typesafe.artifactoryonline.com/typesafe/ivy-releases" + +# pull -J and -D options to give to java. +declare -a residual_args +declare -a java_args +declare -a scalac_args +declare -a sbt_commands + +# args to jvm/sbt via files or environment variables +declare -a extra_jvm_opts extra_sbt_opts + +# if set, use JAVA_HOME over java found in path +[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java" + +# directory to store sbt launchers +declare sbt_launch_dir="$HOME/.sbt/launchers" +[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir" +[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers.XXXXXX)" + +java_version () { + local version=$("$java_cmd" -version 2>&1 | grep -e 'java version' | awk '{ print $3 }' | tr -d \") + vlog "Detected Java version: $version" + echo "${version:2:1}" +} + +# MaxPermSize critical on pre-8 jvms but incurs noisy warning on 8+ +default_jvm_opts () { + local v="$(java_version)" + if [[ $v -ge 8 ]]; then + echo "$default_jvm_opts_common" + else + echo "-XX:MaxPermSize=384m $default_jvm_opts_common" + fi +} + +build_props_scala () { + if [[ -r "$buildProps" ]]; then + versionLine="$(grep '^build.scala.versions' "$buildProps")" + versionString="${versionLine##build.scala.versions=}" + echo "${versionString%% .*}" + fi +} + +execRunner () { + # print the arguments one to a line, quoting any containing spaces + vlog "# Executing command line:" && { + for arg; do + if [[ -n "$arg" ]]; then + if printf "%s\n" "$arg" | grep -q ' '; then + printf >&2 "\"%s\"\n" "$arg" + else + printf >&2 "%s\n" "$arg" + fi + fi + done + vlog "" + } + + [[ -n "$batch" ]] && exec /dev/null; then + curl --fail --silent "$url" --output "$jar" + elif which wget >/dev/null; then + wget --quiet -O "$jar" "$url" + fi + } && [[ -r "$jar" ]] +} + +acquire_sbt_jar () { + sbt_url="$(jar_url "$sbt_version")" + sbt_jar="$(jar_file "$sbt_version")" + + [[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar" +} + +usage () { + cat < display stack traces with a max of frames (default: -1, traces suppressed) + -debug-inc enable debugging log for the incremental compiler + -no-colors disable ANSI color codes + -sbt-create start sbt even if current directory contains no sbt project + -sbt-dir path to global settings/plugins directory (default: ~/.sbt/) + -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11+) + -ivy path to local Ivy repository (default: ~/.ivy2) + -no-share use all local caches; no sharing + -offline put sbt in offline mode + -jvm-debug Turn on JVM debugging, open at the given port. + -batch Disable interactive mode + -prompt Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted + + # sbt version (default: sbt.version from $buildProps if present, otherwise $sbt_release_version) + -sbt-force-latest force the use of the latest release of sbt: $sbt_release_version + -sbt-version use the specified version of sbt (default: $sbt_release_version) + -sbt-dev use the latest pre-release version of sbt: $sbt_unreleased_version + -sbt-jar use the specified jar as the sbt launcher + -sbt-launch-dir directory to hold sbt launchers (default: ~/.sbt/launchers) + -sbt-launch-repo repo url for downloading sbt launcher jar (default: $sbt_launch_repo) + + # scala version (default: as chosen by sbt) + -28 use $latest_28 + -29 use $latest_29 + -210 use $latest_210 + -211 use $latest_211 + -scala-home use the scala build at the specified directory + -scala-version use the specified version of scala + -binary-version use the specified scala version when searching for dependencies + + # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) + -java-home alternate JAVA_HOME + + # passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution + # The default set is used if JVM_OPTS is unset and no -jvm-opts file is found + $(default_jvm_opts) + JVM_OPTS environment variable holding either the jvm args directly, or + the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts') + Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument. + -jvm-opts file containing jvm args (if not given, .jvmopts in project root is used if present) + -Dkey=val pass -Dkey=val directly to the jvm + -J-X pass option -X directly to the jvm (-J is stripped) + + # passing options to sbt, OR to this runner + SBT_OPTS environment variable holding either the sbt args directly, or + the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts') + Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument. + -sbt-opts file containing sbt args (if not given, .sbtopts in project root is used if present) + -S-X add -X to sbt's scalacOptions (-S is stripped) +EOM +} + +addJava () { + vlog "[addJava] arg = '$1'" + java_args=( "${java_args[@]}" "$1" ) +} +addSbt () { + vlog "[addSbt] arg = '$1'" + sbt_commands=( "${sbt_commands[@]}" "$1" ) +} +setThisBuild () { + vlog "[addBuild] args = '$@'" + local key="$1" && shift + addSbt "set $key in ThisBuild := $@" +} + +addScalac () { + vlog "[addScalac] arg = '$1'" + scalac_args=( "${scalac_args[@]}" "$1" ) +} +addResidual () { + vlog "[residual] arg = '$1'" + residual_args=( "${residual_args[@]}" "$1" ) +} +addResolver () { + addSbt "set resolvers += $1" +} +addDebugger () { + addJava "-Xdebug" + addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1" +} +setScalaVersion () { + [[ "$1" == *"-SNAPSHOT" ]] && addResolver 'Resolver.sonatypeRepo("snapshots")' + addSbt "++ $1" +} + +process_args () +{ + require_arg () { + local type="$1" + local opt="$2" + local arg="$3" + + if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then + die "$opt requires <$type> argument" + fi + } + while [[ $# -gt 0 ]]; do + case "$1" in + -h|-help) usage; exit 1 ;; + -v) verbose=true && shift ;; + -d) addSbt "--debug" && shift ;; + -w) addSbt "--warn" && shift ;; + -q) addSbt "--error" && shift ;; + -x) debugUs=true && shift ;; + -trace) require_arg integer "$1" "$2" && trace_level="$2" && shift 2 ;; + -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; + -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; + -no-share) noshare=true && shift ;; + -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; + -sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;; + -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; + -offline) addSbt "set offline := true" && shift ;; + -jvm-debug) require_arg port "$1" "$2" && addDebugger "$2" && shift 2 ;; + -batch) batch=true && shift ;; + -prompt) require_arg "expr" "$1" "$2" && setThisBuild shellPrompt "(s => { val e = Project.extract(s) ; $2 })" && shift 2 ;; + + -sbt-create) sbt_create=true && shift ;; + -sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;; + -sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;; + -sbt-force-latest) sbt_explicit_version="$sbt_release_version" && shift ;; + -sbt-dev) sbt_explicit_version="$sbt_unreleased_version" && shift ;; + -sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;; + -sbt-launch-repo) require_arg path "$1" "$2" && sbt_launch_repo="$2" && shift 2 ;; + -scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;; + -binary-version) require_arg version "$1" "$2" && setThisBuild scalaBinaryVersion "\"$2\"" && shift 2 ;; + -scala-home) require_arg path "$1" "$2" && setThisBuild scalaHome "Some(file(\"$2\"))" && shift 2 ;; + -java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;; + -sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;; + -jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;; + + -D*) addJava "$1" && shift ;; + -J*) addJava "${1:2}" && shift ;; + -S*) addScalac "${1:2}" && shift ;; + -28) setScalaVersion "$latest_28" && shift ;; + -29) setScalaVersion "$latest_29" && shift ;; + -210) setScalaVersion "$latest_210" && shift ;; + -211) setScalaVersion "$latest_211" && shift ;; + + *) addResidual "$1" && shift ;; + esac + done +} + +# process the direct command line arguments +process_args "$@" + +# skip #-styled comments and blank lines +readConfigFile() { + while read line; do + [[ $line =~ ^# ]] || [[ -z $line ]] || echo "$line" + done < "$1" +} + +# if there are file/environment sbt_opts, process again so we +# can supply args to this runner +if [[ -r "$sbt_opts_file" ]]; then + vlog "Using sbt options defined in file $sbt_opts_file" + while read opt; do extra_sbt_opts+=("$opt"); done < <(readConfigFile "$sbt_opts_file") +elif [[ -n "$SBT_OPTS" && ! ("$SBT_OPTS" =~ ^@.*) ]]; then + vlog "Using sbt options defined in variable \$SBT_OPTS" + extra_sbt_opts=( $SBT_OPTS ) +else + vlog "No extra sbt options have been defined" +fi + +[[ -n "${extra_sbt_opts[*]}" ]] && process_args "${extra_sbt_opts[@]}" + +# reset "$@" to the residual args +set -- "${residual_args[@]}" +argumentCount=$# + +# set sbt version +set_sbt_version + +# only exists in 0.12+ +setTraceLevel() { + case "$sbt_version" in + "0.7."* | "0.10."* | "0.11."* ) echoerr "Cannot set trace level in sbt version $sbt_version" ;; + *) setThisBuild traceLevel $trace_level ;; + esac +} + +# set scalacOptions if we were given any -S opts +[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\"" + +# Update build.properties on disk to set explicit version - sbt gives us no choice +[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version" +vlog "Detected sbt version $sbt_version" + +[[ -n "$scala_version" ]] && vlog "Overriding scala version to $scala_version" + +# no args - alert them there's stuff in here +(( argumentCount > 0 )) || { + vlog "Starting $script_name: invoke with -help for other options" + residual_args=( shell ) +} + +# verify this is an sbt dir or -create was given +[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || { + cat <{{baseName}} {{#baseType}}{{baseType}}{{/baseType}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}} -
Body Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isBodyParam}} +
Body Parameter — {{unescapedDescription}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isBodyParam}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache index 5f8392f34eb..19e3fddab8a 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache @@ -1,3 +1,3 @@ {{#isFormParam}}
{{baseName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
-
Form Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}} {{/defaultValue}}{{#dataFormat}}format: {{{dataFormat}}}{{/dataFormat}}
{{/isFormParam}} \ No newline at end of file +
Form Parameter — {{unescapedDescription}} {{#defaultValue}}default: {{{defaultValue}}} {{/defaultValue}}{{#dataFormat}}format: {{{dataFormat}}}{{/dataFormat}}
{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache index bd18f9e15cc..936f3772b03 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache @@ -1,3 +1,3 @@ {{#isHeaderParam}}
{{baseName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
-
Header Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}} {{/defaultValue}}{{#dataFormat}}format: {{{dataFormat}}}{{/dataFormat}}
{{/isHeaderParam}} \ No newline at end of file +
Header Parameter — {{unescapedDescription}} {{#defaultValue}}default: {{{defaultValue}}} {{/defaultValue}}{{#dataFormat}}format: {{{dataFormat}}}{{/dataFormat}}
{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index d3c2681bced..6d5dfaccb2d 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -165,9 +165,9 @@ {{#model}}

{{name}} - {{title}} Up

-
{{description}}
+
{{unescapedDescription}}
- {{#vars}}
{{name}} {{^required}}(optional){{/required}}
{{^isPrimitiveType}}{{datatype}}{{/isPrimitiveType}} {{description}} {{#dataFormat}}format: {{{dataFormat}}}{{/dataFormat}}
+ {{#vars}}
{{name}} {{^required}}(optional){{/required}}
{{^isPrimitiveType}}{{datatype}}{{/isPrimitiveType}} {{unescapedDescription}} {{#dataFormat}}format: {{{dataFormat}}}{{/dataFormat}}
{{#isEnum}}
Enum:
{{#_enum}}
{{this}}
{{/_enum}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache index a198c1765b0..df8d9920400 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache @@ -1,3 +1,3 @@ {{#isPathParam}}
{{baseName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
-
Path Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}} {{/defaultValue}}{{#dataFormat}}format: {{{dataFormat}}}{{/dataFormat}}
{{/isPathParam}} \ No newline at end of file +
Path Parameter — {{unescapedDescription}} {{#defaultValue}}default: {{{defaultValue}}} {{/defaultValue}}{{#dataFormat}}format: {{{dataFormat}}}{{/dataFormat}}
{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache index b5599b34698..79f7ab2b8c6 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache @@ -1,3 +1,3 @@ {{#isQueryParam}}
{{baseName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
-
Query Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}} {{/defaultValue}}{{#dataFormat}}format: {{{dataFormat}}}{{/dataFormat}}
{{/isQueryParam}} \ No newline at end of file +
Query Parameter — {{unescapedDescription}} {{#defaultValue}}default: {{{defaultValue}}} {{/defaultValue}}{{#dataFormat}}format: {{{dataFormat}}}{{/dataFormat}}
{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache index 3f5cb05b3dc..01f9f2eb720 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/index.mustache @@ -218,11 +218,13 @@
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • -
    curl -X {{httpMethod}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}} -H "{{keyParamName}}: [[apiKey]]" {{/isKeyInHeader}}{{/isApiKey}}{{#isBasic}} -H "Authorization: Basic [[basicHash]]" {{/isBasic}}{{/authMethods}} "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
    +
    curl -X {{httpMethod}}{{#authMethods}}{{#isApiKey}}{{#isKeyInHeader}} -H "{{keyParamName}}: [[apiKey]]"{{/isKeyInHeader}}{{/isApiKey}}{{#isBasic}}{{#hasProduces}} -H "Accept: {{#produces}}{{{mediaType}}}{{#hasMore}},{{/hasMore}}{{/produces}}"{{/hasProduces}}{{#hasConsumes}} -H "Content-Type: {{#consumes}}{{{mediaType}}}{{#hasMore}},{{/hasMore}}{{/consumes}}"{{/hasConsumes}} -H "Authorization: Basic [[basicHash]]"{{/isBasic}}{{/authMethods}} "{{basePath}}{{path}}{{#hasQueryParams}}?{{#queryParams}}{{^-first}}&{{/-first}}{{paramName}}={{vendorExtensions.x-eg}}{{/queryParams}}{{/hasQueryParams}}"
    {{>sample_java}}
    @@ -253,6 +255,14 @@
    {{>sample_php}}
    + +
    +
    {{>sample_perl}}
    +
    + +
    +
    {{>sample_python}}
    +

    Parameters

    diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache index 69cf16352ca..aeef539e1da 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/param.mustache @@ -1,4 +1,4 @@ -{{paramName}}{{^required}}{{/required}}{{#required}}*{{/required}} +{{baseName}}{{^required}}{{/required}}{{#required}}*{{/required}} @@ -10,7 +10,7 @@ - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_{{nickname}}_{{paramName}}'); result.empty(); result.append(view.render()); diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache index 2bf0769666c..53f1864a169 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_android.mustache @@ -5,7 +5,7 @@ public class {{{classname}}}Example { public static void main(String[] args) { {{{classname}}} apiInstance = new {{{classname}}}(); {{#allParams}} - {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{unescapedDescription}}} {{/allParams}} try { {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache index ebfef12699f..1a5075ce7f7 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_csharp.mustache @@ -25,10 +25,10 @@ namespace Example var apiInstance = new {{classname}}(); {{#allParams}} {{#isPrimitiveType}} - var {{paramName}} = {{example}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + var {{paramName}} = {{example}}; // {{{dataType}}} | {{{unescapedDescription}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} {{/isPrimitiveType}} {{^isPrimitiveType}} - var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{unescapedDescription}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} {{/isPrimitiveType}} {{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache index 02454e6cc7d..bf0b1c374c1 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_java.mustache @@ -28,7 +28,7 @@ public class {{{classname}}}Example { {{{classname}}} apiInstance = new {{{classname}}}(); {{#allParams}} - {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{unescapedDescription}}} {{/allParams}} try { {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache index 4fc35f07711..6e50faa6a8e 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_js.mustache @@ -19,10 +19,10 @@ var {{{name}}} = defaultClient.authentications['{{{name}}}']; var api = new {{{jsModuleName}}}.{{{classname}}}(){{#hasParams}} {{#vendorExtensions.x-codegen-hasRequiredParams}}{{#allParams}}{{#required}} -var {{{paramName}}} = {{{example}}}; // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}} +var {{{paramName}}} = {{{example}}}; // {{=< >=}}{<&dataType>}<={{ }}=> {{{unescapedDescription}}} {{/required}}{{/allParams}}{{/vendorExtensions.x-codegen-hasRequiredParams}}{{#hasOptionalParams}} var opts = { {{#allParams}}{{^required}} - '{{{paramName}}}': {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} // {{=< >=}}{<&dataType>}<={{ }}=> {{{description}}}{{/required}}{{/allParams}} + '{{{paramName}}}': {{{example}}}{{#vendorExtensions.x-codegen-hasMoreOptional}},{{/vendorExtensions.x-codegen-hasMoreOptional}} // {{=< >=}}{<&dataType>}<={{ }}=> {{{unescapedDescription}}}{{/required}}{{/allParams}} };{{/hasOptionalParams}}{{/hasParams}} {{#usePromises}} api.{{{operationId}}}({{#allParams}}{{#required}}{{{paramName}}}{{#vendorExtensions.x-codegen-hasMoreRequired}}, {{/vendorExtensions.x-codegen-hasMoreRequired}}{{/required}}{{/allParams}}{{#hasOptionalParams}}{{#vendorExtensions.x-codegen-hasRequiredParams}}, {{/vendorExtensions.x-codegen-hasRequiredParams}}opts{{/hasOptionalParams}}).then(function({{#returnType}}data{{/returnType}}) { diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache index 232bf0c2f05..3d1465ab569 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_objc.mustache @@ -13,7 +13,7 @@ [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; {{/isOAuth}}{{/authMethods}} {{/hasAuthMethods}} -{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{#allParams}}{{{dataType}}} *{{paramName}} = {{{example}}}; // {{{unescapedDescription}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} {{/allParams}} {{classname}} *apiInstance = [[{{classname}} alloc] init]; diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_perl.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_perl.mustache new file mode 100644 index 00000000000..8eeb8a246a2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_perl.mustache @@ -0,0 +1,26 @@ +use Data::Dumper; +use {{{perlModuleName}}}::Configuration; +use {{perlModuleName}}::{{classname}}; +{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} +# Configure HTTP basic authorization: {{{name}}} +${{{perlModuleName}}}::Configuration::username = 'YOUR_USERNAME'; +${{{perlModuleName}}}::Configuration::password = 'YOUR_PASSWORD';{{/isBasic}}{{#isApiKey}} +# Configure API key authorization: {{{name}}} +${{{perlModuleName}}}::Configuration::api_key->{'{{{keyParamName}}}'} = 'YOUR_API_KEY'; +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed +#${{{perlModuleName}}}::Configuration::api_key_prefix->{'{{{keyParamName}}}'} = "Bearer";{{/isApiKey}}{{#isOAuth}} +# Configure OAuth2 access token for authorization: {{{name}}} +${{{perlModuleName}}}::Configuration::access_token = 'YOUR_ACCESS_TOKEN';{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +my $api_instance = {{perlModuleName}}::{{classname}}->new(); +{{#allParams}}my ${{paramName}} = {{#isListContainer}}[{{/isListContainer}}{{#isBodyParam}}{{{perlModuleName}}}::Object::{{dataType}}->new(){{/isBodyParam}}{{^isBodyParam}}{{{example}}}{{/isBodyParam}}{{#isListContainer}}]{{/isListContainer}}; # {{{dataType}}} | {{{unescapedDescription}}} +{{/allParams}} + +eval { + {{#returnType}}my $result = {{/returnType}}$api_instance->{{{operationId}}}({{#allParams}}{{paramName}} => ${{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + print Dumper($result);{{/returnType}} +}; +if ($@) { + warn "Exception when calling {{classname}}->{{operationId}}: $@\n"; +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache index b479530d6ca..0bc345b10d2 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_php.mustache @@ -13,7 +13,7 @@ require_once(__DIR__ . '/vendor/autoload.php'); {{/hasAuthMethods}} $api_instance = new Swagger\Client\Api\{{classname}}(); -{{#allParams}}${{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}} +{{#allParams}}${{paramName}} = {{{example}}}; // {{{dataType}}} | {{{unescapedDescription}}} {{/allParams}} try { diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_python.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_python.mustache new file mode 100644 index 00000000000..cb6c5509190 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs2/sample_python.mustache @@ -0,0 +1,28 @@ +from __future__ import print_statement +import time +import {{{pythonPackageName}}} +from {{{pythonPackageName}}}.rest import ApiException +from pprint import pprint +{{#hasAuthMethods}}{{#authMethods}}{{#isBasic}} +# Configure HTTP basic authorization: {{{name}}} +{{{pythonPackageName}}}.configuration.username = 'YOUR_USERNAME' +{{{pythonPackageName}}}.configuration.password = 'YOUR_PASSWORD'{{/isBasic}}{{#isApiKey}} +# Configure API key authorization: {{{name}}} +{{{pythonPackageName}}}.configuration.api_key['{{{keyParamName}}}'] = 'YOUR_API_KEY' +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed +# {{{pythonPackageName}}}.configuration.api_key_prefix['{{{keyParamName}}}'] = 'Bearer'{{/isApiKey}}{{#isOAuth}} +# Configure OAuth2 access token for authorization: {{{name}}} +{{{pythonPackageName}}}.configuration.access_token = 'YOUR_ACCESS_TOKEN'{{/isOAuth}}{{/authMethods}} +{{/hasAuthMethods}} + +# create an instance of the API class +api_instance = {{{pythonPackageName}}}.{{{classname}}}() +{{#allParams}}{{paramName}} = {{{example}}} # {{{dataType}}} | {{{unescapedDescription}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +{{/allParams}} + +try: +{{#summary}} # {{{.}}} +{{/summary}} {{#returnType}}api_response = {{/returnType}}api_instance.{{{operationId}}}({{#allParams}}{{#required}}{{paramName}}{{/required}}{{^required}}{{paramName}}={{paramName}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){{#returnType}} + pprint(api_response){{/returnType}} +except ApiException as e: + print("Exception when calling {{classname}}->{{operationId}}: %s\n" % e) \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache index c4a06b60070..8ff5398633d 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/Project.mustache @@ -39,8 +39,8 @@ bin\Release\{{packageName}}.XML - - ..\..\packages\Nancy.1.4.1\lib\net40\Nancy.dll + + ..\..\packages\Nancy.1.4.3\lib\net40\Nancy.dll True diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache index b4213ff2056..3aca8b8855e 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/api.mustache @@ -40,7 +40,7 @@ namespace {{packageName}}.{{packageContext}}.Modules /// /// Service handling {{classname}} requests. /// - public interface {{classname}}Service + public interface {{interfacePrefix}}{{classname}}Service { {{#operation}}/// /// {{notes}} @@ -56,7 +56,7 @@ namespace {{packageName}}.{{packageContext}}.Modules /// /// Abstraction of {{classname}}Service. /// - public abstract class Abstract{{classname}}Service: {{classname}}Service + public abstract class Abstract{{classname}}Service: {{interfacePrefix}}{{classname}}Service { {{#operation}}public virtual {{#returnType}}{{&returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}(NancyContext context{{#allParams.0}}, {{/allParams.0}}{{>paramsList}}) { diff --git a/modules/swagger-codegen/src/main/resources/nancyfx/packages.config.mustache b/modules/swagger-codegen/src/main/resources/nancyfx/packages.config.mustache index 58198276a42..c511c50acc8 100644 --- a/modules/swagger-codegen/src/main/resources/nancyfx/packages.config.mustache +++ b/modules/swagger-codegen/src/main/resources/nancyfx/packages.config.mustache @@ -1,6 +1,6 @@ - + diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 288708041ec..7e56be1491b 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -80,6 +80,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) @"application/x-www-form-urlencoded": afhttpRequestSerializer, @"multipart/form-data": afhttpRequestSerializer }; + self.securityPolicy = [self createSecurityPolicy]; self.responseSerializer = [AFHTTPResponseSerializer serializer]; } return self; @@ -351,4 +352,25 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } +- (AFSecurityPolicy *) createSecurityPolicy { + AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + + id<{{classPrefix}}Configuration> config = self.configuration; + + if (config.sslCaCert) { + NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; + [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]]; + } + + if (config.verifySSL) { + [securityPolicy setAllowInvalidCertificates:NO]; + } + else { + [securityPolicy setAllowInvalidCertificates:YES]; + [securityPolicy setValidatesDomainName:NO]; + } + + return securityPolicy; +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 47fe9ce4841..f85b9c58f83 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -23,14 +23,6 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; @property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; -@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer *>* requestSerializerForContentType; - -/** - * Gets client singleton instance - */ -+ (instancetype) sharedClient; - - /** * Gets if the client is unreachable * @@ -52,29 +44,16 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ +(AFNetworkReachabilityStatus) getReachabilityStatus; -/** - * Gets the next request id - * - * @return The next executed request id. - */ -+(NSNumber*) nextRequestId; +@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer *>* requestSerializerForContentType; /** - * Generates request id and add it to the queue - * - * @return The next executed request id. + * Gets client singleton instance */ -+(NSNumber*) queueRequest; ++ (instancetype) sharedClient; + /** - * Removes request id from the queue - * - * @param requestId The request which will be removed. - */ -+(void) cancelRequest:(NSNumber*)requestId; - -/** - * Customizes the behavior when the reachability changed + * Updates header parameters and query parameters for authentication * * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. @@ -89,7 +68,15 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * @param configuration The configuration implementation */ - (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration; - + +/** +* Initializes the session manager with a configuration and url +* +* @param url The base url +* @param configuration The configuration implementation +*/ +- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id)configuration; + /** * Performs request * diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache index b9cd2c2edd6..946cc1bc2e5 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache @@ -53,6 +53,18 @@ static NSString * const k{{classPrefix}}APIVersion = @"{{podVersion}}"; */ @property (readonly, nonatomic) BOOL debug; +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (readonly, nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (readonly, nonatomic) NSString *sslCaCert; + /** * Authentication Settings */ @@ -63,4 +75,4 @@ static NSString * const k{{classPrefix}}APIVersion = @"{{podVersion}}"; */ @property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; -@end \ No newline at end of file +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache index 6b0c9fe9745..548383a7e1e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache @@ -32,6 +32,7 @@ _username = @""; _password = @""; _accessToken= @""; + _verifySSL = YES; _mutableApiKey = [NSMutableDictionary dictionary]; _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; _mutableDefaultHeaders = [NSMutableDictionary dictionary]; diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 9ceb7872f8d..80a047b80b2 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -55,17 +55,11 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; /// /// {{{summary}}} /// {{{notes}}} -{{#allParams}} -/// @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} +/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} /// -{{/allParams}} -{{#responses}} -/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}} -{{/responses}} -{{#returnType}} -/// @return {{{returnType}}} -{{/returnType}} --(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{operationId}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +/// +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { {{#allParams}} @@ -166,5 +160,6 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; {{/operation}} +{{newline}} {{/operations}} @end diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index a65f7fecc6e..266e7355fd6 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -16,23 +16,18 @@ extern NSInteger k{{classname}}MissingParamErrorCode; {{#operations}} {{#operation}} /// {{{summary}}} -{{#notes}} -/// {{{notes}}} -{{/notes}} +/// {{#notes}}{{{notes}}}{{/notes}} +/// +/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +/// {{/allParams}}{{#responses}} +/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} /// -{{#allParams}} -/// @param {{paramName}} {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -{{/allParams}} -{{#responses}} -/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}} -{{/responses}} -{{#returnType}} /// @return {{{returnType}}} -{{/returnType}} --(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{operationId}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; +{{newline}} {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index 3ebbbd0a3f8..88c4ab0613f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -22,7 +22,7 @@ Pod::Spec.new do |s| {{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}} s.homepage = "{{gitRepoURL}}" - s.license = "{{#license}}{{license}}{{/license}}{{^license}}Proprietary{{/license}}" + s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}" s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" } s.author = { "{{authorName}}" => "{{authorEmail}}" } @@ -30,8 +30,8 @@ Pod::Spec.new do |s| s.public_header_files = '{{podName}}/**/*.h' {{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}} - s.dependency 'AFNetworking', '~> 3.1' - s.dependency 'JSONModel', '~> 1.4' + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' s.dependency 'ISO8601', '~> 0.6' end diff --git a/modules/swagger-codegen/src/main/resources/perl/README.mustache b/modules/swagger-codegen/src/main/resources/perl/README.mustache index c732448cecf..512ddfbd065 100644 --- a/modules/swagger-codegen/src/main/resources/perl/README.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/README.mustache @@ -10,7 +10,9 @@ Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/ - API version: {{appVersion}} - Package version: {{moduleVersion}} +{{^hideGenerationTimestamp}} - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} - Build package: {{generatorClass}} {{#infoUrl}} For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) @@ -18,43 +20,43 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) ## A note on Moose -This role is the only component of the library that uses Moose. See -{{moduleName}}::ApiFactory for non-Moosey usage. +This role is the only component of the library that uses Moose. See +{{moduleName}}::ApiFactory for non-Moosey usage. # SYNOPSIS -The Perl Swagger Codegen project builds a library of Perl modules to interact with -a web service defined by a OpenAPI Specification. See below for how to build the +The Perl Swagger Codegen project builds a library of Perl modules to interact with +a web service defined by a OpenAPI Specification. See below for how to build the library. -This module provides an interface to the generated library. All the classes, -objects, and methods (well, not quite \*all\*, see below) are flattened into this -role. +This module provides an interface to the generated library. All the classes, +objects, and methods (well, not quite \*all\*, see below) are flattened into this +role. package MyApp; use Moose; with '{{moduleName}}::Role'; - + package main; - + my $api = MyApp->new({ tokens => $tokens }); - + my $pet = $api->get_pet_by_id(pet_id => $pet_id); - + ## Structure of the library The library consists of a set of API classes, one for each endpoint. These APIs -implement the method calls available on each endpoint. +implement the method calls available on each endpoint. -Additionally, there is a set of "object" classes, which represent the objects -returned by and sent to the methods on the endpoints. +Additionally, there is a set of "object" classes, which represent the objects +returned by and sent to the methods on the endpoints. -An API factory class is provided, which builds instances of each endpoint API. +An API factory class is provided, which builds instances of each endpoint API. -This Moose role flattens all the methods from the endpoint APIs onto the consuming -class. It also provides methods to retrieve the endpoint API objects, and the API -factory object, should you need it. +This Moose role flattens all the methods from the endpoint APIs onto the consuming +class. It also provides methods to retrieve the endpoint API objects, and the API +factory object, should you need it. For documentation of all these methods, see AUTOMATIC DOCUMENTATION below. @@ -67,33 +69,33 @@ required and where to put them. You just need to supply the tokens. # basic username => $username, password => $password, - + # oauth access_token => $oauth_token, - + # keys $some_key => { token => $token, - prefix => $prefix, - in => $in, # 'head||query', + prefix => $prefix, + in => $in, # 'head||query', }, - + $another => { token => $token, - prefix => $prefix, - in => $in, # 'head||query', - }, + prefix => $prefix, + in => $in, # 'head||query', + }, ..., - + }; - + my $api = MyApp->new({ tokens => $tokens }); Note these are all optional, as are `prefix` and `in`, and depend on the API you are accessing. Usually `prefix` and `in` will be determined by the code generator from the spec and you will not need to set them at run time. If not, `in` will -default to 'head' and `prefix` to the empty string. +default to 'head' and `prefix` to the empty string. The tokens will be placed in the `{{moduleName}}::Configuration` namespace -as follows, but you don't need to know about this. +as follows, but you don't need to know about this. - `${{moduleName}}::Configuration::username` @@ -124,22 +126,22 @@ as follows, but you don't need to know about this. - `${{moduleName}}::Configuration::access_token` - String. The OAuth access token. + String. The OAuth access token. # METHODS ## `base_url` -The generated code has the `base_url` already set as a default value. This method -returns (and optionally sets, but only if the API client has not been +The generated code has the `base_url` already set as a default value. This method +returns (and optionally sets, but only if the API client has not been created yet) the current value of `base_url`. ## `api_factory` -Returns an API factory object. You probably won't need to call this directly. +Returns an API factory object. You probably won't need to call this directly. $self->api_factory('Pet'); # returns a {{moduleName}}::PetApi instance - + $self->pet_api; # the same # MISSING METHODS @@ -149,9 +151,9 @@ Most of the methods on the API are delegated to individual endpoint API objects same method name (e.g. `new()`), these methods can't be delegated. So you need to call `$api->pet_api->new()`. -In principle, every API is susceptible to the presence of a few, random, undelegatable -method names. In practice, because of the way method names are constructed, it's -unlikely in general that any methods will be undelegatable, except for: +In principle, every API is susceptible to the presence of a few, random, undelegatable +method names. In practice, because of the way method names are constructed, it's +unlikely in general that any methods will be undelegatable, except for: new() class_documentation() @@ -164,12 +166,12 @@ you could also call them on class names. # BUILDING YOUR LIBRARY -See the homepage `https://github.com/swagger-api/swagger-codegen` for full details. -But briefly, clone the git repository, build the codegen codebase, set up your build +See the homepage `https://github.com/swagger-api/swagger-codegen` for full details. +But briefly, clone the git repository, build the codegen codebase, set up your build config file, then run the API build script. You will need git, Java 7 or 8 and Apache maven 3.0.3 or better already installed. -The config file should specify the project name for the generated library: +The config file should specify the project name for the generated library: {"moduleName":"WWW::MyProjectName"} @@ -184,8 +186,8 @@ Your library files will be built under `WWW::MyProjectName`. -c /path/to/config/file.json \ -o /path/to/output/folder -Bang, all done. Run the `autodoc` script in the `bin` directory to see the API -you just built. +Bang, all done. Run the `autodoc` script in the `bin` directory to see the API +you just built. # AUTOMATIC DOCUMENTATION @@ -197,28 +199,28 @@ output formats are supported: -w wide format (default) -n narrow format - -p POD format - -H HTML format + -p POD format + -H HTML format -m Markdown format -h print this help message -c your application class - + The `-c` option allows you to load and inspect your own application. A dummy namespace is used if you don't supply your own class. # DOCUMENTATION FROM THE OpenAPI Spec -Additional documentation for each class and method may be provided by the Swagger -spec. If so, this is available via the `class_documentation()` and -`method_documentation()` methods on each generated object class, and the -`method_documentation()` method on the endpoint API classes: +Additional documentation for each class and method may be provided by the Swagger +spec. If so, this is available via the `class_documentation()` and +`method_documentation()` methods on each generated object class, and the +`method_documentation()` method on the endpoint API classes: + + my $cmdoc = $api->pet_api->method_documentation->{$method_name}; + + my $odoc = $api->get_pet_by_id->(pet_id => $pet_id)->class_documentation; + my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; - my $cmdoc = $api->pet_api->method_documentation->{$method_name}; - - my $odoc = $api->get_pet_by_id->(pet_id => $pet_id)->class_documentation; - my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; - Each of these calls returns a hashref with various useful pieces of information. @@ -297,7 +299,7 @@ Class | Method | HTTP request | Description {{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} {{#authMethods}}## {{{name}}} -{{#isApiKey}}- **Type**: API key +{{#isApiKey}}- **Type**: API key - **API key parameter name**: {{{keyParamName}}} - **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} {{/isApiKey}} @@ -312,5 +314,3 @@ Class | Method | HTTP request | Description {{/isOAuth}} {{/authMethods}} - - diff --git a/modules/swagger-codegen/src/main/resources/perl/Role.mustache b/modules/swagger-codegen/src/main/resources/perl/Role.mustache index 0c8c1a0375b..f853faeb726 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Role.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Role.mustache @@ -1,6 +1,6 @@ {{>partial_license}} # -# NOTE: This class is auto generated by the swagger code generator program. +# NOTE: This class is auto generated by the swagger code generator program. # Do not edit the class manually. # Ref: https://github.com/swagger-api/swagger-codegen # @@ -21,7 +21,7 @@ has base_url => ( is => 'ro', has api_factory => ( is => 'ro', isa => '{{moduleName}}::ApiFactory', - builder => '_build_af', + builder => '_build_af', lazy => 1, documentation => 'Builds an instance of the endpoint API class', ); @@ -38,12 +38,14 @@ has _cfg => ( is => 'ro', default => '{{moduleName}}::Configuration', ); -has version_info => ( is => 'ro', - isa => 'HashRef', +has version_info => ( is => 'ro', + isa => 'HashRef', default => sub { { app_name => '{{appName}}', app_version => '{{appVersion}}', + {{^hideGenerationTimestamp}} generated_date => '{{generatedDate}}', + {{/hideGenerationTimestamp}} generator_class => '{{generatorClass}}', } }, documentation => 'Information about the application version and the codegen codebase version' @@ -51,36 +53,36 @@ has version_info => ( is => 'ro', sub BUILD { my $self = shift; - + $self->_cfg->accept_tokens( $self->tokens ) if keys %{$self->tokens}; - + # ignore these symbols imported into API namespaces my %outsiders = map {$_ => 1} qw( croak ); - + my %delegates; - + # collect the methods callable on each API foreach my $api_name ($self->api_factory->apis_available) { my $api_class = $self->api_factory->classname_for($api_name); my $methods = Class::Inspector->methods($api_class, 'expanded'); # not Moose, so use CI instead my @local_methods = grep {! /^_/} grep {! $outsiders{$_}} map {$_->[2]} grep {$_->[1] eq $api_class} @$methods; - push( @{$delegates{$_}}, {api_name => $api_name, api_class => $api_class} ) for @local_methods; + push( @{$delegates{$_}}, {api_name => $api_name, api_class => $api_class} ) for @local_methods; } - + # remove clashes foreach my $method (keys %delegates) { if ( @{$delegates{$method}} > 1 ) { my ($apis) = delete $delegates{$method}; } } - + # build the flattened API foreach my $api_name ($self->api_factory->apis_available) { my $att_name = sprintf "%s_api", lc($api_name); my $api_class = $self->api_factory->classname_for($api_name); my @delegated = grep { $delegates{$_}->[0]->{api_name} eq $api_name } keys %delegates; $log->debugf("Adding API: '%s' handles %s", $att_name, join ', ', @delegated); - $self->meta->add_attribute( $att_name => ( + $self->meta->add_attribute( $att_name => ( is => 'ro', isa => $api_class, default => sub {$self->api_factory->get_api($api_name)}, @@ -99,62 +101,64 @@ sub _build_af { =head1 NAME -{{moduleName}}::Role - a Moose role for the {{appName}} +{{moduleName}}::Role - a Moose role for the {{appName}} =head2 {{appName}} version: {{appVersion}} =head1 VERSION -Automatically generated by the Perl Swagger Codegen project: +Automatically generated by the Perl Swagger Codegen project: -=over 4 +=over 4 +{{^hideGenerationTimestamp}} =item Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} =item Build package: {{generatorClass}} -=item Codegen version: +=item Codegen version: =back =head2 A note on Moose -This role is the only component of the library that uses Moose. See -{{moduleName}}::ApiFactory for non-Moosey usage. +This role is the only component of the library that uses Moose. See +{{moduleName}}::ApiFactory for non-Moosey usage. =head1 SYNOPSIS -The Perl Swagger Codegen project builds a library of Perl modules to interact with -a web service defined by a OpenAPI Specification. See below for how to build the +The Perl Swagger Codegen project builds a library of Perl modules to interact with +a web service defined by a OpenAPI Specification. See below for how to build the library. -This module provides an interface to the generated library. All the classes, -objects, and methods (well, not quite *all*, see below) are flattened into this -role. +This module provides an interface to the generated library. All the classes, +objects, and methods (well, not quite *all*, see below) are flattened into this +role. package MyApp; use Moose; with '{{moduleName}}::Role'; - + package main; - + my $api = MyApp->new({ tokens => $tokens }); - + my $pet = $api->get_pet_by_id(pet_id => $pet_id); - + =head2 Structure of the library The library consists of a set of API classes, one for each endpoint. These APIs -implement the method calls available on each endpoint. +implement the method calls available on each endpoint. -Additionally, there is a set of "object" classes, which represent the objects -returned by and sent to the methods on the endpoints. +Additionally, there is a set of "object" classes, which represent the objects +returned by and sent to the methods on the endpoints. -An API factory class is provided, which builds instances of each endpoint API. +An API factory class is provided, which builds instances of each endpoint API. -This Moose role flattens all the methods from the endpoint APIs onto the consuming -class. It also provides methods to retrieve the endpoint API objects, and the API -factory object, should you need it. +This Moose role flattens all the methods from the endpoint APIs onto the consuming +class. It also provides methods to retrieve the endpoint API objects, and the API +factory object, should you need it. For documentation of all these methods, see AUTOMATIC DOCUMENTATION below. @@ -167,33 +171,33 @@ required and where to put them. You just need to supply the tokens. # basic username => $username, password => $password, - + # oauth access_token => $oauth_token, - + # keys $some_key => { token => $token, - prefix => $prefix, - in => $in, # 'head||query', + prefix => $prefix, + in => $in, # 'head||query', }, - + $another => { token => $token, - prefix => $prefix, - in => $in, # 'head||query', - }, + prefix => $prefix, + in => $in, # 'head||query', + }, ..., - + }; - + my $api = MyApp->new({ tokens => $tokens }); Note these are all optional, as are C and C, and depend on the API you are accessing. Usually C and C will be determined by the code generator from the spec and you will not need to set them at run time. If not, C will -default to 'head' and C to the empty string. +default to 'head' and C to the empty string. The tokens will be placed in the C<{{moduleName}}::Configuration> namespace -as follows, but you don't need to know about this. +as follows, but you don't need to know about this. =over 4 @@ -226,7 +230,7 @@ all api keys require a prefix. =item C<${{moduleName}}::Configuration::access_token> -String. The OAuth access token. +String. The OAuth access token. =back @@ -234,16 +238,16 @@ String. The OAuth access token. =head2 C -The generated code has the C already set as a default value. This method -returns (and optionally sets, but only if the API client has not been +The generated code has the C already set as a default value. This method +returns (and optionally sets, but only if the API client has not been created yet) the current value of C. =head2 C -Returns an API factory object. You probably won't need to call this directly. - +Returns an API factory object. You probably won't need to call this directly. + $self->api_factory('Pet'); # returns a {{moduleName}}::PetApi instance - + $self->pet_api; # the same =head1 MISSING METHODS @@ -253,9 +257,9 @@ Most of the methods on the API are delegated to individual endpoint API objects same method name (e.g. C), these methods can't be delegated. So you need to call C<$api-Epet_api-Enew()>. -In principle, every API is susceptible to the presence of a few, random, undelegatable -method names. In practice, because of the way method names are constructed, it's -unlikely in general that any methods will be undelegatable, except for: +In principle, every API is susceptible to the presence of a few, random, undelegatable +method names. In practice, because of the way method names are constructed, it's +unlikely in general that any methods will be undelegatable, except for: new() class_documentation() @@ -268,12 +272,12 @@ you could also call them on class names. =head1 BUILDING YOUR LIBRARY -See the homepage C for full details. -But briefly, clone the git repository, build the codegen codebase, set up your build +See the homepage C for full details. +But briefly, clone the git repository, build the codegen codebase, set up your build config file, then run the API build script. You will need git, Java 7 or 8 and Apache maven 3.0.3 or better already installed. -The config file should specify the project name for the generated library: +The config file should specify the project name for the generated library: {"moduleName":"WWW::MyProjectName"} @@ -288,8 +292,8 @@ Your library files will be built under C. -c /path/to/config/file.json \ -o /path/to/output/folder -Bang, all done. Run the C script in the C directory to see the API -you just built. +Bang, all done. Run the C script in the C directory to see the API +you just built. =head1 AUTOMATIC DOCUMENTATION @@ -301,28 +305,28 @@ output formats are supported: -w wide format (default) -n narrow format - -p POD format - -H HTML format + -p POD format + -H HTML format -m Markdown format -h print this help message -c your application class - + The C<-c> option allows you to load and inspect your own application. A dummy namespace is used if you don't supply your own class. =head1 DOCUMENTATION FROM THE OpenAPI Spec -Additional documentation for each class and method may be provided by the Swagger -spec. If so, this is available via the C and -C methods on each generated object class, and the -C method on the endpoint API classes: +Additional documentation for each class and method may be provided by the Swagger +spec. If so, this is available via the C and +C methods on each generated object class, and the +C method on the endpoint API classes: - my $cmdoc = $api->pet_api->method_documentation->{$method_name}; - - my $odoc = $api->get_pet_by_id->(pet_id => $pet_id)->class_documentation; - my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; - -Each of these calls returns a hashref with various useful pieces of information. + my $cmdoc = $api->pet_api->method_documentation->{$method_name}; + + my $odoc = $api->get_pet_by_id->(pet_id => $pet_id)->class_documentation; + my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; + +Each of these calls returns a hashref with various useful pieces of information. =cut diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 27d02e1d33d..dd1a221d766 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -153,6 +153,11 @@ class ApiClient if ($this->config->getCurlTimeout() !== 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } + // set connect timeout, if needed + if ($this->config->getCurlConnectTimeout() != 0) { + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->config->getCurlConnectTimeout()); + } + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); @@ -164,6 +169,22 @@ class ApiClient curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } + if ($this->config->getCurlProxyHost()) { + curl_setopt($curl, CURLOPT_PROXY, $this->config->getCurlProxyHost()); + } + + if ($this->config->getCurlProxyPort()) { + curl_setopt($curl, CURLOPT_PROXYPORT, $this->config->getCurlProxyPort()); + } + + if ($this->config->getCurlProxyType()) { + curl_setopt($curl, CURLOPT_PROXYTYPE, $this->config->getCurlProxyType()); + } + + if ($this->config->getCurlProxyUser()) { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->config->getCurlProxyUser() . ':' .$this->config->getCurlProxyPassword()); + } + if (!empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 1768ff7ac5e..bfbb6fca373 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -49,7 +49,6 @@ use \{{invokerPackage}}\ObjectSerializer; { if ($apiClient === null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('{{basePath}}'); } $this->apiClient = $apiClient; diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 4877db1db29..d409c625cda 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -87,6 +87,13 @@ class Configuration */ protected $curlTimeout = 0; + /** + * Timeout (second) of the HTTP connection, by default set to 0, no timeout + * + * @var string + */ + protected $curlConnectTimeout = 0; + /** * User agent of the HTTP request, set to "PHP-Swagger" by default * @@ -124,6 +131,42 @@ class Configuration */ protected $sslVerification = true; + /** + * Curl proxy host + * + * @var string + */ + protected $proxyHost; + + /** + * Curl proxy port + * + * @var integer + */ + protected $proxyPort; + + /** + * Curl proxy type, e.g. CURLPROXY_HTTP or CURLPROXY_SOCKS5 + * + * @see https://secure.php.net/manual/en/function.curl-setopt.php + * @var integer + */ + protected $proxyType; + + /** + * Curl proxy username + * + * @var string + */ + protected $proxyUser; + + /** + * Curl proxy password + * + * @var string + */ + protected $proxyPassword; + /** * Constructor */ @@ -370,6 +413,149 @@ class Configuration return $this->curlTimeout; } + /** + * Sets the HTTP connect timeout value + * + * @param integer $seconds Number of seconds before connection times out [set to 0 for no timeout] + * + * @return Configuration + */ + public function setCurlConnectTimeout($seconds) + { + if (!is_numeric($seconds) || $seconds < 0) { + throw new \InvalidArgumentException('Connect timeout value must be numeric and a non-negative number.'); + } + + $this->curlConnectTimeout = $seconds; + return $this; + } + + /** + * Gets the HTTP connect timeout value + * + * @return string HTTP connect timeout value + */ + public function getCurlConnectTimeout() + { + return $this->curlConnectTimeout; + } + + + /** + * Sets the HTTP Proxy Host + * + * @param string $proxyHost HTTP Proxy URL + * + * @return ApiClient + */ + public function setCurlProxyHost($proxyHost) + { + $this->proxyHost = $proxyHost; + return $this; + } + + /** + * Gets the HTTP Proxy Host + * + * @return string + */ + public function getCurlProxyHost() + { + return $this->proxyHost; + } + + /** + * Sets the HTTP Proxy Port + * + * @param integer $proxyPort HTTP Proxy Port + * + * @return ApiClient + */ + public function setCurlProxyPort($proxyPort) + { + $this->proxyPort = $proxyPort; + return $this; + } + + /** + * Gets the HTTP Proxy Port + * + * @return integer + */ + public function getCurlProxyPort() + { + return $this->proxyPort; + } + + /** + * Sets the HTTP Proxy Type + * + * @param integer $proxyType HTTP Proxy Type + * + * @return ApiClient + */ + public function setCurlProxyType($proxyType) + { + $this->proxyType = $proxyType; + return $this; + } + + /** + * Gets the HTTP Proxy Type + * + * @return integer + */ + public function getCurlProxyType() + { + return $this->proxyType; + } + + /** + * Sets the HTTP Proxy User + * + * @param string $proxyUser HTTP Proxy User + * + * @return ApiClient + */ + public function setCurlProxyUser($proxyUser) + { + $this->proxyUser = $proxyUser; + return $this; + } + + /** + * Gets the HTTP Proxy User + * + * @return string + */ + public function getCurlProxyUser() + { + return $this->proxyUser; + } + + /** + * Sets the HTTP Proxy Password + * + * @param string $proxyPassword HTTP Proxy Password + * + * @return ApiClient + */ + public function setCurlProxyPassword($proxyPassword) + { + $this->proxyPassword = $proxyPassword; + return $this; + } + + /** + * Gets the HTTP Proxy Password + * + * @return string + */ + public function getCurlProxyPassword() + { + return $this->proxyPassword; + } + /** * Sets debug flag * diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 0c2378aa1a5..9c4eab93107 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -26,11 +26,10 @@ use \ArrayAccess; /** * {{classname}} Class Doc Comment * - * @category Class */ + * @category Class {{#description}} - // @description {{description}} + * @description {{description}} {{/description}} -/** * @package {{invokerPackage}} * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen diff --git a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache index f7ab60ad616..ae141ee6cab 100644 --- a/modules/swagger-codegen/src/main/resources/php/model_generic.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model_generic.mustache @@ -117,7 +117,13 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple */ public function listInvalidProperties() { + {{#parent}} + $invalid_properties = parent::listInvalidProperties(); + {{/parent}} + {{^parent}} $invalid_properties = []; + {{/parent}} + {{#vars}} {{#required}} if ($this->container['{{name}}'] === null) { @@ -128,7 +134,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple {{^isContainer}} $allowed_values = [{{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}]; if (!in_array($this->container['{{name}}'], $allowed_values)) { - $invalid_properties[] = "invalid value for '{{name}}', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for '{{name}}', must be one of {{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}."; } {{/isContainer}} @@ -185,10 +191,16 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}}imple * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + {{#parent}} + if (!parent::valid()) { + return false; + } + {{/parent}} + {{#vars}} {{#required}} if ($this->container['{{name}}'] === null) { diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index eb8b73c7bdf..04b53afba9b 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -107,7 +107,7 @@ class ApiClient(object): collection_formats) for k, v in path_params: resource_path = resource_path.replace( - '{%s}' % k, quote(str(v))) + '{%s}' % k, quote(str(v), safe='')) # no safe chars, encode everything # query parameters if query_params: diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 171b7277f06..dcf3c755020 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -172,6 +172,9 @@ class {{classname}}(object): """ Returns true if both objects are equal """ + if not isinstance(other, {{classname}}): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache b/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache index bde2a260c61..a5dd2578e20 100644 --- a/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/qt5cpp/model-body.mustache @@ -57,10 +57,10 @@ void void {{classname}}::fromJsonObject(QJsonObject &pJson) { {{#vars}} - {{^isContainer}}::Swagger::setValue(&{{name}}, pJson["{{name}}"], "{{baseType}}", "{{complexType}}");{{/isContainer}} + {{^isContainer}}::Swagger::setValue(&{{name}}, pJson["{{baseName}}"], "{{baseType}}", "{{complexType}}");{{/isContainer}} {{#isContainer}} - {{#complexType}}::Swagger::setValue(&{{name}}, pJson["{{name}}"], "{{baseType}}", "{{complexType}}");{{/complexType}} - {{^complexType}}::Swagger::setValue(&{{name}}, pJson["{{name}}"], "{{baseType}}", "{{items.baseType}}");{{/complexType}} + {{#complexType}}::Swagger::setValue(&{{name}}, pJson["{{baseName}}"], "{{baseType}}", "{{complexType}}");{{/complexType}} + {{^complexType}}::Swagger::setValue(&{{name}}, pJson["{{baseName}}"], "{{baseType}}", "{{items.baseType}}");{{/complexType}} {{/isContainer}} {{/vars}} } @@ -79,17 +79,17 @@ QJsonObject* {{classname}}::asJsonObject() { QJsonObject* obj = new QJsonObject(); {{#vars}}{{#complexType}}{{^isContainer}}{{#complexType}} - toJsonValue(QString("{{name}}"), {{name}}, obj, QString("{{complexType}}"));{{/complexType}}{{^complexType}} + toJsonValue(QString("{{baseName}}"), {{name}}, obj, QString("{{complexType}}"));{{/complexType}}{{^complexType}} if({{name}} != nullptr && *{{name}} != nullptr) { obj->insert("{{name}}", QJsonValue(*{{name}})); }{{/complexType}}{{/isContainer}}{{#isContainer}} QJsonArray {{name}}JsonArray; toJsonArray((QList*){{name}}, &{{name}}JsonArray, "{{name}}", "{{complexType}}"); - obj->insert("{{name}}", {{name}}JsonArray);{{/isContainer}}{{/complexType}}{{^complexType}}{{^isContainer}} - obj->insert("{{name}}", QJsonValue({{name}}));{{/isContainer}}{{#isContainer}} + obj->insert("{{baseName}}", {{name}}JsonArray);{{/isContainer}}{{/complexType}}{{^complexType}}{{^isContainer}} + obj->insert("{{baseName}}", QJsonValue({{name}}));{{/isContainer}}{{#isContainer}} QJsonArray {{name}}JsonArray; toJsonArray((QList*){{name}}, &{{name}}JsonArray, "{{name}}", "{{items.baseType}}"); - obj->insert("{{name}}", {{name}}JsonArray);{{/isContainer}}{{/complexType}} + obj->insert("{{baseName}}", {{name}}JsonArray);{{/isContainer}}{{/complexType}} {{/vars}} return obj; diff --git a/modules/swagger-codegen/src/main/resources/rails5/README.md b/modules/swagger-codegen/src/main/resources/rails5/README.md index 841b82ad656..91fe3051c49 100644 --- a/modules/swagger-codegen/src/main/resources/rails5/README.md +++ b/modules/swagger-codegen/src/main/resources/rails5/README.md @@ -1,6 +1,6 @@ # Swagger for Rails 5 -This is a project to provide Swagger support inside the [Sinatra](http://rubyonrails.org/) framework. +This is a project to provide Swagger support inside the [Ruby on Rails](http://rubyonrails.org/) framework. ## Prerequisites You need to install ruby >= 2.2.2 and run: diff --git a/modules/swagger-codegen/src/main/resources/scala/api.mustache b/modules/swagger-codegen/src/main/resources/scala/api.mustache index 977f4e2b056..177fc96cd13 100644 --- a/modules/swagger-codegen/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -113,7 +113,7 @@ class {{classname}}(val defBasePath: String = "{{basePath}}", try { apiInvoker.invokeApi(basePath, path, "{{httpMethod}}", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - {{#returnType}} Some(ApiInvoker.deserialize(s, "{{returnContainer}}", classOf[{{returnBaseType}}]).asInstanceOf[{{returnType}}]) + {{#returnType}} Some(apiInvoker.deserialize(s, "{{returnContainer}}", classOf[{{returnBaseType}}]).asInstanceOf[{{returnType}}]) {{/returnType}} case _ => None } diff --git a/modules/swagger-codegen/src/main/resources/scalatra/build.sbt b/modules/swagger-codegen/src/main/resources/scalatra/build.sbt index 00575312d85..9dc3cff3596 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/build.sbt +++ b/modules/swagger-codegen/src/main/resources/scalatra/build.sbt @@ -23,23 +23,12 @@ scalaVersion := "2.11.2" scalacOptions += "-language:postfixOps" libraryDependencies ++= Seq( - "org.scalatest" %% "scalatest" % "2.2.1" % "test", - "org.scalatra" %% "scalatra" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-json" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3", - "org.json4s" %% "json4s-jackson" % "3.2.10", - "org.json4s" %% "json4s-ext" % "3.2.10", - "commons-codec" % "commons-codec" % "1.7", - "net.databinder.dispatch" %% "dispatch-core" % "0.11.2", - //"net.databinder.dispatch" %% "json4s-jackson" % "0.11.2", - "net.databinder.dispatch" %% "dispatch-json4s-jackson" % "0.11.2", - "com.typesafe.akka" %% "akka-actor" % "2.3.6", - "org.eclipse.jetty" % "jetty-server" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty" % "jetty-webapp" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar")) + "com.github.finagle" %% "finch-core" % "0.9.2-SNAPSHOT" changing(), + "com.github.finagle" %% "finch-argonaut" % "0.9.2-SNAPSHOT" changing(), + "io.argonaut" %% "argonaut" % "6.1", + "com.github.finagle" %% "finch-test" % "0.9.2-SNAPSHOT" % "test,it" changing(), + "org.scalacheck" %% "scalacheck" % "1.12.5" % "test,it", + "org.scalatest" %% "scalatest" % "2.2.5" % "test,it" ) resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository" @@ -48,6 +37,9 @@ resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/reposi resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/" +resolvers += "TM" at "http://maven.twttr.com" + + ivyXML := diff --git a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache index 23e727b6b54..b91cd27851a 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIHelper.mustache @@ -19,6 +19,16 @@ class APIHelper { return destination } + static func rejectNilHeaders(source: [String:AnyObject?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { guard let source = source else { return nil diff --git a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache index 9ba749ab69e..e16e45b1a18 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache @@ -31,7 +31,7 @@ public class APIBase { public class RequestBuilder { var credential: NSURLCredential? - var headers: [String:String] = [:] + var headers: [String:String] let parameters: [String:AnyObject]? let isBody: Bool let method: String @@ -40,11 +40,12 @@ public class RequestBuilder { /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((NSProgress) -> ())? - required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool, headers: [String:String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody + self.headers = headers addHeaders({{projectName}}API.customHeaders) } diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 4ea47d8926c..66971688891 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -41,8 +41,8 @@ public struct SynchronizedDictionary { private var managerStore = SynchronizedDictionary() class AlamofireRequestBuilder: RequestBuilder { - required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { - super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 24b8905f2c5..c339c4433d8 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -119,11 +119,15 @@ public class {{classname}}: APIBase { let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} - let convertedParameters = APIHelper.convertBoolToString(parameters) + let convertedParameters = APIHelper.convertBoolToString(parameters){{#headerParams}}{{^secondaryParam}} + let nillableHeaders: [String: AnyObject?] = [{{/secondaryParam}} + {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders){{/hasMore}}{{/headerParams}} let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: convertedParameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) + return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: convertedParameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}{{#headerParams}}{{^secondaryParam}}, headers: headerParameters{{/secondaryParam}}{{/headerParams}}) } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/swift3/APIHelper.mustache b/modules/swagger-codegen/src/main/resources/swift3/APIHelper.mustache index 967dcc34735..b612ff90921 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/APIHelper.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/APIHelper.mustache @@ -21,6 +21,16 @@ class APIHelper { return destination } + static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { guard let source = source else { return nil @@ -39,4 +49,17 @@ class APIHelper { return destination } + + static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { + let returnValues = values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + if returnValues.count == 0 { + return nil + } + return returnValues + } + } diff --git a/modules/swagger-codegen/src/main/resources/swift3/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift3/APIs.mustache index cf17d427e7e..ee1560e2997 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/APIs.mustache @@ -31,7 +31,7 @@ open class APIBase { open class RequestBuilder { var credential: URLCredential? - var headers: [String:String] = [:] + var headers: [String:String] let parameters: [String:Any]? let isBody: Bool let method: String @@ -40,11 +40,12 @@ open class RequestBuilder { /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? - required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool) { + required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody + self.headers = headers addHeaders({{projectName}}API.customHeaders) } diff --git a/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache index d8e2004302d..801647631e4 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/AlamofireImplementations.mustache @@ -16,8 +16,8 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { private var managerStore: [String: Alamofire.SessionManager] = [:] open class AlamofireRequestBuilder: RequestBuilder { - required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool) { - super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } /** diff --git a/modules/swagger-codegen/src/main/resources/swift3/api.mustache b/modules/swagger-codegen/src/main/resources/swift3/api.mustache index c997fe7b352..8ef1739f687 100644 --- a/modules/swagger-codegen/src/main/resources/swift3/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift3/api.mustache @@ -108,20 +108,40 @@ open class {{classname}}: APIBase { path = path.replacingOccurrences(of: "{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", with: "\({{paramName}}{{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}})", options: .literal, range: nil){{/pathParams}} let URLString = {{projectName}}API.basePath + path {{#bodyParam}} - let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} - let nillableParameters: [String:Any?] = {{^queryParams}}{{^formParams}}[:]{{/formParams}}{{#formParams}}{{^secondaryParam}}[{{/secondaryParam}} + let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject] + {{/bodyParam}} + {{^bodyParam}} + {{#hasFormParams}} + let formParams: [String:Any?] = [ + {{#formParams}} + {{> _param}}{{#hasMore}},{{/hasMore}} + {{/formParams}} + ] + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + {{/hasFormParams}} + {{^hasFormParams}} + let parameters: [String:Any]? = nil + {{/hasFormParams}} + {{/bodyParam}} + + let url = NSURLComponents(string: URLString) + {{#hasQueryParams}} + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + {{#queryParams}} + {{> _param}}{{#hasMore}}, {{/hasMore}} + {{/queryParams}} + ]) + {{/hasQueryParams}}{{#headerParams}}{{^secondaryParam}} + let nillableHeaders: [String: Any?] = [{{/secondaryParam}} {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} - ]{{/hasMore}}{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} - {{> _param}}{{#hasMore}},{{/hasMore}}{{^hasMore}} - ]{{/hasMore}}{{/queryParams}} - - let parameters = APIHelper.rejectNil(nillableParameters){{/bodyParam}} - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders){{/hasMore}}{{/headerParams}} + let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: convertedParameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) + return requestBuilder.init(method: "{{httpMethod}}", URLString: (url?.string ?? URLString), parameters: parameters, isBody: {{hasBodyParam}}{{#headerParams}}{{^secondaryParam}}, headers: headerParameters{{/secondaryParam}}{{/headerParams}}) } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/api.d.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/api.d.mustache deleted file mode 100644 index a8bf1c58267..00000000000 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/api.d.mustache +++ /dev/null @@ -1,13 +0,0 @@ -{{#models}} -{{#model}} -/// -{{/model}} -{{/models}} - -{{#apiInfo}} -{{#apis}} -{{#operations}} -/// -{{/operations}} -{{/apis}} -{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/api.module.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/api.module.mustache new file mode 100644 index 00000000000..1b01079af8c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/api.module.mustache @@ -0,0 +1,13 @@ +import * as api from './api/api'; +import * as angular from 'angular'; + +{{#apiInfo}} +const apiModule = angular.module('api', []) +{{#apis}} +{{#operations}} +.service('{{classname}}', api.{{classname}}) +{{/operations}} +{{/apis}} + +export default apiModule; +{{/apiInfo}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache index 6a426c806f1..f73752f7df5 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/api.mustache @@ -1,99 +1,85 @@ {{>licenseInfo}} -/// +import * as models from '../model/models'; /* tslint:disable:no-unused-variable member-ordering */ {{#operations}} -namespace {{package}} { - 'use strict'; - {{#description}} - /** - * {{&description}} - */ +/** + * {{&description}} + */ {{/description}} - export class {{classname}} { - protected basePath = '{{basePath}}'; - public defaultHeaders : any = {}; +export class {{classname}} { + protected basePath = '{{basePath}}'; + public defaultHeaders : any = {}; - static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; - constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath !== undefined) { - this.basePath = basePath; - } - } - - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { + if (basePath !== undefined) { + this.basePath = basePath; } + } {{#operation}} - /** - * {{summary}} - * {{notes}} - {{#allParams}}* @param {{paramName}} {{description}} - {{/allParams}}*/ - public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { - const localVarPath = this.basePath + '{{path}}'{{#pathParams}} - .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; + /** + * {{summary}} + * {{notes}} + {{#allParams}}* @param {{paramName}} {{description}} + {{/allParams}}*/ + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { + const localVarPath = this.basePath + '{{path}}'{{#pathParams}} + .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); {{#hasFormParams}} - let formParams: any = {}; + let formParams: any = {}; {{/hasFormParams}} {{#allParams}} {{#required}} - // verify required parameter '{{paramName}}' is not null or undefined - if ({{paramName}} === null || {{paramName}} === undefined) { - throw new Error('Required parameter {{paramName}} was null or undefined when calling {{nickname}}.'); - } + // verify required parameter '{{paramName}}' is not null or undefined + if ({{paramName}} === null || {{paramName}} === undefined) { + throw new Error('Required parameter {{paramName}} was null or undefined when calling {{nickname}}.'); + } {{/required}} {{/allParams}} {{#queryParams}} - if ({{paramName}} !== undefined) { - queryParameters['{{baseName}}'] = {{paramName}}; - } + if ({{paramName}} !== undefined) { + queryParameters['{{baseName}}'] = {{paramName}}; + } {{/queryParams}} {{#headerParams}} - headerParams['{{baseName}}'] = {{paramName}}; + headerParams['{{baseName}}'] = {{paramName}}; {{/headerParams}} {{#hasFormParams}} - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; {{/hasFormParams}} {{#formParams}} - formParams['{{baseName}}'] = {{paramName}}; + formParams['{{baseName}}'] = {{paramName}}; {{/formParams}} - let httpRequestParams: any = { - method: '{{httpMethod}}', - url: localVarPath, - json: {{#hasFormParams}}false{{/hasFormParams}}{{^hasFormParams}}true{{/hasFormParams}}, - {{#bodyParam}}data: {{paramName}}, - {{/bodyParam}} - {{#hasFormParams}}data: this.$httpParamSerializer(formParams), - {{/hasFormParams}} - params: queryParameters, - headers: headerParams - }; + let httpRequestParams: ng.IRequestConfig = { + method: '{{httpMethod}}', + url: localVarPath, + {{#bodyParam}}data: {{paramName}}, + {{/bodyParam}} + {{#hasFormParams}}data: this.$httpParamSerializer(formParams), + {{/hasFormParams}} + params: queryParameters, + headers: headerParams + }; - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); } -{{/operation}} + + return this.$http(httpRequestParams); } +{{/operation}} } -{{/operations}} +{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/apis.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/apis.mustache new file mode 100644 index 00000000000..85522cf6c58 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/apis.mustache @@ -0,0 +1,9 @@ +{{#apiInfo}} +{{#apis}} +{{#operations}} +export * from './{{ classname }}'; +import { {{ classname }} } from './{{ classname }}'; +{{/operations}} +{{/apis}} +export const APIS = [ {{#apis}}{{#operations}}{{ classname }}, {{/operations}}{{/apis}}]; +{{/apiInfo}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/index.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/index.mustache new file mode 100644 index 00000000000..557365516ad --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/index.mustache @@ -0,0 +1,2 @@ +export * from './api/api'; +export * from './model/models'; \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/model.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/model.mustache index 56732788f62..f1bded256c0 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular/model.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/model.mustache @@ -1,43 +1,38 @@ {{>licenseInfo}} -/// - -namespace {{package}} { - 'use strict'; +import * as models from './models'; {{#models}} {{#model}} +{{#description}} +/** + * {{{description}}} + */ +{{/description}} +export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ +{{#vars}} {{#description}} /** * {{{description}}} */ {{/description}} - export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ -{{#vars}} -{{#description}} - /** - * {{{description}}} - */ -{{/description}} - "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; - + "{{name}}"{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{/isEnum}}; {{/vars}} - } +} {{#hasEnums}} - export namespace {{classname}} { +export namespace {{classname}} { {{#vars}} {{#isEnum}} - export enum {{enumName}} { - {{#allowableValues}} - {{#enumVars}} - {{{name}}} = {{{value}}}{{^-last}},{{/-last}} - {{/enumVars}} - {{/allowableValues}} - } + export enum {{enumName}} { + {{#allowableValues}} + {{#enumVars}} + {{{name}}} = {{{value}}}{{^-last}},{{/-last}} + {{/enumVars}} + {{/allowableValues}} + } {{/isEnum}} {{/vars}} - } +} {{/hasEnums}} {{/model}} {{/models}} -} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular/models.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular/models.mustache new file mode 100644 index 00000000000..ace053bd55b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/typescript-angular/models.mustache @@ -0,0 +1,5 @@ +{{#models}} +{{#model}} +export * from './{{{ classname }}}'; +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.service.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.service.mustache index 2b3ce3713b5..a80fb8e022d 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/api.service.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/api.service.mustache @@ -11,7 +11,7 @@ import '../rxjs-operators'; import { {{classname}} } from '../{{filename}}'; {{/imports}} -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -113,15 +113,40 @@ export class {{classname}} { {{/required}} {{/allParams}} {{#queryParams}} - if ({{paramName}} !== undefined) { - queryParameters.set('{{baseName}}', {{paramName}}); + {{#isListContainer}} + if ({{paramName}}) { + {{#isCollectionFormatMulti}} + {{paramName}}.forEach((element) => { + queryParameters.append('{{baseName}}', element); + }) + {{/isCollectionFormatMulti}} + {{^isCollectionFormatMulti}} + queryParameters.set('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])); + {{/isCollectionFormatMulti}} } + {{/isListContainer}} + {{^isListContainer}} + if ({{paramName}} !== undefined) { + if({{paramName}} instanceof Date) { + queryParameters.set('{{baseName}}', {{paramName}}.d.toISOString()); + } else { + queryParameters.set('{{baseName}}', {{paramName}}); + } + } + {{/isListContainer}} + {{/queryParams}} - {{#headerParams}} + {{#isListContainer}} + if ({{paramName}}) { + headers.set('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])); + } + {{/isListContainer}} + {{^isListContainer}} headers.set('{{baseName}}', String({{paramName}})); -{{/headerParams}} + {{/isListContainer}} +{{/headerParams}} {{#hasFormParams}} // to determine the Content-Type header let consumes: string[] = [ @@ -147,52 +172,66 @@ export class {{classname}} { '{{{mediaType}}}'{{#hasMore}}, {{/hasMore}} {{/produces}} ]; - + {{#authMethods}} // authentication ({{name}}) required {{#isApiKey}} {{#isKeyInHeader}} - if (this.configuration.apiKey) - { + if (this.configuration.apiKey) { headers.set('{{keyParamName}}', this.configuration.apiKey); } + {{/isKeyInHeader}} {{#isKeyInQuery}} - if (this.configuration.apiKey) - { - formParams.set('{{keyParamName}}', this.configuration.apiKey); + if (this.configuration.apiKey) { + queryParameters.set('{{keyParamName}}', this.configuration.apiKey); } + {{/isKeyInQuery}} {{/isApiKey}} {{#isBasic}} // http basic authentication required - if (this.configuration.username || this.configuration.password) - { + if (this.configuration.username || this.configuration.password) { headers.set('Authorization', 'Basic ' + btoa(this.configuration.username + ':' + this.configuration.password)); } + {{/isBasic}} {{#isOAuth}} // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + {{/isOAuth}} {{/authMethods}} {{#bodyParam}} headers.set('Content-Type', 'application/json'); + {{/bodyParam}} - {{#formParams}} - if ({{paramName}} !== undefined) { - formParams.set('{{baseName}}', {{paramName}}); + {{#isListContainer}} + if ({{paramName}}) { + {{#isCollectionFormatMulti}} + {{paramName}}.forEach((element) => { + formParams.append('{{baseName}}', element); + }) + {{/isCollectionFormatMulti}} + {{^isCollectionFormatMulti}} + formParams.set('{{baseName}}', {{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])); + {{/isCollectionFormatMulti}} } -{{/formParams}} + {{/isListContainer}} + {{^isListContainer}} + if ({{paramName}} !== undefined) { + formParams.set('{{baseName}}', {{paramName}}); + } + {{/isListContainer}} +{{/formParams}} let requestOptions: RequestOptionsArgs = new RequestOptions({ method: {{httpMethod}}, headers: headers, @@ -207,10 +246,10 @@ export class {{classname}} { {{/isResponseFile}} search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache index 09109130871..28e0c985929 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/apis.mustache @@ -4,4 +4,5 @@ export * from './{{ apiFilename }}'; {{/operations}} {{/apis}} -{{/apiInfo}} \ No newline at end of file +export const APIS = [ {{#apis}}{{#operations}}{{ classname }}, {{/operations}}{{/apis}}]; +{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache b/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache index 27b987e9b23..944e688f1b1 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-angular2/variables.mustache @@ -1,3 +1,9 @@ import { OpaqueToken } from '@angular/core'; -export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file +export const BASE_PATH = new OpaqueToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache b/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache index 7174bc168b0..6c69a0e9b37 100644 --- a/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/typescript-node/api.mustache @@ -346,14 +346,6 @@ export class {{classname}} { } {{/isOAuth}} {{/authMethods}} - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } {{#operation}} /** * {{summary}} @@ -364,7 +356,7 @@ export class {{classname}} { const localVarPath = this.basePath + '{{path}}'{{#pathParams}} .replace('{' + '{{baseName}}' + '}', String({{paramName}})){{/pathParams}}; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; {{#allParams}}{{#required}} diff --git a/modules/swagger-codegen/src/main/resources/undertow/pojo.mustache b/modules/swagger-codegen/src/main/resources/undertow/pojo.mustache index 58bfed16381..e63ecfe2f47 100644 --- a/modules/swagger-codegen/src/main/resources/undertow/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/undertow/pojo.mustache @@ -19,7 +19,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali return this; } - {{#vendorExtensions.extraAnnotation}}{{vendorExtensions.extraAnnotation}}{{/vendorExtensions.extraAnnotation}} + {{#vendorExtensions.extraAnnotation}}{{{vendorExtensions.extraAnnotation}}}{{/vendorExtensions.extraAnnotation}} @ApiModelProperty({{#example}}example = "{{example}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") @JsonProperty("{{baseName}}") public {{{datatypeWithEnum}}} {{getter}}() { diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/Date.php.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/Date.php.mustache new file mode 100644 index 00000000000..89bcf5ba0ec --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/Date.php.mustache @@ -0,0 +1,17 @@ +format(static::DATE_TIME_FORMAT); + } + return $result; + } + + /** + * @inheritDoc + */ + public function hydrate($arrayValue, $objectValue, array $array = null) + { + $result = null; + if (!empty($arrayValue)) { + $date = $this->parseDateString($arrayValue); + if ($date instanceof \DateTime) { + $result = $date; + } + } + return $result; + } + + /** + * @param $arrayValue + * @return \DateTime + */ + protected function parseDateString($arrayValue) + { + return \DateTime::createFromFormat(static::DATE_TIME_FORMAT, $arrayValue, new \DateTimeZone('UTC')); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/ErrorMiddleware.php.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/ErrorMiddleware.php.mustache new file mode 100644 index 00000000000..d9696c081c9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/ErrorMiddleware.php.mustache @@ -0,0 +1,20 @@ +withStatus(500, 'Internal server error'); + $response->getBody()->write((string)$error); + error_log((string) $error); + return ($out === null)? $response : $out($request, $response); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/README.md.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/README.md.mustache new file mode 100644 index 00000000000..81eb543af3a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/README.md.mustache @@ -0,0 +1,10 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a PHP server. + +This example uses the [Zend Expressive](https://zendframework.github.io/zend-expressive) micro framework and [Path Handler](https://github.com/Articus/PathHandler) library. To see how to make this your own, please take a look at the template here: + +[TEMPLATES](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources/ze-ph/) diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/Type.php.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/Type.php.mustache new file mode 100644 index 00000000000..050fbbef54b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/Type.php.mustache @@ -0,0 +1,71 @@ + 'Invalid type given.', + ]; + + /** + * @var string + */ + protected $type; + + /** + * @return mixed + */ + public function getType() + { + return $this->type; + } + + /** + * @param string $type + * @return self + */ + public function setType($type) + { + $this->type = $type; + return $this; + } + + /** + * @inheritDoc + */ + public function isValid($value) + { + $result = true; + if (!$this->checkType($value)) { + $this->error(self::INVALID); + $result = false; + } + return $result; + } + + protected function checkType($value) + { + switch ($this->type) { + case 'int': + return is_int($value); + case 'bool': + return is_bool($value); + case 'float': + return is_float($value) || is_int($value); + case 'string': + return is_string($value); + default: + throw new \InvalidArgumentException(sprintf('Can not check for type %s.', $this->type)); + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/api.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/api.mustache new file mode 100644 index 00000000000..a2463ccfb65 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/api.mustache @@ -0,0 +1,60 @@ +getAttribute("{{paramName}}"); +{{/isPrimitiveType}} +{{/bodyParam}} + throw new PHException\HttpCode(500, "Not implemented"); + } +{{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/app.yml.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/app.yml.mustache new file mode 100644 index 00000000000..1cabd291fd6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/app.yml.mustache @@ -0,0 +1,19 @@ +dependencies: + invokables: + #Has to add this line because currently router is strict requirement for Zend\Expressive\Application even if only middleware_pipeline is used + Zend\Expressive\Router\RouterInterface: Zend\Expressive\Router\ZendRouter + Zend\Diactoros\Response\EmitterInterface: Zend\Diactoros\Response\SapiStreamEmitter + {{invokerPackage}}\ErrorMiddleware: {{invokerPackage}}\ErrorMiddleware + factories: + Zend\Expressive\Application: Zend\Expressive\Container\ApplicationFactory + Articus\PathHandler\Middleware: Articus\PathHandler\MiddlewareFactory + Articus\DataTransfer\Service: Articus\DataTransfer\ServiceFactory + +middleware_pipeline: + api: + middleware: Articus\PathHandler\Middleware + path: {{basePathWithoutHost}} + error: + middleware: {{invokerPackage}}\ErrorMiddleware + error: true + priority: -10000 diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/composer.json.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/composer.json.mustache new file mode 100644 index 00000000000..df263a37b8e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/composer.json.mustache @@ -0,0 +1,22 @@ +{ + "name": "{{gitUserId}}/{{gitRepoId}}", + "description": "{{description}}", + "license": "proprietary", + "version": "{{artifactVersion}}", + "type": "project", + "require": { + "php": "^5.6 || ^7.0", + "ext-yaml" : "^1.2 || ^2.0", + "zendframework/zend-expressive": "^1.0", + "zendframework/zend-expressive-router": "1.2.*", + "articus/path-handler": "0.1.*", + "articus/data-transfer": "*", + "zendframework/zend-serializer": "*", + "zendframework/zend-config": "*" + }, + "autoload": { + "psr-4": { + "": "src/" + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/config.yml b/modules/swagger-codegen/src/main/resources/ze-ph/config.yml new file mode 100644 index 00000000000..dce9c534bcd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/config.yml @@ -0,0 +1,2 @@ +#App +cache_configuration: false diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/container.php b/modules/swagger-codegen/src/main/resources/ze-ph/container.php new file mode 100644 index 00000000000..e70a0663cf3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/container.php @@ -0,0 +1,46 @@ +setService('config', $config); +$container->setAlias('Config', 'config'); + +return $container; diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/data_transfer.yml.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/data_transfer.yml.mustache new file mode 100644 index 00000000000..8c9fb5bfceb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/data_transfer.yml.mustache @@ -0,0 +1,28 @@ +data_transfer: + metadata_cache: + adapter: + name: blackhole +# adapter: +# name: filesystem +# options: +# cache_dir: data/cache/data_transfer +# namespace: dt + + strategies: + invokables: + {{invokerPackage}}\Strategy\Date: {{invokerPackage}}\Strategy\Date + {{invokerPackage}}\Strategy\DateTime: {{invokerPackage}}\Strategy\DateTime +# factories: + aliases: + Date: {{invokerPackage}}\Strategy\Date + DateTime: {{invokerPackage}}\Strategy\DateTime + validators: + invokables: + {{invokerPackage}}\Validator\Type: {{invokerPackage}}\Validator\Type + factories: + Articus\DataTransfer\Validator\Dictionary: Articus\DataTransfer\Validator\Factory + Articus\DataTransfer\Validator\Collection: Articus\DataTransfer\Validator\Factory + aliases: + Dictionary: Articus\DataTransfer\Validator\Dictionary + Collection: Articus\DataTransfer\Validator\Collection + Type: {{invokerPackage}}\Validator\Type diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/index.php b/modules/swagger-codegen/src/main/resources/ze-ph/index.php new file mode 100644 index 00000000000..09e8b0233e4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/index.php @@ -0,0 +1,10 @@ +get(\Zend\Expressive\Application::class); +$app->run(); \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/model.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/model.mustache new file mode 100644 index 00000000000..69201b27e5a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/model.mustache @@ -0,0 +1,131 @@ +route}}{{/routes}} + default_params: + middleware: '' + metadata_cache: + adapter: + name: blackhole +# adapter: +# name: filesystem +# options: +# cache_dir: data/cache/path_handler +# namespace: ph + + handlers: + invokables: +{{#apiInfo}} +{{#apis}} +{{#operations}} + {{classname}}: {{package}}\{{classname}} +{{/operations}} +{{/apis}} +{{/apiInfo}} +# consumers: +# attributes: +# producers: diff --git a/modules/swagger-codegen/src/main/resources/ze-ph/route.mustache b/modules/swagger-codegen/src/main/resources/ze-ph/route.mustache new file mode 100644 index 00000000000..cfb73260540 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ze-ph/route.mustache @@ -0,0 +1,15 @@ + {{padding}}'{{name}}': + {{padding}} type: {{type}} + {{padding}} options: + {{padding}} route: {{route}} +{{#handler}} + {{padding}} defaults: + {{padding}} handler: {{handler}} +{{/handler}} +{{#hasChildren}} +{{#handler}} + {{padding}} may_terminate: true +{{/handler}} + {{padding}} child_routes: +{{/hasChildren}} +{{#children}}{{>route}}{{/children}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java index 5848108055d..a661ba4ea42 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -24,6 +24,20 @@ public class CodegenTest { Assert.assertEquals(codegen.sanitizeTag("1foo"), "_1foo"); } + @Test(description = "test camelize") + public void camelizeNamesTest() { + final DefaultCodegen codegen = new DefaultCodegen(); + + Assert.assertEquals(codegen.camelize("foo"), "Foo"); + Assert.assertEquals(codegen.camelize(".foo"), "Foo"); + Assert.assertEquals(codegen.camelize(".foo.bar"), "FooBar"); + Assert.assertEquals(codegen.camelize("foo$bar"), "Foo$bar"); + Assert.assertEquals(codegen.camelize("foo_bar"), "FooBar"); + Assert.assertEquals(codegen.camelize("foo_bar_baz"), "FooBarBaz"); + Assert.assertEquals(codegen.camelize("foo/bar.baz"), "FooBarBaz"); + Assert.assertEquals(codegen.camelize("/foo/bar/baz.qux/corge"), "FooBarBazQuxCorge"); + } + @Test(description = "read a file upload param from a 2.0 spec") public void fileUploadParamTest() { final Swagger model = parseAndPrepareSwagger("src/test/resources/2_0/petstore.json"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java index d4c22b88aad..ab50384e883 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java @@ -50,12 +50,12 @@ public class ExampleGeneratorTest { types.add(XML); Assert.assertEquals(example, "\n" + " \n" + - " string\n" + + " aeiou\n" + " \n" + " \n" + " \n" + " \n" + - " string\n" + + " aeiou\n" + " \n" + " \n" + " \n" + diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java index b94ec49f361..d3e97de43b8 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/android/AndroidClientOptionsTest.java @@ -48,6 +48,8 @@ public class AndroidClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setSerializableModel(Boolean.valueOf(AndroidClientOptionsProvider.SERIALIZABLE_MODEL_VALUE)); times = 1; + clientCodegen.setAllowUnicodeIdentifiers(Boolean.valueOf(AndroidClientOptionsProvider.ALLOW_UNICODE_IDENTIFIERS_VALUE)); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java new file mode 100644 index 00000000000..1cfb8b847a3 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashClientOptionsTest.java @@ -0,0 +1,59 @@ +package io.swagger.codegen.bash; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.BashClientCodegen; +import io.swagger.codegen.options.BashClientOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class BashClientOptionsTest extends AbstractOptionsTest { + + @Tested + private BashClientCodegen clientCodegen; + + public BashClientOptionsTest() { + super(new BashClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setCurlOptions( + BashClientOptionsProvider.CURL_OPTIONS); + times = 1; + clientCodegen.setProcessMarkdown( + Boolean.parseBoolean( + BashClientOptionsProvider.PROCESS_MARKDOWN)); + times = 1; + clientCodegen.setScriptName( + BashClientOptionsProvider.SCRIPT_NAME); + times = 1; + clientCodegen.setGenerateBashCompletion( + Boolean.parseBoolean( + BashClientOptionsProvider.GENERATE_BASH_COMPLETION)); + times = 1; + clientCodegen.setGenerateZshCompletion( + Boolean.parseBoolean( + BashClientOptionsProvider.GENERATE_ZSH_COMPLETION)); + times = 1; + clientCodegen.setHostEnvironmentVariable( + BashClientOptionsProvider.HOST_ENVIRONMENT_VARIABLE_NAME); + times = 1; + clientCodegen.setApiKeyAuthEnvironmentVariable( + BashClientOptionsProvider.APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME); + times = 1; + clientCodegen.setAllowUnicodeIdentifiers(Boolean.valueOf(BashClientOptionsProvider.ALLOW_UNICODE_IDENTIFIERS_VALUE)); + times = 1; + + }}; + } +} + diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java new file mode 100644 index 00000000000..4f355723a7f --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/bash/BashTest.java @@ -0,0 +1,158 @@ +package io.swagger.codegen.bash; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.BashClientCodegen; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; +import io.swagger.parser.SwaggerParser; + +import org.testng.Assert; +import org.testng.annotations.Test; +import org.testng.annotations.ITestAnnotation; + +import com.google.common.collect.Sets; +import java.util.Map; + +@SuppressWarnings("static-method") +public class BashTest { + + @Test(description = "test basic petstore operation with Bash extensions") + public void petstoreOperationTest() { + + final Swagger swagger + = new SwaggerParser() + .read("src/test/resources/2_0/petstore-bash.json"); + final DefaultCodegen codegen = new BashClientCodegen(); + final Operation findPetsByStatusOperation + = swagger.getPath("/pet/findByStatus").getGet(); + + final CodegenOperation op + = codegen.fromOperation( + "/pet/findByStatus", + "GET", + findPetsByStatusOperation, + swagger.getDefinitions(), + swagger); + + Assert.assertTrue( + op.vendorExtensions.containsKey("x-bash-codegen-sample")); + + Assert.assertEquals( + op.vendorExtensions.get("x-bash-codegen-description"), + "Multiple status 'values' can be provided with comma separated strings"); + + } + + @Test(description = "test basic petstore operation with example body") + public void petstoreParameterExampleTest() { + + final Swagger swagger + = new SwaggerParser() + .read("src/test/resources/2_0/petstore-bash.json"); + final DefaultCodegen codegen = new BashClientCodegen(); + final Operation addPetOperation + = swagger.getPath("/pet").getPost(); + + final CodegenOperation op + = codegen.fromOperation( + "/pet", + "POST", + addPetOperation, + swagger.getDefinitions(), + swagger); + + Assert.assertEquals(op.bodyParams.size(), 1); + + CodegenParameter pet = op.bodyParams.get(0); + + Assert.assertTrue(pet.vendorExtensions + .containsKey("x-codegen-body-example")); + + } + + + @Test(description = "test Bash client codegen escapeText method") + public void escapeTextTest() { + final DefaultCodegen codegen = new BashClientCodegen(); + + + Assert.assertEquals(codegen.escapeText("\\/"), "/"); + + Assert.assertEquals(codegen.escapeText("\\"), "\\\\"); + + + ((BashClientCodegen)codegen).setProcessMarkdown(false); + + Assert.assertEquals(codegen.escapeText("__Bold text__"), + "__Bold text__"); + + Assert.assertEquals(codegen.escapeText("**Bold text**"), + "**Bold text**"); + + Assert.assertEquals(codegen.escapeText("*Italic text*"), + "*Italic text*"); + + Assert.assertEquals(codegen.escapeText("_Italic text_"), + "_Italic text_"); + + + ((BashClientCodegen)codegen).setProcessMarkdown(true); + + Assert.assertEquals(codegen.escapeText("__Bold text__"), + "$(tput bold) Bold text $(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("**Bold text**"), + "$(tput bold) Bold text $(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("*Italic text*"), + "$(tput dim) Italic text $(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("_Italic text_"), + "$(tput dim) Italic text $(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("# SECTION NAME"), + "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("## SECTION NAME"), + "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText("### SECTION NAME"), + "\n$(tput bold)$(tput setaf 7)SECTION NAME$(tput sgr0)"); + + Assert.assertEquals(codegen.escapeText( + "```\nnice -n 100 mvn test\n```"), + "\n---\nnice -n 100 mvn test\n---"); + } + + @Test(description = "test Bash client codegen escapeUnsafeCharacters method") + public void escapeUnsafeCharactersTest() { + final DefaultCodegen codegen = new BashClientCodegen(); + + Assert.assertEquals(codegen.escapeUnsafeCharacters("`no backticks`"), + "'no backticks'"); + + + } + + @Test(description = "test Bash client codegen escapeReservedWord method") + public void escapeReservedWordTest() { + final DefaultCodegen codegen = new BashClientCodegen(); + + Assert.assertEquals(codegen.escapeReservedWord("case"), "_case"); + } + + +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java index e3de3fdf8af..edffc835de8 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java @@ -295,6 +295,8 @@ public class CodegenConfiguratorTest { assertEquals(configurator.getDynamicProperties().size(), 1); assertValueInMap(configurator.getDynamicProperties(), CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); + + assertEquals(configurator.getIgnoreFileOverride(), "/path/to/override/.swagger-codegen-ignore"); } @SuppressWarnings("unused") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java index f53ac5e0626..37b37ba0b8f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -50,6 +50,13 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setGeneratePropertyChanged(true); times = 1; + clientCodegen.setNonPublicApi(true); + times = 1; + clientCodegen.setInterfacePrefix("X"); + times = 1; + clientCodegen.setAllowUnicodeIdentifiers(Boolean.valueOf(CSharpClientOptionsProvider.ALLOW_UNICODE_IDENTIFIERS_VALUE)); + times = 1; + }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/elixir/ElixirClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/elixir/ElixirClientOptionsTest.java new file mode 100644 index 00000000000..edeab0eb284 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/elixir/ElixirClientOptionsTest.java @@ -0,0 +1,31 @@ +package io.swagger.codegen.elixir; + +import io.swagger.codegen.AbstractOptionsTest; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.languages.ElixirClientCodegen; +import io.swagger.codegen.options.ElixirClientOptionsProvider; +import mockit.Expectations; +import mockit.Tested; + +public class ElixirClientOptionsTest extends AbstractOptionsTest { + + @Tested + private ElixirClientCodegen clientCodegen; + + public ElixirClientOptionsTest() { + super(new ElixirClientOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + // TODO + }}; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java index ec1bc951f38..a4a13ecbcbc 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaClientOptionsTest.java @@ -46,6 +46,24 @@ public class JavaClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setArtifactVersion(JavaClientOptionsProvider.ARTIFACT_VERSION_VALUE); times = 1; + clientCodegen.setArtifactUrl(JavaClientOptionsProvider.ARTIFACT_URL_VALUE); + times = 1; + clientCodegen.setArtifactDescription(JavaClientOptionsProvider.ARTIFACT_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setScmConnection(JavaClientOptionsProvider.SCM_CONNECTION_VALUE); + times = 1; + clientCodegen.setScmDeveloperConnection(JavaClientOptionsProvider.SCM_DEVELOPER_CONNECTION_VALUE); + times = 1; + clientCodegen.setScmUrl(JavaClientOptionsProvider.SCM_URL_VALUE); + times = 1; + clientCodegen.setDeveloperName(JavaClientOptionsProvider.DEVELOPER_NAME_VALUE); + times = 1; + clientCodegen.setDeveloperEmail(JavaClientOptionsProvider.DEVELOPER_EMAIL_VALUE); + times = 1; + clientCodegen.setDeveloperOrganization(JavaClientOptionsProvider.DEVELOPER_ORGANIZATION_VALUE); + times = 1; + clientCodegen.setDeveloperOrganizationUrl(JavaClientOptionsProvider.DEVELOPER_ORGANIZATION_URL_VALUE); + times = 1; clientCodegen.setLicenseName(JavaClientOptionsProvider.LICENSE_NAME_VALUE); times = 1; clientCodegen.setLicenseUrl(JavaClientOptionsProvider.LICENSE_URL_VALUE); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java index 0aedbdf89e0..f8d38149ce1 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/javascript/JavaScriptModelEnumTest.java @@ -95,7 +95,7 @@ public class JavaScriptModelEnumTest { } @Test(description = "test enum array model") - public void enumArrayMdoelTest() { + public void enumArrayModelTest() { final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); final DefaultCodegen codegen = new JavascriptClientCodegen(); final Model definition = model.getDefinitions().get("EnumArrays"); @@ -126,7 +126,7 @@ public class JavaScriptModelEnumTest { } @Test(description = "test enum model for values (numeric, string, etc)") - public void enumMdoelValueTest() { + public void enumModelValueTest() { final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml"); final DefaultCodegen codegen = new JavascriptClientCodegen(); final Model definition = model.getDefinitions().get("Enum_Test"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java index 8d74b035901..d76ee89416f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JavaResteasyServerOptionsTest.java @@ -59,6 +59,8 @@ public class JavaResteasyServerOptionsTest extends AbstractOptionsTest { clientCodegen.setGenerateJbossDeploymentDescriptor( Boolean.valueOf(JavaResteasyServerOptionsProvider.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR)); + + clientCodegen.setUseBeanValidation(Boolean.valueOf(JavaResteasyServerOptionsProvider.USE_BEANVALIDATION)); times = 1; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java index 8c6c7149f9b..4ce6410eafd 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/jaxrs/JaxRSServerOptionsTest.java @@ -41,6 +41,24 @@ public class JaxRSServerOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setArtifactVersion(JaxRSServerOptionsProvider.ARTIFACT_VERSION_VALUE); times = 1; + clientCodegen.setArtifactUrl(JaxRSServerOptionsProvider.ARTIFACT_URL_VALUE); + times = 1; + clientCodegen.setArtifactDescription(JaxRSServerOptionsProvider.ARTIFACT_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setScmConnection(JaxRSServerOptionsProvider.SCM_CONNECTION_VALUE); + times = 1; + clientCodegen.setScmDeveloperConnection(JaxRSServerOptionsProvider.SCM_DEVELOPER_CONNECTION_VALUE); + times = 1; + clientCodegen.setScmUrl(JaxRSServerOptionsProvider.SCM_URL_VALUE); + times = 1; + clientCodegen.setDeveloperName(JaxRSServerOptionsProvider.DEVELOPER_NAME_VALUE); + times = 1; + clientCodegen.setDeveloperEmail(JaxRSServerOptionsProvider.DEVELOPER_EMAIL_VALUE); + times = 1; + clientCodegen.setDeveloperOrganization(JaxRSServerOptionsProvider.DEVELOPER_ORGANIZATION_VALUE); + times = 1; + clientCodegen.setDeveloperOrganizationUrl(JaxRSServerOptionsProvider.DEVELOPER_ORGANIZATION_URL_VALUE); + times = 1; clientCodegen.setSourceFolder(JaxRSServerOptionsProvider.SOURCE_FOLDER_VALUE); times = 1; clientCodegen.setLocalVariablePrefix(JaxRSServerOptionsProvider.LOCAL_PREFIX_VALUE); @@ -56,6 +74,8 @@ public class JaxRSServerOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setSupportJava6(false); times = 1; + clientCodegen.setUseBeanValidation(Boolean.valueOf(JaxRSServerOptionsProvider.USE_BEANVALIDATION)); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java index a1cc4aab2b9..658b2f7ecca 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/nodejs/NodeJSServerOptionsTest.java @@ -7,6 +7,9 @@ import io.swagger.codegen.options.NodeJSServerOptionsProvider; import mockit.Expectations; import mockit.Tested; +import org.testng.annotations.Test; + +import static org.testng.Assert.assertEquals; public class NodeJSServerOptionsTest extends AbstractOptionsTest { @@ -32,4 +35,27 @@ public class NodeJSServerOptionsTest extends AbstractOptionsTest { times = 1; }}; } + + + @Test + public void testCleanTitle() { + String dirtyTitle = "safe-title"; + String clean = dirtyTitle.replaceAll("[^a-zA-Z0-9]", "-") + .replaceAll("^[-]*", "") + .replaceAll("[-]*$", "") + .replaceAll("[-]{2,}", "-"); + + assertEquals(clean, "safe-title"); + } + + @Test + public void testDirtyTitleCleansing() { + String dirtyTitle = "_it's-$ooo//////////---_//dirty!!!!"; + String clean = dirtyTitle.replaceAll("[^a-zA-Z0-9]", "-") + .replaceAll("^[-]*", "") + .replaceAll("[-]*$", "") + .replaceAll("[-]{2,}", "-"); + + assertEquals(clean, "it-s-ooo-dirty"); + } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java index c9fd8bca97a..cf0142a9e0e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AkkaScalaClientOptionsProvider.java @@ -4,6 +4,8 @@ import io.swagger.codegen.CodegenConstants; import com.google.common.collect.ImmutableMap; +import com.sun.org.apache.bcel.internal.classfile.Code; + import java.util.Map; public class AkkaScalaClientOptionsProvider implements OptionsProvider { @@ -12,6 +14,7 @@ public class AkkaScalaClientOptionsProvider implements OptionsProvider { public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @Override public String getLanguage() { @@ -26,6 +29,7 @@ public class AkkaScalaClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java index 79e61844c8b..c17a567798e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AndroidClientOptionsProvider.java @@ -20,6 +20,7 @@ public class AndroidClientOptionsProvider implements OptionsProvider { public static final String ANDROID_MAVEN_GRADLE_PLUGIN_VALUE = "true"; public static final String LIBRARY_VALUE = "httpclient"; public static final String SERIALIZABLE_MODEL_VALUE = "false"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @Override public String getLanguage() { @@ -41,6 +42,7 @@ public class AndroidClientOptionsProvider implements OptionsProvider { .put(AndroidClientCodegen.USE_ANDROID_MAVEN_GRADLE_PLUGIN, ANDROID_MAVEN_GRADLE_PLUGIN_VALUE) .put(CodegenConstants.LIBRARY, LIBRARY_VALUE) .put(CodegenConstants.SERIALIZABLE_MODEL, SERIALIZABLE_MODEL_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java index aa09c1e4aec..9bf0d1d6ee6 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/AsyncScalaClientOptionsProvider.java @@ -12,6 +12,7 @@ public class AsyncScalaClientOptionsProvider implements OptionsProvider { public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @Override public String getLanguage() { @@ -26,6 +27,7 @@ public class AsyncScalaClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java new file mode 100644 index 00000000000..cd27b2f43dd --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/BashClientOptionsProvider.java @@ -0,0 +1,65 @@ +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.BashClientCodegen; + +import com.google.common.collect.ImmutableMap; + +import java.util.Map; + +public class BashClientOptionsProvider implements OptionsProvider { + + public static final String CURL_OPTIONS = "-k --tlsv1.2"; + public static final String PROCESS_MARKDOWN = "true"; + public static final String SCRIPT_NAME = "petstore-cli"; + public static final String GENERATE_BASH_COMPLETION = "true"; + public static final String GENERATE_ZSH_COMPLETION = "false"; + public static final String HOST_ENVIRONMENT_VARIABLE_NAME + = "PETSTORE_HOSTNAME"; + public static final String BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME + = "PETSTORE_BASIC_AUTH"; + public static final String APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME + = "PETSTORE_APIKEY"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE + = "false"; + + + @Override + public String getLanguage() { + return "bash"; + } + + @Override + public Map createOptions() { + + ImmutableMap.Builder builder + = new ImmutableMap.Builder(); + + return builder + .put(BashClientCodegen.CURL_OPTIONS, CURL_OPTIONS) + .put(BashClientCodegen.SCRIPT_NAME, SCRIPT_NAME) + .put(BashClientCodegen.PROCESS_MARKDOWN, PROCESS_MARKDOWN) + .put(BashClientCodegen.GENERATE_BASH_COMPLETION, + GENERATE_BASH_COMPLETION) + .put(BashClientCodegen.GENERATE_ZSH_COMPLETION, + GENERATE_ZSH_COMPLETION) + .put(BashClientCodegen.HOST_ENVIRONMENT_VARIABLE_NAME, + HOST_ENVIRONMENT_VARIABLE_NAME) + .put(BashClientCodegen.BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME, + BASIC_AUTH_ENVIRONMENT_VARIABLE_NAME) + .put(BashClientCodegen.APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME, + APIKEY_AUTH_ENVIRONMENT_VARIABLE_NAME) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false") + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "false") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) + .build(); + + } + + @Override + public boolean isServer() { + + return false; + + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java index a438a31e2b7..3e2f896bc95 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -11,7 +11,8 @@ public class CSharpClientOptionsProvider implements OptionsProvider { public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SOURCE_FOLDER_VALUE = "src_csharp"; public static final String PACKAGE_GUID_VALUE = "{894EAEBB-649A-498C-A735-10D0BD7B73E0}"; - + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { return "csharp"; @@ -35,6 +36,9 @@ public class CSharpClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, "true") .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") .put(CodegenConstants.GENERATE_PROPERTY_CHANGED, "true") + .put(CodegenConstants.NON_PUBLIC_API, "true") + .put(CodegenConstants.INTERFACE_PREFIX, "X") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java index 5560780eb96..4e2670f2653 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/DartClientOptionsProvider.java @@ -15,6 +15,8 @@ public class DartClientOptionsProvider implements OptionsProvider { public static final String PUB_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String PUB_DESCRIPTION_VALUE = "Swagger API client dart"; public static final String SOURCE_FOLDER_VALUE = "src"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -31,6 +33,7 @@ public class DartClientOptionsProvider implements OptionsProvider { .put(DartClientCodegen.PUB_VERSION, PUB_VERSION_VALUE) .put(DartClientCodegen.PUB_DESCRIPTION, PUB_DESCRIPTION_VALUE) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ElixirClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ElixirClientOptionsProvider.java new file mode 100644 index 00000000000..092fccc2e0a --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ElixirClientOptionsProvider.java @@ -0,0 +1,29 @@ +package io.swagger.codegen.options; + +import com.google.common.collect.ImmutableMap; +import io.swagger.codegen.CodegenConstants; + +import java.util.Map; + +public class ElixirClientOptionsProvider implements OptionsProvider { + + @Override + public String getLanguage() { + return "elixir"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "false") + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "false") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, "false") + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoServerOptionsProvider.java index 71e47537f45..d231a4ee3d9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/GoServerOptionsProvider.java @@ -9,6 +9,8 @@ import java.util.Map; public class GoServerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -20,6 +22,7 @@ public class GoServerOptionsProvider implements OptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/HaskellServantOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/HaskellServantOptionsProvider.java index cc4f7f3a9b3..1152a626b2b 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/HaskellServantOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/HaskellServantOptionsProvider.java @@ -11,6 +11,8 @@ public class HaskellServantOptionsProvider implements OptionsProvider { public static final String API_PACKAGE_VALUE = "Api"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -24,6 +26,7 @@ public class HaskellServantOptionsProvider implements OptionsProvider { .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFServerOptionsProvider.java index fa32252c0b0..22deb3daace 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaCXFServerOptionsProvider.java @@ -40,6 +40,10 @@ public class JavaCXFServerOptionsProvider extends JavaOptionsProvider { public static final String ADD_CONSUMES_PRODUCES_JSON = "true"; public static final String IMPL_FOLDER_VALUE = "src/main/java"; + + public static final String USE_ANNOTATED_BASE_PATH = "true"; + + public static final String GENERATE_NON_SPRING_APPLICATION = "true"; @Override public boolean isServer() { @@ -85,6 +89,10 @@ public class JavaCXFServerOptionsProvider extends JavaOptionsProvider { builder.put(JavaCXFServerCodegen.ADD_CONSUMES_PRODUCES_JSON, ADD_CONSUMES_PRODUCES_JSON); + builder.put(JavaCXFServerCodegen.USE_ANNOTATED_BASE_PATH, USE_ANNOTATED_BASE_PATH); + + builder.put(JavaCXFServerCodegen.GENERATE_NON_SPRING_APPLICATION, GENERATE_NON_SPRING_APPLICATION); + return builder.build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java index 9fe39cc95d3..eb60599435c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaOptionsProvider.java @@ -13,9 +13,18 @@ public class JavaOptionsProvider implements OptionsProvider { public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; public static final String LICENSE_NAME_VALUE = "Apache License, Version 2.0"; public static final String LICENSE_URL_VALUE = "http://www.apache.org/licenses/LICENSE-2.0"; + public static final String DEVELOPER_NAME_VALUE = "Swagger"; + public static final String DEVELOPER_EMAIL_VALUE = "apiteam@swagger.io"; + public static final String DEVELOPER_ORGANIZATION_VALUE = "Swagger"; + public static final String DEVELOPER_ORGANIZATION_URL_VALUE = "http://swagger.io"; + public static final String SCM_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + public static final String SCM_DEVELOPER_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + public static final String SCM_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; public static final String SORT_PARAMS_VALUE = "false"; public static final String GROUP_ID_VALUE = "io.swagger.test"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String ARTIFACT_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; + public static final String ARTIFACT_DESCRIPTION_VALUE = "Swagger Java Client Test"; public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; public static final String LOCAL_PREFIX_VALUE = "tst"; public static final String SERIALIZABLE_MODEL_VALUE = "false"; @@ -23,6 +32,8 @@ public class JavaOptionsProvider implements OptionsProvider { public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; //public static final String SUPPORT_JAVA6 = "true"; public static final String USE_BEANVALIDATION = "false"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + private ImmutableMap options; @@ -39,6 +50,15 @@ public class JavaOptionsProvider implements OptionsProvider { .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.ARTIFACT_URL, ARTIFACT_URL_VALUE) + .put(CodegenConstants.ARTIFACT_DESCRIPTION, ARTIFACT_DESCRIPTION_VALUE) + .put(CodegenConstants.SCM_CONNECTION, SCM_CONNECTION_VALUE) + .put(CodegenConstants.SCM_DEVELOPER_CONNECTION, SCM_DEVELOPER_CONNECTION_VALUE) + .put(CodegenConstants.SCM_URL, SCM_URL_VALUE) + .put(CodegenConstants.DEVELOPER_NAME, DEVELOPER_NAME_VALUE) + .put(CodegenConstants.DEVELOPER_EMAIL, DEVELOPER_EMAIL_VALUE) + .put(CodegenConstants.DEVELOPER_ORGANIZATION, DEVELOPER_ORGANIZATION_VALUE) + .put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, DEVELOPER_ORGANIZATION_URL_VALUE) .put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE) .put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) @@ -48,7 +68,8 @@ public class JavaOptionsProvider implements OptionsProvider { .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") .put(JavaClientCodegen.DATE_LIBRARY, "joda") .put("hideGenerationTimestamp", "true") - //.put("supportJava6", "true") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) + //.put("supportJava6", "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java index 769f759d95c..eae8a6dcccf 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaResteasyServerOptionsProvider.java @@ -6,6 +6,7 @@ import com.google.common.collect.ImmutableMap; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.languages.JavaCXFServerCodegen; +import io.swagger.codegen.languages.JavaResteasyServerCodegen; public class JavaResteasyServerOptionsProvider extends JavaOptionsProvider { @@ -13,6 +14,8 @@ public class JavaResteasyServerOptionsProvider extends JavaOptionsProvider { public static final String IMPL_FOLDER_VALUE = "src/main/java"; + public static final String USE_BEANVALIDATION = "true"; + @Override public boolean isServer() { return true; @@ -35,6 +38,7 @@ public class JavaResteasyServerOptionsProvider extends JavaOptionsProvider { builder.put("title", "Test title"); builder.put(JavaCXFServerCodegen.GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR, GENERATE_JBOSS_DEPLOYMENT_DESCRIPTOR); + builder.put(JavaResteasyServerCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION); return builder.build(); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java index 5b75f59b356..02f1f102ed4 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavaScriptOptionsProvider.java @@ -29,6 +29,8 @@ public class JavaScriptOptionsProvider implements OptionsProvider { public static final String USE_INHERITANCE_VALUE = "false"; public static final String EMIT_MODEL_METHODS_VALUE = "true"; public static final String EMIT_JS_DOC_VALUE = "false"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + private ImmutableMap options; @@ -59,6 +61,7 @@ public class JavaScriptOptionsProvider implements OptionsProvider { .put(JavascriptClientCodegen.EMIT_MODEL_METHODS, EMIT_MODEL_METHODS_VALUE) .put(JavascriptClientCodegen.EMIT_JS_DOC, EMIT_JS_DOC_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java index baf4cfb8537..4ca8cbb6110 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JavascriptClosureAnularClientOptionsProvider.java @@ -9,6 +9,8 @@ import java.util.Map; public class JavascriptClosureAnularClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -21,6 +23,7 @@ public class JavascriptClosureAnularClientOptionsProvider implements OptionsProv return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java index 57896db9ca6..3aeebceef90 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/JaxRSServerOptionsProvider.java @@ -2,6 +2,7 @@ package io.swagger.codegen.options; import com.google.common.collect.ImmutableMap; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.JavaCXFServerCodegen; import io.swagger.codegen.languages.JavaClientCodegen; import java.util.Map; @@ -14,6 +15,15 @@ public class JaxRSServerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String GROUP_ID_VALUE = "io.swagger.test"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String ARTIFACT_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; + public static final String ARTIFACT_DESCRIPTION_VALUE = "Swagger Java Client Test"; + public static final String DEVELOPER_NAME_VALUE = "Swagger"; + public static final String DEVELOPER_EMAIL_VALUE = "apiteam@swagger.io"; + public static final String DEVELOPER_ORGANIZATION_VALUE = "Swagger"; + public static final String DEVELOPER_ORGANIZATION_URL_VALUE = "http://swagger.io"; + public static final String SCM_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + public static final String SCM_DEVELOPER_CONNECTION_VALUE = "scm:git:git@github.com:swagger-api/swagger-codegen.git"; + public static final String SCM_URL_VALUE = "https://github.com/swagger-api/swagger-codegen"; public static final String LICENSE_NAME_VALUE = "Apache License, Version 2.0"; public static final String LICENSE_URL_VALUE = "http://www.apache.org/licenses/LICENSE-2.0"; public static final String SOURCE_FOLDER_VALUE = "src/main/java/test"; @@ -25,6 +35,9 @@ public class JaxRSServerOptionsProvider implements OptionsProvider { public static final String JODA_DATE_LIBRARY = "joda"; public static final String IMPL_FOLDER_VALUE = "src/main/java/impl"; public static final String JAXRS_DEFAULT_LIBRARY_VALUE = "jersey1"; + public static final String USE_BEANVALIDATION = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public boolean isServer() { @@ -51,6 +64,15 @@ public class JaxRSServerOptionsProvider implements OptionsProvider { .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.ARTIFACT_URL, ARTIFACT_URL_VALUE) + .put(CodegenConstants.ARTIFACT_DESCRIPTION, ARTIFACT_DESCRIPTION_VALUE) + .put(CodegenConstants.SCM_CONNECTION, SCM_CONNECTION_VALUE) + .put(CodegenConstants.SCM_DEVELOPER_CONNECTION, SCM_DEVELOPER_CONNECTION_VALUE) + .put(CodegenConstants.SCM_URL, SCM_URL_VALUE) + .put(CodegenConstants.DEVELOPER_NAME, DEVELOPER_NAME_VALUE) + .put(CodegenConstants.DEVELOPER_EMAIL, DEVELOPER_EMAIL_VALUE) + .put(CodegenConstants.DEVELOPER_ORGANIZATION, DEVELOPER_ORGANIZATION_VALUE) + .put(CodegenConstants.DEVELOPER_ORGANIZATION_URL, DEVELOPER_ORGANIZATION_URL_VALUE) .put(CodegenConstants.LICENSE_NAME, LICENSE_NAME_VALUE) .put(CodegenConstants.LICENSE_URL, LICENSE_URL_VALUE) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) @@ -60,7 +82,9 @@ public class JaxRSServerOptionsProvider implements OptionsProvider { .put(CodegenConstants.LIBRARY, JAXRS_DEFAULT_LIBRARY_VALUE) .put(CodegenConstants.SERIALIZE_BIG_DECIMAL_AS_STRING, "true") //.put(JavaClientCodegen.DATE_LIBRARY, "joda") - .put("hideGenerationTimestamp", "true"); + .put("hideGenerationTimestamp", "true") + .put(JavaCXFServerCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE); return builder.build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java index 6edc611b59e..eefe050e708 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/LumenServerOptionsProvider.java @@ -19,6 +19,8 @@ public class LumenServerOptionsProvider implements OptionsProvider { public static final String GIT_USER_ID_VALUE = "gitSwaggerPhp"; public static final String GIT_REPO_ID_VALUE = "git-swagger-php"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -39,6 +41,7 @@ public class LumenServerOptionsProvider implements OptionsProvider { .put(CodegenConstants.GIT_USER_ID, GIT_USER_ID_VALUE) .put(CodegenConstants.GIT_REPO_ID, GIT_REPO_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java index 77a374f648e..950e92a5a91 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NancyFXServerOptionsProvider.java @@ -1,21 +1,17 @@ package io.swagger.codegen.options; -import static io.swagger.codegen.CodegenConstants.PACKAGE_NAME; -import static io.swagger.codegen.CodegenConstants.PACKAGE_VERSION; -import static io.swagger.codegen.CodegenConstants.RETURN_ICOLLECTION; -import static io.swagger.codegen.CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG; -import static io.swagger.codegen.CodegenConstants.SOURCE_FOLDER; -import static io.swagger.codegen.CodegenConstants.USE_COLLECTION; -import static io.swagger.codegen.CodegenConstants.USE_DATETIME_OFFSET; - import java.util.Map; import com.google.common.collect.ImmutableMap; +import static io.swagger.codegen.CodegenConstants.*; + public class NancyFXServerOptionsProvider implements OptionsProvider { public static final String PACKAGE_NAME_VALUE = "swagger_server_nancyfx"; public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SOURCE_FOLDER_VALUE = "src_nancyfx"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -32,6 +28,9 @@ public class NancyFXServerOptionsProvider implements OptionsProvider { .put(USE_DATETIME_OFFSET, "true") .put(USE_COLLECTION, "false") .put(RETURN_ICOLLECTION, "false") + .put(INTERFACE_PREFIX, "X") + .put(ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) + .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java index e18704e2b54..992460d314c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/NodeJSServerOptionsProvider.java @@ -11,6 +11,8 @@ public class NodeJSServerOptionsProvider implements OptionsProvider { public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String GOOGLE_CLOUD_FUNCTIONS = "false"; public static final String EXPORTED_NAME = "exported"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -24,6 +26,7 @@ public class NodeJSServerOptionsProvider implements OptionsProvider { .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(NodeJSServerCodegen.GOOGLE_CLOUD_FUNCTIONS, GOOGLE_CLOUD_FUNCTIONS) .put(NodeJSServerCodegen.EXPORTED_NAME, EXPORTED_NAME) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java index 5ffe04bff2b..d1a0def86d3 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PerlClientOptionsProvider.java @@ -24,6 +24,7 @@ public class PerlClientOptionsProvider implements OptionsProvider { .put(PerlClientCodegen.MODULE_VERSION, MODULE_VERSION_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, "true") + .put("hideGenerationTimestamp", "true") .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java index 26cdacc98b2..5468f6379e5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/PhpClientOptionsProvider.java @@ -21,6 +21,8 @@ public class PhpClientOptionsProvider implements OptionsProvider { public static final String GIT_USER_ID_VALUE = "gitSwaggerPhp"; public static final String GIT_REPO_ID_VALUE = "git-swagger-client-php"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -44,6 +46,7 @@ public class PhpClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.GIT_REPO_ID, GIT_REPO_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Qt5CPPOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Qt5CPPOptionsProvider.java index 05f9f1f068c..1ec21310297 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Qt5CPPOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Qt5CPPOptionsProvider.java @@ -9,6 +9,8 @@ import java.util.Map; public class Qt5CPPOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -20,6 +22,7 @@ public class Qt5CPPOptionsProvider implements OptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java index 34a36534a31..d0e6b78e081 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java @@ -20,6 +20,8 @@ public class RubyClientOptionsProvider implements OptionsProvider { public static final String GEM_DESCRIPTION_VALUE = "description"; public static final String GEM_AUTHOR_VALUE = "foo"; public static final String GEM_AUTHOR_EMAIL_VALUE = "foo"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -42,6 +44,7 @@ public class RubyClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java index f8a22c031ba..468ce1ae8f7 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalaClientOptionsProvider.java @@ -13,6 +13,8 @@ public class ScalaClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String MODEL_PROPERTY_NAMING = "modelPropertyNaming"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -28,6 +30,7 @@ public class ScalaClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java index e36ed80bbd5..6498f242079 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/ScalatraServerOptionsProvider.java @@ -12,6 +12,8 @@ public class ScalatraServerOptionsProvider implements OptionsProvider { public static final String API_PACKAGE_VALUE = "apiPackage"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -26,6 +28,7 @@ public class ScalatraServerOptionsProvider implements OptionsProvider { .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SilexServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SilexServerOptionsProvider.java index ae6596923d2..3b859985d6c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SilexServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SilexServerOptionsProvider.java @@ -9,6 +9,7 @@ import java.util.Map; public class SilexServerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @Override public String getLanguage() { @@ -20,6 +21,7 @@ public class SilexServerOptionsProvider implements OptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SlimFrameworkServerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SlimFrameworkServerOptionsProvider.java index d7676725750..3b0e9fca0f5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SlimFrameworkServerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SlimFrameworkServerOptionsProvider.java @@ -9,6 +9,8 @@ import java.util.Map; public class SlimFrameworkServerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -20,6 +22,7 @@ public class SlimFrameworkServerOptionsProvider implements OptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java index de7caa0d6c7..3bad178c416 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SpringOptionsProvider.java @@ -1,45 +1,51 @@ -package io.swagger.codegen.options; - -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.languages.SpringCodegen; - -import java.util.HashMap; -import java.util.Map; - -public class SpringOptionsProvider extends JavaOptionsProvider { - public static final String TITLE = "swagger"; - public static final String CONFIG_PACKAGE_VALUE = "configPackage"; - public static final String BASE_PACKAGE_VALUE = "basePackage"; - public static final String LIBRARY_VALUE = "spring-mvc"; //FIXME hidding value from super class - public static final String INTERFACE_ONLY = "true"; - public static final String SINGLE_CONTENT_TYPES = "true"; - public static final String JAVA_8 = "true"; - public static final String ASYNC = "true"; - public static final String RESPONSE_WRAPPER = "Callable"; - - @Override - public String getLanguage() { - return "spring"; - } - - @Override - public Map createOptions() { - Map options = new HashMap(super.createOptions()); - options.put(SpringCodegen.TITLE, TITLE); - options.put(SpringCodegen.CONFIG_PACKAGE, CONFIG_PACKAGE_VALUE); - options.put(SpringCodegen.BASE_PACKAGE, BASE_PACKAGE_VALUE); - options.put(CodegenConstants.LIBRARY, LIBRARY_VALUE); - options.put(SpringCodegen.INTERFACE_ONLY, INTERFACE_ONLY); - options.put(SpringCodegen.SINGLE_CONTENT_TYPES, SINGLE_CONTENT_TYPES); - options.put(SpringCodegen.JAVA_8, JAVA_8); - options.put(SpringCodegen.ASYNC, ASYNC); - options.put(SpringCodegen.RESPONSE_WRAPPER, RESPONSE_WRAPPER); - - return options; - } - - @Override - public boolean isServer() { - return true; - } -} +package io.swagger.codegen.options; + +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.SpringCodegen; + +import java.util.HashMap; +import java.util.Map; + +public class SpringOptionsProvider extends JavaOptionsProvider { + public static final String TITLE = "swagger"; + public static final String CONFIG_PACKAGE_VALUE = "configPackage"; + public static final String BASE_PACKAGE_VALUE = "basePackage"; + public static final String LIBRARY_VALUE = "spring-mvc"; //FIXME hidding value from super class + public static final String INTERFACE_ONLY = "true"; + public static final String DELEGATE_PATTERN = "true"; + public static final String SINGLE_CONTENT_TYPES = "true"; + public static final String JAVA_8 = "true"; + public static final String ASYNC = "true"; + public static final String RESPONSE_WRAPPER = "Callable"; + public static final String USE_TAGS = "useTags"; + public static final String USE_BEANVALIDATION = "false"; + + @Override + public String getLanguage() { + return "spring"; + } + + @Override + public Map createOptions() { + Map options = new HashMap(super.createOptions()); + options.put(SpringCodegen.TITLE, TITLE); + options.put(SpringCodegen.CONFIG_PACKAGE, CONFIG_PACKAGE_VALUE); + options.put(SpringCodegen.BASE_PACKAGE, BASE_PACKAGE_VALUE); + options.put(CodegenConstants.LIBRARY, LIBRARY_VALUE); + options.put(SpringCodegen.INTERFACE_ONLY, INTERFACE_ONLY); + options.put(SpringCodegen.DELEGATE_PATTERN, DELEGATE_PATTERN); + options.put(SpringCodegen.SINGLE_CONTENT_TYPES, SINGLE_CONTENT_TYPES); + options.put(SpringCodegen.JAVA_8, JAVA_8); + options.put(SpringCodegen.ASYNC, ASYNC); + options.put(SpringCodegen.RESPONSE_WRAPPER, RESPONSE_WRAPPER); + options.put(SpringCodegen.USE_TAGS, USE_TAGS); + options.put(SpringCodegen.USE_BEANVALIDATION, USE_BEANVALIDATION); + + return options; + } + + @Override + public boolean isServer() { + return true; + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticDocOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticDocOptionsProvider.java index d5d14238ec7..891a9a94323 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticDocOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticDocOptionsProvider.java @@ -13,6 +13,8 @@ public class StaticDocOptionsProvider implements OptionsProvider { public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; public static final String GROUP_ID_VALUE = "io.swagger.test"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -28,6 +30,7 @@ public class StaticDocOptionsProvider implements OptionsProvider { .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java index 899eed6f4b7..423c13f8a4d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/StaticHtmlOptionsProvider.java @@ -13,6 +13,8 @@ public class StaticHtmlOptionsProvider implements OptionsProvider { public static final String INVOKER_PACKAGE_VALUE = "io.swagger.client.test"; public static final String GROUP_ID_VALUE = "io.swagger.test"; public static final String ARTIFACT_VERSION_VALUE = "1.0.0-SNAPSHOT"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -34,6 +36,7 @@ public class StaticHtmlOptionsProvider implements OptionsProvider { .put(CodegenConstants.GROUP_ID, GROUP_ID_VALUE) .put(CodegenConstants.ARTIFACT_ID, ARTIFACT_ID_VALUE) .put(CodegenConstants.ARTIFACT_VERSION, ARTIFACT_VERSION_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerOptionsProvider.java index e97860e83ab..362c598adef 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerOptionsProvider.java @@ -9,6 +9,8 @@ import java.util.Map; public class SwaggerOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -20,6 +22,7 @@ public class SwaggerOptionsProvider implements OptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java index 3d73e681c8c..860a0ef15f1 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwaggerYamlOptionsProvider.java @@ -9,6 +9,7 @@ import java.util.Map; public class SwaggerYamlOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @Override public String getLanguage() { @@ -21,6 +22,7 @@ public class SwaggerYamlOptionsProvider implements OptionsProvider { return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put("outputFile", "swagger.yaml") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Swift3OptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Swift3OptionsProvider.java index 475239022f4..4e4bed0f826 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Swift3OptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/Swift3OptionsProvider.java @@ -26,6 +26,7 @@ public class Swift3OptionsProvider implements OptionsProvider { public static final String POD_SCREENSHOTS_VALUE = "podScreenshots"; public static final String POD_DOCUMENTATION_URL_VALUE = "podDocumentationURL"; public static final String SWIFT_USE_API_NAMESPACE_VALUE = "swiftUseApiNamespace"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @Override public String getLanguage() { @@ -53,6 +54,7 @@ public class Swift3OptionsProvider implements OptionsProvider { .put(Swift3Codegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE) .put(Swift3Codegen.SWIFT_USE_API_NAMESPACE, SWIFT_USE_API_NAMESPACE_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java index b79ecfb351d..8229e97aee8 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/SwiftOptionsProvider.java @@ -26,6 +26,8 @@ public class SwiftOptionsProvider implements OptionsProvider { public static final String POD_SCREENSHOTS_VALUE = "podScreenshots"; public static final String POD_DOCUMENTATION_URL_VALUE = "podDocumentationURL"; public static final String SWIFT_USE_API_NAMESPACE_VALUE = "swiftUseApiNamespace"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -53,6 +55,7 @@ public class SwiftOptionsProvider implements OptionsProvider { .put(SwiftCodegen.POD_DOCUMENTATION_URL, POD_DOCUMENTATION_URL_VALUE) .put(SwiftCodegen.SWIFT_USE_API_NAMESPACE, SWIFT_USE_API_NAMESPACE_VALUE) .put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true") + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TizenClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TizenClientOptionsProvider.java index ff8659627f4..0d062dba84c 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TizenClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TizenClientOptionsProvider.java @@ -9,6 +9,8 @@ import java.util.Map; public class TizenClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -20,6 +22,7 @@ public class TizenClientOptionsProvider implements OptionsProvider { ImmutableMap.Builder builder = new ImmutableMap.Builder(); return builder.put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngular2ClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngular2ClientOptionsProvider.java index 8b8077edfee..b454130ca74 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngular2ClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngular2ClientOptionsProvider.java @@ -15,6 +15,8 @@ public class TypeScriptAngular2ClientOptionsProvider implements OptionsProvider 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"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -32,6 +34,7 @@ public class TypeScriptAngular2ClientOptionsProvider implements OptionsProvider .put(TypeScriptAngular2ClientCodegen.NPM_VERSION, NMP_VERSION) .put(TypeScriptAngular2ClientCodegen.SNAPSHOT, Boolean.FALSE.toString()) .put(TypeScriptAngular2ClientCodegen.NPM_REPOSITORY, NPM_REPOSITORY) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java index 4fe0820d34e..2c3fd50387f 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptAngularClientOptionsProvider.java @@ -11,6 +11,8 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -24,6 +26,7 @@ public class TypeScriptAngularClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.SUPPORTS_ES6, SUPPORTS_ES6_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java index cc5be4fe456..f7c222c1e06 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java @@ -13,6 +13,8 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; private static final String NMP_NAME = "npmName"; private static final String NMP_VERSION = "1.0.0"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { @@ -28,6 +30,7 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.SUPPORTS_ES6, String.valueOf(SUPPORTS_ES6_VALUE)) .put(TypeScriptFetchClientCodegen.NPM_NAME, NMP_NAME) .put(TypeScriptFetchClientCodegen.NPM_VERSION, NMP_VERSION) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java index 61868ef6faf..a3e98c64f9e 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptNodeClientOptionsProvider.java @@ -18,6 +18,8 @@ public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { private static final String NMP_VERSION = "1.1.2"; private static final String NPM_REPOSITORY = "https://registry.npmjs.org"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + @Override public String getLanguage() { return "typescript-node"; @@ -34,6 +36,7 @@ public class TypeScriptNodeClientOptionsProvider implements OptionsProvider { .put(TypeScriptAngular2ClientCodegen.NPM_VERSION, NMP_VERSION) .put(TypeScriptAngular2ClientCodegen.SNAPSHOT, Boolean.FALSE.toString()) .put(TypeScriptAngular2ClientCodegen.NPM_REPOSITORY, NPM_REPOSITORY) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .build(); } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientCodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientCodegenTest.java index 40b7e8dc55b..bf69f043b54 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientCodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientCodegenTest.java @@ -49,8 +49,7 @@ public class RubyClientCodegenTest { ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); DefaultGenerator generator = new DefaultGenerator(); - generator.opts(clientOptInput); - List files = generator.generate(); + List files = generator.opts(clientOptInput).generate(); boolean apiFileGenerated = false; for (File file : files) { if (file.getName().equals("default_api.rb")) { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java index 4084c0a80e9..b69f958aef5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/spring/SpringOptionsTest.java @@ -1,72 +1,78 @@ -package io.swagger.codegen.spring; - -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.java.JavaClientOptionsTest; -import io.swagger.codegen.languages.SpringCodegen; -import io.swagger.codegen.options.SpringOptionsProvider; - -import mockit.Expectations; -import mockit.Tested; - -public class SpringOptionsTest extends JavaClientOptionsTest { - - @Tested - private SpringCodegen clientCodegen; - - public SpringOptionsTest() { - super(new SpringOptionsProvider()); - } - - @Override - protected CodegenConfig getCodegenConfig() { - return clientCodegen; - } - - @SuppressWarnings("unused") - @Override - protected void setExpectations() { - new Expectations(clientCodegen) {{ - clientCodegen.setModelPackage(SpringOptionsProvider.MODEL_PACKAGE_VALUE); - times = 1; - clientCodegen.setApiPackage(SpringOptionsProvider.API_PACKAGE_VALUE); - times = 1; - clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SpringOptionsProvider.SORT_PARAMS_VALUE)); - times = 1; - clientCodegen.setInvokerPackage(SpringOptionsProvider.INVOKER_PACKAGE_VALUE); - times = 1; - clientCodegen.setGroupId(SpringOptionsProvider.GROUP_ID_VALUE); - times = 1; - clientCodegen.setArtifactId(SpringOptionsProvider.ARTIFACT_ID_VALUE); - times = 1; - clientCodegen.setArtifactVersion(SpringOptionsProvider.ARTIFACT_VERSION_VALUE); - times = 1; - clientCodegen.setSourceFolder(SpringOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.setLocalVariablePrefix(SpringOptionsProvider.LOCAL_PREFIX_VALUE); - times = 1; - clientCodegen.setSerializableModel(Boolean.valueOf(SpringOptionsProvider.SERIALIZABLE_MODEL_VALUE)); - times = 1; - clientCodegen.setLibrary(SpringOptionsProvider.LIBRARY_VALUE); - times = 1; - clientCodegen.setFullJavaUtil(Boolean.valueOf(SpringOptionsProvider.FULL_JAVA_UTIL_VALUE)); - times = 1; - clientCodegen.setTitle(SpringOptionsProvider.TITLE); - times = 1; - clientCodegen.setConfigPackage(SpringOptionsProvider.CONFIG_PACKAGE_VALUE); - times = 1; - clientCodegen.setBasePackage(SpringOptionsProvider.BASE_PACKAGE_VALUE); - times = 1; - clientCodegen.setInterfaceOnly(Boolean.valueOf(SpringOptionsProvider.INTERFACE_ONLY)); - times = 1; - clientCodegen.setSingleContentTypes(Boolean.valueOf(SpringOptionsProvider.SINGLE_CONTENT_TYPES)); - times = 1; - clientCodegen.setJava8(Boolean.valueOf(SpringOptionsProvider.JAVA_8)); - times = 1; - clientCodegen.setAsync(Boolean.valueOf(SpringOptionsProvider.ASYNC)); - times = 1; - clientCodegen.setResponseWrapper(SpringOptionsProvider.RESPONSE_WRAPPER); - times = 1; - - }}; - } -} +package io.swagger.codegen.spring; + +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.java.JavaClientOptionsTest; +import io.swagger.codegen.languages.SpringCodegen; +import io.swagger.codegen.options.SpringOptionsProvider; + +import mockit.Expectations; +import mockit.Tested; + +public class SpringOptionsTest extends JavaClientOptionsTest { + + @Tested + private SpringCodegen clientCodegen; + + public SpringOptionsTest() { + super(new SpringOptionsProvider()); + } + + @Override + protected CodegenConfig getCodegenConfig() { + return clientCodegen; + } + + @SuppressWarnings("unused") + @Override + protected void setExpectations() { + new Expectations(clientCodegen) {{ + clientCodegen.setModelPackage(SpringOptionsProvider.MODEL_PACKAGE_VALUE); + times = 1; + clientCodegen.setApiPackage(SpringOptionsProvider.API_PACKAGE_VALUE); + times = 1; + clientCodegen.setSortParamsByRequiredFlag(Boolean.valueOf(SpringOptionsProvider.SORT_PARAMS_VALUE)); + times = 1; + clientCodegen.setInvokerPackage(SpringOptionsProvider.INVOKER_PACKAGE_VALUE); + times = 1; + clientCodegen.setGroupId(SpringOptionsProvider.GROUP_ID_VALUE); + times = 1; + clientCodegen.setArtifactId(SpringOptionsProvider.ARTIFACT_ID_VALUE); + times = 1; + clientCodegen.setArtifactVersion(SpringOptionsProvider.ARTIFACT_VERSION_VALUE); + times = 1; + clientCodegen.setSourceFolder(SpringOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.setLocalVariablePrefix(SpringOptionsProvider.LOCAL_PREFIX_VALUE); + times = 1; + clientCodegen.setSerializableModel(Boolean.valueOf(SpringOptionsProvider.SERIALIZABLE_MODEL_VALUE)); + times = 1; + clientCodegen.setLibrary(SpringOptionsProvider.LIBRARY_VALUE); + times = 1; + clientCodegen.setFullJavaUtil(Boolean.valueOf(SpringOptionsProvider.FULL_JAVA_UTIL_VALUE)); + times = 1; + clientCodegen.setTitle(SpringOptionsProvider.TITLE); + times = 1; + clientCodegen.setConfigPackage(SpringOptionsProvider.CONFIG_PACKAGE_VALUE); + times = 1; + clientCodegen.setBasePackage(SpringOptionsProvider.BASE_PACKAGE_VALUE); + times = 1; + clientCodegen.setInterfaceOnly(Boolean.valueOf(SpringOptionsProvider.INTERFACE_ONLY)); + times = 1; + clientCodegen.setDelegatePattern(Boolean.valueOf(SpringOptionsProvider.DELEGATE_PATTERN)); + times = 1; + clientCodegen.setSingleContentTypes(Boolean.valueOf(SpringOptionsProvider.SINGLE_CONTENT_TYPES)); + times = 1; + clientCodegen.setJava8(Boolean.valueOf(SpringOptionsProvider.JAVA_8)); + times = 1; + clientCodegen.setAsync(Boolean.valueOf(SpringOptionsProvider.ASYNC)); + times = 1; + clientCodegen.setResponseWrapper(SpringOptionsProvider.RESPONSE_WRAPPER); + times = 1; + clientCodegen.setUseTags(Boolean.valueOf(SpringOptionsProvider.USE_TAGS)); + times = 1; + clientCodegen.setUseBeanValidation(Boolean.valueOf(SpringOptionsProvider.USE_BEANVALIDATION)); + times = 1; + + }}; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java index b7dacc22357..438d9c8c488 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescript/typescriptangular/TypeScriptAngularModelTest.java @@ -118,10 +118,10 @@ public class TypeScriptAngularModelTest { final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.datatype, "Children"); + Assert.assertEquals(property1.datatype, "models.Children"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.defaultValue, "null"); - Assert.assertEquals(property1.baseType, "Children"); + Assert.assertEquals(property1.baseType, "models.Children"); Assert.assertFalse(property1.required); Assert.assertTrue(property1.isNotContainer); } @@ -142,8 +142,8 @@ public class TypeScriptAngularModelTest { final CodegenProperty property1 = cm.vars.get(0); Assert.assertEquals(property1.baseName, "children"); - Assert.assertEquals(property1.complexType, "Children"); - Assert.assertEquals(property1.datatype, "Array"); + Assert.assertEquals(property1.complexType, "models.Children"); + Assert.assertEquals(property1.datatype, "Array"); Assert.assertEquals(property1.name, "children"); Assert.assertEquals(property1.baseType, "Array"); Assert.assertFalse(property1.required); @@ -177,6 +177,6 @@ public class TypeScriptAngularModelTest { Assert.assertEquals(cm.description, "a map model"); Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.imports.size(), 1); - Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("models.Children")).size(), 1); } } diff --git a/modules/swagger-codegen/src/test/resources/2_0/bash-config.json b/modules/swagger-codegen/src/test/resources/2_0/bash-config.json new file mode 100644 index 00000000000..a95e6b41733 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/bash-config.json @@ -0,0 +1,10 @@ +{ + "processMarkdown": true, + "curlOptions": "-sS --tlsv1.2", + "scriptName": "petstore-cli", + "generateBashCompletion": true, + "generateZshCompletion": true, + "hostEnvironmentVariable": "PETSTORE_HOST", + "basicAuthEnvironmentVariable": "PETSTORE_BASIC_AUTH", + "apiKeyAuthEnvironmentVariable": "PETSTORE_API_KEY" +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-bash.json b/modules/swagger-codegen/src/test/resources/2_0/petstore-bash.json new file mode 100644 index 00000000000..b58cd694d4e --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-bash.json @@ -0,0 +1,1056 @@ +{ + "swagger":"2.0", + "info":{ + "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.", + "version":"1.0.0", + "title":"Swagger Petstore", + "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" + } + }, + "host":"petstore.swagger.io", + "basePath":"/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" + } + } + ], + "schemes":[ + "http" + ], + "paths":{ + "/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":"body", + "description":"Pet object that needs to be added to the store", + "required":true, + "schema":{ + "$ref":"#/definitions/Pet" + } + } + ], + "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 added to 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", + "x-bash-codegen-description": "Multiple status `values` can be provided with comma separated strings", + "description": "Multiple status values can be provided with comma separated strings", + "operationId":"findPetsByStatus", + "produces":[ + "application/xml", + "application/json" + ], + "x-code-samples":[ + { + "lang": "Shell", + "source": "petstore-cli findPetsByStatus status=available" + } + ], + "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":"multi" + } + ], + "responses":{ + "200":{ + "description":"successful operation", + "schema":{ + "type":"array", + "items":{ + "$ref":"#/definitions/Pet" + } + } + }, + "400":{ + "description":"Invalid status value" + } + }, + "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", + "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/{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 ID supplied" + }, + "404":{ + "description":"Pet not found" + } + }, + "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 >= 1 and <= 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":10.0, + "minimum":1.0, + "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 positive integer value. Negative or non-integer values 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":"integer", + "minimum":1.0, + "format":"int64" + } + ], + "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 token 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 updated", + "required":true, + "type":"string" + }, + { + "in":"body", + "name":"body", + "description":"Updated user object", + "required":true, + "schema":{ + "$ref":"#/definitions/User" + } + } + ], + "responses":{ + "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/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":{ + "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", + "format":"int32", + "description":"User Status" + } + }, + "xml":{ + "name":"User" + } + }, + "Tag":{ + "type":"object", + "properties":{ + "id":{ + "type":"integer", + "format":"int64" + }, + "name":{ + "type":"string" + } + }, + "xml":{ + "name":"Tag" + } + }, + "Pet":{ + "type":"object", + "required":[ + "name", + "photoUrls" + ], + "example": { + "name": "lucky", + "photoUrls": [ + "http://example.com/lucky1.jpg" + ] + }, + "properties":{ + "id":{ + "type":"integer", + "format":"int64" + }, + "category":{ + "$ref":"#/definitions/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":"#/definitions/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" + } + } + } + }, + "externalDocs":{ + "description":"Find out more about Swagger", + "url":"http://swagger.io" + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index 793cb68d79b..02e608f1d5a 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1,16 +1,16 @@ swagger: '2.0' info: description: "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\" - version: 1.0.0 - title: Swagger Petstore + version: 1.0.0 + title: Swagger Petstore termsOfService: 'http://swagger.io/terms/' contact: - email: apiteam@swagger.io + email: apiteam@swagger.io license: - name: Apache 2.0 + name: Apache 2.0 url: 'http://www.apache.org/licenses/LICENSE-2.0.html' -host: petstore.swagger.io -basePath: /v2 +host: petstore.swagger.io +basePath: /v2 tags: - name: pet description: Everything about your Pets @@ -367,7 +367,6 @@ paths: description: ID of the order that needs to be deleted required: true type: string - minimum: 1 responses: '400': description: Invalid ID supplied @@ -634,7 +633,7 @@ paths: - _abc - '-efg' - (xyz) - in: formData + in: formData description: Form parameter enum test (string) - name: enum_header_string_array type: array @@ -644,7 +643,7 @@ paths: enum: - '>' - '$' - in: header + in: header description: Header parameter enum test (string array) - name: enum_header_string type: string @@ -656,7 +655,7 @@ paths: in: header description: Header parameter enum test (string) - name: enum_query_string_array - type: array + type: array items: type: string default: '$' @@ -672,11 +671,11 @@ paths: - _abc - '-efg' - (xyz) - in: query + in: query description: Query parameter enum test (string) - name: enum_query_integer type: integer - format: int32 + format: int32 enum: - 1 - -2 @@ -684,7 +683,7 @@ paths: description: Query parameter enum test (double) - name: enum_query_double type: number - format: double + format: double enum: - 1.1 - -1.2 @@ -697,7 +696,7 @@ paths: description: Not found post: tags: - - fake + - fake summary: | Fake endpoint for testing various parameters 假端點 @@ -1069,7 +1068,7 @@ definitions: format: date-time uuid: type: string - format: uuid + format: uuid password: type: string format: password @@ -1090,6 +1089,7 @@ definitions: enum: - UPPER - lower + - '' enum_integer: type: integer format: int32 @@ -1126,7 +1126,7 @@ definitions: dateTime: type: string format: date-time - map: + map: type: object additionalProperties: $ref: '#/definitions/Animal' @@ -1157,6 +1157,23 @@ definitions: foo: type: string readOnly: true + Capitalization: + type: object + properties: + smallCamel: + type: string + CapitalCamel: + type: string + small_Snake: + type: string + Capital_Snake: + type: string + SCA_ETH_Flow_Points: + type: string + ATT_NAME: + description: > + Name of the pet + type: string MapTest: type: object properties: @@ -1165,14 +1182,14 @@ definitions: additionalProperties: type: object additionalProperties: - type: string + type: string # comment out the following (map of map of enum) as many language not yet support this #map_map_of_enum: # type: object # additionalProperties: # type: object # additionalProperties: - # type: string + # type: string # enum: # - UPPER # - lower @@ -1240,7 +1257,7 @@ definitions: type: string enum: - ">=" - - "$" + - "$" array_enum: type: array items: diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml index cd10223ba04..e3ba184ea57 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.yaml @@ -367,7 +367,6 @@ paths: description: ID of the order that needs to be deleted required: true type: string - minimum: 1 responses: '400': description: Invalid ID supplied diff --git a/modules/swagger-codegen/src/test/resources/sampleConfig.json b/modules/swagger-codegen/src/test/resources/sampleConfig.json index 373665877c4..5c147400d8f 100644 --- a/modules/swagger-codegen/src/test/resources/sampleConfig.json +++ b/modules/swagger-codegen/src/test/resources/sampleConfig.json @@ -13,6 +13,7 @@ "artifactId" : "awesome-api", "artifactVersion" : "1.2.3", "library" : "jersey2", + "ignoreFileOverride": "/path/to/override/.swagger-codegen-ignore", "systemProperties" : { "systemProp1" : "value1" }, diff --git a/modules/swagger-generator/Dockerfile b/modules/swagger-generator/Dockerfile index dc31cbd965e..0360aa66ce0 100644 --- a/modules/swagger-generator/Dockerfile +++ b/modules/swagger-generator/Dockerfile @@ -1,12 +1,13 @@ -FROM java:8-jdk +FROM java:8-jre-alpine WORKDIR /generator + COPY target/lib/jetty-runner* /generator/jetty-runner.jar COPY target/*.war /generator/swagger-generator.war ENV GENERATOR_HOST=https://generator.swaggerhub.com/api/swagger.json -RUN apt-get update EXPOSE 8080 + CMD ["java", "-jar", "/generator/jetty-runner.jar", "/generator/swagger-generator.war"] diff --git a/pom.xml b/pom.xml index 11fce525f74..4e88549b0e2 100644 --- a/pom.xml +++ b/pom.xml @@ -314,6 +314,18 @@ samples/client/petstore/android/volley + + bash-client + + + env + java + + + + samples/client/petstore/bash + + clojure-client @@ -748,6 +760,7 @@ samples/client/petstore/ruby samples/client/petstore/android/volley + samples/client/petstore/bash samples/client/petstore/clojure samples/client/petstore/go samples/client/petstore/java/feign @@ -850,7 +863,7 @@ - 1.0.25 + 1.0.26-SNAPSHOT 2.11.1 2.3.4 1.5.12 diff --git a/run-in-docker.sh b/run-in-docker.sh index 39a7601dd03..99581115871 100755 --- a/run-in-docker.sh +++ b/run-in-docker.sh @@ -1,34 +1,16 @@ #!/bin/bash -set -e -cd "$(dirname $BASH_SOURCE)" +set -exo pipefail -maven_cache_repo="$HOME/.m2/repository" -myname="$(basename $BASH_SOURCE)" +cd "$(dirname ${BASH_SOURCE})" -if [ "$1" = "mvn" ]; then - cmd="$1" - shift - args="$@" -else - jar="modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - - # Check if project is built - if [ ! -f "$jar" ]; then - echo "ERROR File not found: $jar" - echo "ERROR Did you forget to './$myname mvn package'?" - exit 1 - fi - - cmd="java -jar /gen/$jar" - args="$@" -fi +maven_cache_repo="${HOME}/.m2/repository" -mkdir -p "$maven_cache_repo" +mkdir -p "${maven_cache_repo}" -set -x - -docker run -it \ +docker run --rm -it \ -w /gen \ + -e GEN_DIR=/gen \ -v "${PWD}:/gen" \ -v "${maven_cache_repo}:/root/.m2/repository" \ - maven:3-jdk-7 $cmd $args + --entrypoint /gen/docker-entrypoint.sh \ + maven:3-jdk-7 "$@" diff --git a/samples/client/petstore-security-test/java/okhttp-gson/pom.xml b/samples/client/petstore-security-test/java/okhttp-gson/pom.xml index d6ce1873282..be07768b92e 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/pom.xml +++ b/samples/client/petstore-security-test/java/okhttp-gson/pom.xml @@ -15,6 +15,14 @@ 2.2.0 + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html *_/ ' \" =end -- \\r\\n \\n \\r + repo + + + @@ -129,7 +137,6 @@ joda-time ${jodatime-version} - junit @@ -150,4 +157,4 @@ 4.12 UTF-8 - \ No newline at end of file + diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index 4ff3984453d..43b8be5d60c 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -170,14 +170,15 @@ class DateAdapter implements JsonSerializer, JsonDeserializer { */ class DateTimeTypeAdapter extends TypeAdapter { - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { - out.value(formatter.print(date)); + out.value(printFormatter.print(date)); } } @@ -189,7 +190,7 @@ class DateTimeTypeAdapter extends TypeAdapter { return null; default: String date = in.nextString(); - return formatter.parseDateTime(date); + return parseFormatter.parseDateTime(date); } } } diff --git a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index 0d0407f94b3..8a4e08dc244 100644 --- a/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore-security-test/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -9,146 +9,159 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testCodeInjectEndRnNR */ - private com.squareup.okhttp.Call testCodeInjectEndRnNRCall(String testCodeInjectEndRnNR, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (testCodeInjectEndRnNR != null) - localVarFormParams.put("test code inject */ ' " =end -- \r\n \n \r", testCodeInjectEndRnNR); - - final String[] localVarAccepts = { - "application/json", "*_/ ' =end -- " - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "*_/ ' =end -- " - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - /** - * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r - * - * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testCodeInjectEndRnNR(String testCodeInjectEndRnNR) throws ApiException { - testCodeInjectEndRnNRWithHttpInfo(testCodeInjectEndRnNR); - } - - /** - * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r - * - * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testCodeInjectEndRnNRWithHttpInfo(String testCodeInjectEndRnNR) throws ApiException { - com.squareup.okhttp.Call call = testCodeInjectEndRnNRCall(testCodeInjectEndRnNR, null, null); - return apiClient.execute(call); - } - - /** - * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (asynchronously) - * - * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testCodeInjectEndRnNRAsync(String testCodeInjectEndRnNR, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testCodeInjectEndRnNRCall(testCodeInjectEndRnNR, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for testCodeInjectEndRnNR */ + private com.squareup.okhttp.Call testCodeInjectEndRnNRCall(String testCodeInjectEndRnNR, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (testCodeInjectEndRnNR != null) + localVarFormParams.put("test code inject */ ' " =end -- \r\n \n \r", testCodeInjectEndRnNR); + + final String[] localVarAccepts = { + "application/json", "*_/ ' =end -- " + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "*_/ ' =end -- " + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testCodeInjectEndRnNRValidateBeforeCall(String testCodeInjectEndRnNR, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + + com.squareup.okhttp.Call call = testCodeInjectEndRnNRCall(testCodeInjectEndRnNR, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testCodeInjectEndRnNR(String testCodeInjectEndRnNR) throws ApiException { + testCodeInjectEndRnNRWithHttpInfo(testCodeInjectEndRnNR); + } + + /** + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testCodeInjectEndRnNRWithHttpInfo(String testCodeInjectEndRnNR) throws ApiException { + com.squareup.okhttp.Call call = testCodeInjectEndRnNRValidateBeforeCall(testCodeInjectEndRnNR, null, null); + return apiClient.execute(call); + } + + /** + * To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (asynchronously) + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end -- \\r\\n \\n \\r (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testCodeInjectEndRnNRAsync(String testCodeInjectEndRnNR, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testCodeInjectEndRnNRValidateBeforeCall(testCodeInjectEndRnNR, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md index e25623732e0..975d73429f4 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md @@ -4,7 +4,7 @@ This spec is mainly for testing Petstore server and contains fake endpoints, mod This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: - API version: 1.0.0 *_/ ' \" =end -- \\r\\n \\n \\r -- Build package: class io.swagger.codegen.languages.PhpClientCodegen +- Build package: io.swagger.codegen.languages.PhpClientCodegen ## Requirements diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php b/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php index f4d106bc37b..efee00a5f46 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php @@ -9,17 +9,6 @@ * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * - * 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 - * - * http://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. */ /** diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json index 78602f3be45..7d1a19b4318 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/composer.json @@ -8,7 +8,7 @@ "api" ], "homepage": "http://swagger.io", - "license": "Apache-2.0", + "license": "proprietary", "authors": [ { "name": "Swagger and contributors", diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index d399e789de5..07f9f0e92fb 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -5,8 +5,7 @@ * * @category Class * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ @@ -19,17 +18,6 @@ * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * - * 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 - * - * http://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. */ /** @@ -50,8 +38,7 @@ use \Swagger\Client\ObjectSerializer; * * @category Class * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class FakeApi @@ -72,7 +59,6 @@ class FakeApi { if ($apiClient === null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('https://petstore.swagger.io *_/ ' \" =end -- \\r\\n \\n \\r/v2 *_/ ' \" =end -- \\r\\n \\n \\r'); } $this->apiClient = $apiClient; diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php index c8d7f70fedb..ea22b4f99ee 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php @@ -6,8 +6,7 @@ * * @category Class * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ @@ -20,17 +19,6 @@ * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * - * 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 - * - * http://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. */ /** @@ -46,8 +34,7 @@ namespace Swagger\Client; * * @category Class * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class ApiClient @@ -176,6 +163,11 @@ class ApiClient if ($this->config->getCurlTimeout() !== 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } + // set connect timeout, if needed + if ($this->config->getCurlConnectTimeout() != 0) { + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->config->getCurlConnectTimeout()); + } + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); @@ -187,6 +179,22 @@ class ApiClient curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } + if ($this->config->getCurlProxyHost()) { + curl_setopt($curl, CURLOPT_PROXY, $this->config->getCurlProxyHost()); + } + + if ($this->config->getCurlProxyPort()) { + curl_setopt($curl, CURLOPT_PROXYPORT, $this->config->getCurlProxyPort()); + } + + if ($this->config->getCurlProxyType()) { + curl_setopt($curl, CURLOPT_PROXYTYPE, $this->config->getCurlProxyType()); + } + + if ($this->config->getCurlProxyUser()) { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->config->getCurlProxyUser() . ':' .$this->config->getCurlProxyPassword()); + } + if (!empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php index 2e320f1bba5..4c029f982ae 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php @@ -5,8 +5,7 @@ * * @category Class * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ @@ -19,17 +18,6 @@ * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * - * 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 - * - * http://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. */ /** @@ -47,8 +35,7 @@ use \Exception; * * @category Class * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class ApiException extends Exception diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php index 69c7ce6bcbd..d430f0c7717 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php @@ -5,8 +5,7 @@ * * @category Class * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ @@ -19,17 +18,6 @@ * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * - * 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 - * - * http://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. */ /** @@ -46,8 +34,7 @@ namespace Swagger\Client; * * @category Class * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class Configuration @@ -110,6 +97,13 @@ class Configuration */ protected $curlTimeout = 0; + /** + * Timeout (second) of the HTTP connection, by default set to 0, no timeout + * + * @var string + */ + protected $curlConnectTimeout = 0; + /** * User agent of the HTTP request, set to "PHP-Swagger" by default * @@ -147,6 +141,42 @@ class Configuration */ protected $sslVerification = true; + /** + * Curl proxy host + * + * @var string + */ + protected $proxyHost; + + /** + * Curl proxy port + * + * @var integer + */ + protected $proxyPort; + + /** + * Curl proxy type, e.g. CURLPROXY_HTTP or CURLPROXY_SOCKS5 + * + * @see https://secure.php.net/manual/en/function.curl-setopt.php + * @var integer + */ + protected $proxyType; + + /** + * Curl proxy username + * + * @var string + */ + protected $proxyUser; + + /** + * Curl proxy password + * + * @var string + */ + protected $proxyPassword; + /** * Constructor */ @@ -393,6 +423,149 @@ class Configuration return $this->curlTimeout; } + /** + * Sets the HTTP connect timeout value + * + * @param integer $seconds Number of seconds before connection times out [set to 0 for no timeout] + * + * @return Configuration + */ + public function setCurlConnectTimeout($seconds) + { + if (!is_numeric($seconds) || $seconds < 0) { + throw new \InvalidArgumentException('Connect timeout value must be numeric and a non-negative number.'); + } + + $this->curlConnectTimeout = $seconds; + return $this; + } + + /** + * Gets the HTTP connect timeout value + * + * @return string HTTP connect timeout value + */ + public function getCurlConnectTimeout() + { + return $this->curlConnectTimeout; + } + + + /** + * Sets the HTTP Proxy Host + * + * @param string $proxyHost HTTP Proxy URL + * + * @return ApiClient + */ + public function setCurlProxyHost($proxyHost) + { + $this->proxyHost = $proxyHost; + return $this; + } + + /** + * Gets the HTTP Proxy Host + * + * @return string + */ + public function getCurlProxyHost() + { + return $this->proxyHost; + } + + /** + * Sets the HTTP Proxy Port + * + * @param integer $proxyPort HTTP Proxy Port + * + * @return ApiClient + */ + public function setCurlProxyPort($proxyPort) + { + $this->proxyPort = $proxyPort; + return $this; + } + + /** + * Gets the HTTP Proxy Port + * + * @return integer + */ + public function getCurlProxyPort() + { + return $this->proxyPort; + } + + /** + * Sets the HTTP Proxy Type + * + * @param integer $proxyType HTTP Proxy Type + * + * @return ApiClient + */ + public function setCurlProxyType($proxyType) + { + $this->proxyType = $proxyType; + return $this; + } + + /** + * Gets the HTTP Proxy Type + * + * @return integer + */ + public function getCurlProxyType() + { + return $this->proxyType; + } + + /** + * Sets the HTTP Proxy User + * + * @param string $proxyUser HTTP Proxy User + * + * @return ApiClient + */ + public function setCurlProxyUser($proxyUser) + { + $this->proxyUser = $proxyUser; + return $this; + } + + /** + * Gets the HTTP Proxy User + * + * @return string + */ + public function getCurlProxyUser() + { + return $this->proxyUser; + } + + /** + * Sets the HTTP Proxy Password + * + * @param string $proxyPassword HTTP Proxy Password + * + * @return ApiClient + */ + public function setCurlProxyPassword($proxyPassword) + { + $this->proxyPassword = $proxyPassword; + return $this; + } + + /** + * Gets the HTTP Proxy Password + * + * @return string + */ + public function getCurlProxyPassword() + { + return $this->proxyPassword; + } + /** * Sets debug flag * diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php index 2eade42511f..7f68442329a 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -6,8 +6,7 @@ * * @category Class * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swaagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ @@ -20,17 +19,6 @@ * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * - * 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 - * - * http://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. */ /** @@ -46,12 +34,10 @@ use \ArrayAccess; /** * ModelReturn Class Doc Comment * - * @category Class */ - // @description Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r -/** + * @category Class + * @description Model for testing reserved words *_/ ' \" =end -- \\r\\n \\n \\r * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class ModelReturn implements ArrayAccess @@ -145,6 +131,7 @@ class ModelReturn implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -152,10 +139,11 @@ class ModelReturn implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } @@ -239,3 +227,4 @@ class ModelReturn implements ArrayAccess } } + diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php index c72c36f24fd..4bfe77988bd 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -6,8 +6,7 @@ * * @category Class * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ @@ -20,17 +19,6 @@ * Contact: apiteam@swagger.io *_/ ' \" =end -- \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * - * 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 - * - * http://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. */ /** @@ -46,8 +34,7 @@ namespace Swagger\Client; * * @category Class * @package Swagger\Client - * @author http://github.com/swagger-api/swagger-codegen - * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License v2 + * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen */ class ObjectSerializer diff --git a/samples/client/petstore-security-test/python/README.md b/samples/client/petstore-security-test/python/README.md index 9f90aa1d071..971b2c7c77a 100644 --- a/samples/client/petstore-security-test/python/README.md +++ b/samples/client/petstore-security-test/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 */ ' \" =end -- \\r\\n \\n \\r - Package version: 1.0.0 -- Build package: class io.swagger.codegen.languages.PythonClientCodegen +- Build package: io.swagger.codegen.languages.PythonClientCodegen ## Requirements. diff --git a/samples/client/petstore-security-test/python/petstore_api/api_client.py b/samples/client/petstore-security-test/python/petstore_api/api_client.py index 02c6172ccc4..f8b73bc1463 100644 --- a/samples/client/petstore-security-test/python/petstore_api/api_client.py +++ b/samples/client/petstore-security-test/python/petstore_api/api_client.py @@ -116,7 +116,7 @@ class ApiClient(object): collection_formats) for k, v in path_params: resource_path = resource_path.replace( - '{%s}' % k, quote(str(v))) + '{%s}' % k, quote(str(v), safe="")) # query parameters if query_params: diff --git a/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py b/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py index f713d227c0e..a6961921ac4 100644 --- a/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py +++ b/samples/client/petstore-security-test/python/petstore_api/apis/fake_api.py @@ -116,12 +116,9 @@ class FakeApi(object): form_params.append(('test code inject */ ' " =end -- \r\n \n \r', params['test_code_inject____end____rn_n_r'])) body_params = None - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', '*/ \" =end -- ']) - if not header_params['Accept']: - del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ diff --git a/samples/client/petstore-security-test/python/petstore_api/models/model_return.py b/samples/client/petstore-security-test/python/petstore_api/models/model_return.py index 8256e70ca94..2b6f2a45172 100644 --- a/samples/client/petstore-security-test/python/petstore_api/models/model_return.py +++ b/samples/client/petstore-security-test/python/petstore_api/models/model_return.py @@ -105,6 +105,9 @@ class ModelReturn(object): """ Returns true if both objects are equal """ + if not isinstance(other, ModelReturn): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala index 18505facbd8..73949422393 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala @@ -85,10 +85,10 @@ object ApiInvoker { case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { case JString(s) => - ISODateTimeFormat.dateTimeParser().parseDateTime(s) + ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(s) }, { case d: DateTime => - JString(ISODateTimeFormat.dateTimeParser().print(d)) + JString(ISODateTimeFormat.dateTime().print(d)) })) } diff --git a/samples/client/petstore/bash/.swagger-codegen-ignore b/samples/client/petstore/bash/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/bash/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/bash/README.md b/samples/client/petstore/bash/README.md new file mode 100644 index 00000000000..619928a4026 --- /dev/null +++ b/samples/client/petstore/bash/README.md @@ -0,0 +1,88 @@ +# Swagger Petstore Bash client + +## Overview +This is a Bash client script for accessing Swagger Petstore service. + +The script uses cURL underneath for making all REST calls. + +## Usage + +```shell +# Make sure the script has executable rights +$ chmod u+x petstore-cli + +# Print the list of operations available on the service +$ ./petstore-cli -h + +# Print the service description +$ ./petstore-cli --about + +# Print detailed information about specific operation +$ ./petstore-cli -h + +# Make GET request +./petstore-cli --host http://: --accept xml = : + +# Make GET request using arbitrary curl options (must be passed before ) to an SSL service using username:password +petstore-cli -k -sS --tlsv1.2 --host https:// -u : --accept xml = : + +# Make POST request +$ echo '' | petstore-cli --host --content-type json - + +# Make POST request with simple JSON content, e.g.: +# { +# "key1": "value1", +# "key2": "value2", +# "key3": 23 +# } +$ echo '' | petstore-cli --host --content-type json key1==value1 key2=value2 key3:=23 - + +# Preview the cURL command without actually executing it +$ petstore-cli --host http://: --dry-run + +``` + +## Docker image +You can easily create a Docker image containing a preconfigured environment +for using the REST Bash client including working autocompletion and short +welcome message with basic instructions, using the generated Dockerfile: + +```shell +docker build -t my-rest-client . +docker run -it my-rest-client +``` + +By default you will be logged into a Zsh environment which has much more +advanced auto completion, but you can switch to Bash, where basic autocompletion +is also available. + +## Shell completion + +### Bash +The generated bash-completion script can be either directly loaded to the current Bash session using: + +```shell +source petstore-cli.bash-completion +``` + +Alternatively, the script can be copied to the `/etc/bash-completion.d` (or on OSX with Homebrew to `/usr/local/etc/bash-completion.d`): + +```shell +sudo cp petstore-cli.bash-completion /etc/bash-completion.d/petstore-cli +``` + +#### OS X +On OSX you might need to install bash-completion using Homebrew: +```shell +brew install bash-completion +``` +and add the following to the `~/.bashrc`: + +```shell +if [ -f $(brew --prefix)/etc/bash_completion ]; then + . $(brew --prefix)/etc/bash_completion +fi +``` + +### Zsh +In Zsh, the generated `_petstore-cli` Zsh completion file must be copied to one of the folders under `$FPATH` variable. diff --git a/samples/client/petstore/bash/_petstore-cli b/samples/client/petstore/bash/_petstore-cli new file mode 100644 index 00000000000..a1a2a44dcb9 --- /dev/null +++ b/samples/client/petstore/bash/_petstore-cli @@ -0,0 +1,491 @@ +#compdef petstore-cli + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Based on: https://github.com/Valodim/zsh-curl-completion/blob/master/_curl +# ! +# ! Generated on: 2017-02-06T21:48:13.013+01:00 +# ! +# ! +# ! Installation: +# ! +# ! Copy the _petstore-cli file to any directory under FPATH +# ! environment variable (echo $FPATH) +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + +local curcontext="$curcontext" state line ret=1 +typeset -A opt_args + +typeset -A mime_type_abbreviations +# text/* +mime_type_abbreviations[text]="text/plain" +mime_type_abbreviations[html]="text/html" +mime_type_abbreviations[md]="text/x-markdown" +mime_type_abbreviations[csv]="text/csv" +mime_type_abbreviations[css]="text/css" +mime_type_abbreviations[rtf]="text/rtf" +# application/* +mime_type_abbreviations[json]="application/json" +mime_type_abbreviations[xml]="application/xml" +mime_type_abbreviations[yaml]="application/yaml" +mime_type_abbreviations[js]="application/javascript" +mime_type_abbreviations[bin]="application/octet-stream" +mime_type_abbreviations[rdf]="application/rdf+xml" +# image/* +mime_type_abbreviations[jpg]="image/jpeg" +mime_type_abbreviations[png]="image/png" +mime_type_abbreviations[gif]="image/gif" +mime_type_abbreviations[bmp]="image/bmp" +mime_type_abbreviations[tiff]="image/tiff" + +# +# Generate zsh completion string list for abbreviated mime types +# +get_mime_type_completions() { + typeset -a result + result=() + for k in "${(@k)mime_type_abbreviations}"; do + value=$mime_type_abbreviations[${k}] + #echo $value + result+=( "${k}[${value}]" ) + #echo $result + done + echo "$result" +} + +# +# cURL crypto engines completion function +# +_curl_crypto_engine() { + local vals + vals=( ${${(f)"$(curl --engine list)":gs/ /}[2,$]} ) + _describe -t outputs 'engines' vals && return 0 +} + +# +# cURL post data completion functions= +# +_curl_post_data() { + + # don't do anything further if this is raw content + compset -P '=' && _message 'raw content' && return 0 + + # complete filename or stdin for @ syntax + compset -P '*@' && { + local expl + _description files expl stdin + compadd "$expl[@]" - "-" + _files + return 0 + } + + # got a name already? expecting data. + compset -P '*=' && _message 'data value' && return 0 + + # otherwise, name (or @ or =) should be specified + _message 'data name' && return 0 + +} + + +local arg_http arg_ftp arg_other arg_proxy arg_crypto arg_connection arg_auth arg_input arg_output + +# HTTP Arguments +arg_http=(''\ + {-0,--http1.0}'[force use of use http 1.0 instead of 1.1]' \ + {-b,--cookie}'[pass data to http server as cookie]:data or file' \ + {-c,--cookie-jar}'[specify cookie file]:file name:_files' \ + {-d,--data}'[send specified data as HTTP POST data]:data:{_curl_post_data}' \ + '--data-binary[post HTTP POST data without any processing]:data:{_curl_post_data}' \ + '--data-urlencode[post HTTP POST data, with url encoding]:data:{_curl_post_data}' \ + {-f,--fail}'[enable failfast behavior for server errors]' \ + '*'{-F,--form}'[add POST form data]:name=content' \ + {-G,--get}'[use HTTP GET even with data (-d, --data, --data-binary)]' \ + '*'{-H,--header}'[specify an extra header]:header' \ + '--ignore-content-length[ignore Content-Length header]' \ + {-i,--include}'[include HTTP header in the output]' \ + {-j,--junk-session-cookies}'[discard all session cookies]' \ + {-e,--referer}'[send url as referer]:referer url:_urls' \ + {-L,--location}'[follow Location headers on http 3XX response]' \ + '--location-trusted[like --location, but allows sending of auth data to redirected hosts]' \ + '--max-redirs[set maximum number of redirection followings allowed]:number' \ + {-J,--remote-header-name}'[use Content-Disposition for output file name]' \ + {-O,--remote-name}'[write to filename parsed from url instead of stdout]' \ + '--post301[do not convert POST to GET after following 301 Location response (follow RFC 2616/10.3.2)]' \ + '--post302[do not convert POST to GET after following 302 Location response (follow RFC 2616/10.3.2)]' \ + ) + +# FTP arguments +arg_ftp=(\ + {-a,--append}'[append to target file instead of overwriting (FTP/SFTP)]' \ + '--crlf[convert LF to CRLF in upload]' \ + '--disable-eprt[disable use of EPRT and LPRT for active FTP transfers]' \ + '--disable-epsv[disable use of EPSV for passive FTP transfers]' \ + '--ftp-account[account data (FTP)]:data' \ + '--ftp-alternative-to-user[command to send when USER and PASS commands fail (FTP)]:command' \ + '--ftp-create-dirs[create paths remotely if it does not exist]' \ + '--ftp-method[ftp method to use to reach a file (FTP)]:method:(multicwd ocwd singlecwd)' \ + '--ftp-pasv[use passive mode for the data connection (FTP)]' \ + '--ftp-skip-pasv-ip[do not use the ip the server suggests for PASV]' \ + '--form-string[like --form, but do not parse content]:name=string' \ + '--ftp-pret[send PRET before PASV]' \ + '--ftp-ssl-ccc[use clear command channel (CCC) after authentication (FTP)]' \ + '--ftp-ssl-ccc-mode[sets the CCC mode (FTP)]:mode:(active passive)' \ + '--ftp-ssl-control[require SSL/TLS for FTP login, clear for transfer]' \ + {-l,--list-only}'[list names only when listing directories (FTP)]' \ + {-P,--ftp-port}'[use active mode, tell server to connect to specified address or interface (FTP]:address' \ + '*'{-Q,--quote}'[send arbitrary command to the remote server before transfer (FTP/SFTP)]:command' \ + ) + +# Other Protocol arguments +arg_other=(\ + '--mail-from[specify From: address]:address' \ + '--mail-rcpt[specify email recipient for SMTP, may be given multiple times]:address' \ + {-t,--telnet-option}'[pass options to telnet protocol]:opt=val' \ + '--tftp-blksize[set tftp BLKSIZE option]:value' \ + ) + +# Proxy arguments +arg_proxy=(\ + '--noproxy[list of hosts to connect directly to instead of through proxy]:no-proxy-list' \ + {-p,--proxytunnel}'[tunnel non-http protocols through http proxy]' \ + {-U,--proxy-user}'[specify the user name and password to use for proxy authentication]:user:password' \ + '--proxy-anyauth[use any authentication method for proxy, default to most secure]' \ + '--proxy-basic[use HTTP Basic authentication for proxy]' \ + '--proxy-digest[use http digest authentication for proxy]' \ + '--proxy-negotiate[enable GSS-Negotiate authentication for proxy]' \ + '--proxy-ntlm[enable ntlm authentication for proxy]' \ + '--proxy1.0[use http 1.0 proxy]:proxy url' \ + {-x,--proxy}'[use specified proxy]:proxy url' \ + '--socks5-gssapi-service[change service name for socks server]:servicename' \ + '--socks5-gssapi-nec[allow unprotected exchange of protection mode negotiation]' \ + ) + +# Crypto arguments +arg_crypto=(\ + {-1,--tlsv1}'[Forces curl to use TLS version 1 when negotiating with a remote TLS server.]' \ + {-2,--sslv2}'[Forces curl to use SSL version 2 when negotiating with a remote SSL server.]' \ + {-3,--sslv3}'[Forces curl to use SSL version 3 when negotiating with a remote SSL server.]' \ + '--ciphers[specifies which cipher to use for the ssl connection]:list of ciphers' \ + '--crlfile[specify file with revoked certificates]:file' \ + '--delegation[set delegation policy to use with GSS/kerberos]:delegation policy:(none policy always)' \ + {-E,--cert}'[use specified client certificate]:certificate file:_files' \ + '--engine[use selected OpenSSL crypto engine]:ssl crypto engine:{_curl_crypto_engine}' \ + '--egd-file[set ssl entropy gathering daemon socket]:entropy socket:_files' \ + '--cert-type[specify certificate type (PEM, DER, ENG)]:certificate type:(PEM DER ENG)' \ + '--cacert[specify certificate file to verify the peer with]:CA certificate:_files' \ + '--capath[specify a search path for certificate files]:CA certificate directory:_directories' \ + '--hostpubmd5[check remote hosts public key]:md5 hash' \ + {-k,--insecure}'[allow ssl to perform insecure ssl connections (ie, ignore certificate)]' \ + '--key[ssl/ssh private key file name]:key file:_files' \ + '--key-type[ssl/ssh private key file type]:file type:(PEM DER ENG)' \ + '--pubkey[ssh public key file]:pubkey file:_files' \ + '--random-file[set source of random data for ssl]:random source:_files' \ + '--no-sessionid[disable caching of ssl session ids]' \ + '--pass:phrase[passphrase for ssl/ssh private key]' \ + '--ssl[try to use ssl/tls for connection, if available]' \ + '--ssl-reqd[try to use ssl/tls for connection, fail if unavailable]' \ + '--tlsauthtype[set TLS authentication type (only SRP supported!)]:authtype' \ + '--tlsuser[set username for TLS authentication]:user' \ + '--tlspassword[set password for TLS authentication]:password' \ + ) + +# Connection arguments +arg_connection=(\ + {-4,--ipv4}'[prefer ipv4]' \ + {-6,--ipv6}'[prefer ipv6, if available]' \ + {-B,--use-ascii}'[use ascii mode]' \ + '--compressed[request a compressed transfer]' \ + '--connect-timeout[timeout for connection phase]:seconds' \ + {-I,--head}'[fetch http HEAD only (HTTP/FTP/FILE]' \ + '--interface[work on a specific interface]:name' \ + '--keepalive-time[set time to wait before sending keepalive probes]:seconds' \ + '--limit-rate[specify maximum transfer rate]:speed' \ + '--local-port[set preferred number or range of local ports to use]:num' \ + {-N,--no-buffer}'[disable buffering of the output stream]' \ + '--no-keepalive[disable use of keepalive messages in TCP connections]' \ + '--raw[disable all http decoding and pass raw data]' \ + '--resolve[provide a custom address for a specific host and port pair]:host\:port\:address' \ + '--retry[specify maximum number of retries for transient errors]:num' \ + '--retry-delay[specify delay between retries]:seconds' \ + '--retry-max-time[maximum time to spend on retries]:seconds' \ + '--tcp-nodelay[turn on TCP_NODELAY option]' \ + {-y,--speed-time}'[specify time to abort after if download is slower than speed-limit]:time' \ + {-Y,--speed-limit}'[specify minimum speed for --speed-time]:speed' \ + ) + +# Authentication arguments +arg_auth=(\ + '--anyauth[use any authentication method, default to most secure]' \ + '--basic[use HTTP Basic authentication]' \ + '--ntlm[enable ntlm authentication]' \ + '--digest[use http digest authentication]' \ + '--krb[use kerberos authentication]:auth:(clear safe confidential private)' \ + '--negotiate[enable GSS-Negotiate authentication]' \ + {-n,--netrc}'[scan ~/.netrc for login data]' \ + '--netrc-optional[like --netrc, but does not make .netrc usage mandatory]' \ + '--netrc-file[like --netrc, but specify file to use]:netrc file:_files' \ + '--tr-encoding[request compressed transfer-encoding]' \ + {-u,--user}'[specify user name and password for server authentication]:user\:password' \ + ) + +# Input arguments +arg_input=(\ + {-C,--continue-at}'[resume at offset ]:offset' \ + {-g,--globoff}'[do not glob {}\[\] letters]' \ + '--max-filesize[maximum filesize to download, fail for bigger files]:bytes' \ + '--proto[specify allowed protocols for transfer]:protocols' \ + '--proto-redir[specify allowed protocols for transfer after a redirect]:protocols' \ + {-r,--range}'[set range of bytes to request (HTTP/FTP/SFTP/FILE)]:range' \ + {-R,--remote-time}'[use timestamp of remote file for local file]' \ + {-T,--upload-file}'[transfer file to remote url (using PUT for HTTP)]:file to upload:_files' \ + '--url[specify a URL to fetch (multi)]:url:_urls' \ + {-z,--time-cond}'[request downloaded file to be newer than date or given reference file]:date expression' \ + ) + +# Output arguments +arg_output=(\ + '--create-dirs[create local directory hierarchy as needed]' \ + {-D,--dump-header}'[write protocol headers to file]:dump file:_files' \ + {-o,--output}'[write to specified file instead of stdout]:output file:_files' \ + {--progress-bar,-\#}'[display progress as a simple progress bar]' \ + {-\#,--progress-bar}'[Make curl display progress as a simple progress bar instead of the standard, more informational, meter.]' \ + {-R,--remote-time}'[use timestamp of remote file for local file]' \ + '--raw[disable all http decoding and pass raw data]' \ + {-s,--silent}'[silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[show errors in silent mode]' \ + '--stderr[redirect stderr to specified file]:output file:_files' \ + '--trace[enable full trace dump of all incoming and outgoing data]:trace file:_files' \ + '--trace-ascii[enable full trace dump of all incoming and outgoing data, without hex data]:trace file:_files' \ + '--trace-time[prepends a time stamp to each trace or verbose line that curl displays]' \ + {-v,--verbose}'[output debug info]' \ + {-w,--write-out}'[specify message to output on successful operation]:format string' \ + '--xattr[store some file metadata in extended file attributes]' \ + {-X,--request}'[specifies request method for HTTP server]:method:(GET POST PUT DELETE HEAD OPTIONS TRACE CONNECT PATCH LINK UNLINK)' \ + ) + +_arguments -C -s $arg_http $arg_ftp $arg_other $arg_crypto $arg_connection $arg_auth $arg_input $arg_output \ + {-M,--manual}'[Print manual]' \ + '*'{-K,--config}'[Use other config file to read arguments from]:config file:_files' \ + '--libcurl[output libcurl code for the operation to file]:output file:_files' \ + {-m,--max-time}'[Limit total time of operation]:seconds' \ + {-s,--silent}'[Silent mode, do not show progress meter or error messages]' \ + {-S,--show-error}'[Show errors in silent mode]' \ + '--stderr[Redirect stderr to specified file]:output file:_files' \ + '-q[Do not read settings from .curlrc (must be first option)]' \ + {-h,--help}'[Print help and list of operations]' \ + {-V,--version}'[Print service API version]' \ + '--about[Print the information about service]' \ + '--host[Specify the host URL]':URL:_urls \ + '--dry-run[Print out the cURL command without executing it]' \ + {-ac,--accept}'[Set the Accept header in the request]: :{_values "Accept mime type" $(get_mime_type_completions)}' \ + {-ct,--content-type}'[Set the Content-type header in request]: :{_values "Content mime type" $(get_mime_type_completions)}' \ + '1: :->ops' \ + '*:: :->args' \ + && ret=0 + + +case $state in + ops) + # Operations + _values "Operations" \ + "testClientModel[To test \"client\" model]" \ + "testEndpointParameters[Fake endpoint for testing various parameters +假端點 +偽のエンドポイント +가짜 엔드 포인트]" \ + "testEnumParameters[To test enum parameters]" "addPet[Add a new pet to the store]" \ + "deletePet[Deletes a pet]" \ + "findPetsByStatus[Finds Pets by status]" \ + "findPetsByTags[Finds Pets by tags]" \ + "getPetById[Find pet by ID]" \ + "updatePet[Update an existing pet]" \ + "updatePetWithForm[Updates a pet in the store with form data]" \ + "uploadFile[uploads an image]" "deleteOrder[Delete purchase order by ID]" \ + "getInventory[Returns pet inventories by status]" \ + "getOrderById[Find purchase order by ID]" \ + "placeOrder[Place an order for a pet]" "createUser[Create user]" \ + "createUsersWithArrayInput[Creates list of users with given input array]" \ + "createUsersWithListInput[Creates list of users with given input array]" \ + "deleteUser[Delete user]" \ + "getUserByName[Get user by user name]" \ + "loginUser[Logs user into the system]" \ + "logoutUser[Logs out current logged in user session]" \ + "updateUser[Updated user]" + _arguments "(--help)--help[Print information about operation]" + + ret=0 + ;; + args) + case $line[1] in + testClientModel) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + testEndpointParameters) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + testEnumParameters) + local -a _op_arguments + _op_arguments=( + "enum_query_string_array=:[QUERY] Query parameter enum test (string array)" +"enum_query_string=:[QUERY] Query parameter enum test (string)" +"enum_query_integer=:[QUERY] Query parameter enum test (double)" + "enum_header_string_array\::[HEADER] Header parameter enum test (string array)" +"enum_header_string\::[HEADER] Header parameter enum test (string)" +) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + addPet) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + deletePet) + local -a _op_arguments + _op_arguments=( + "petId=:[PATH] Pet id to delete" + "api_key\::[HEADER] " +) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + findPetsByStatus) + local -a _op_arguments + _op_arguments=( + "status=:[QUERY] Status values that need to be considered for filter" + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + findPetsByTags) + local -a _op_arguments + _op_arguments=( + "tags=:[QUERY] Tags to filter by" + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + getPetById) + local -a _op_arguments + _op_arguments=( + "petId=:[PATH] ID of pet to return" + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + updatePet) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + updatePetWithForm) + local -a _op_arguments + _op_arguments=( + "petId=:[PATH] ID of pet that needs to be updated" + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + uploadFile) + local -a _op_arguments + _op_arguments=( + "petId=:[PATH] ID of pet to update" + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + deleteOrder) + local -a _op_arguments + _op_arguments=( + "orderId=:[PATH] ID of the order that needs to be deleted" + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + getInventory) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + getOrderById) + local -a _op_arguments + _op_arguments=( + "orderId=:[PATH] ID of pet that needs to be fetched" + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + placeOrder) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + createUser) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + createUsersWithArrayInput) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + createUsersWithListInput) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + deleteUser) + local -a _op_arguments + _op_arguments=( + "username=:[PATH] The name that needs to be deleted" + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + getUserByName) + local -a _op_arguments + _op_arguments=( + "username=:[PATH] The name that needs to be fetched. Use user1 for testing." + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + loginUser) + local -a _op_arguments + _op_arguments=( + "username=:[QUERY] The user name for login" +"password=:[QUERY] The password for login in clear text" + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + logoutUser) + local -a _op_arguments + _op_arguments=( + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + updateUser) + local -a _op_arguments + _op_arguments=( + "username=:[PATH] name that need to be deleted" + ) + _describe -t actions 'operations' _op_arguments -S '' && ret=0 + ;; + esac + ;; + +esac + +return ret diff --git a/samples/client/petstore/bash/petstore-cli b/samples/client/petstore/bash/petstore-cli new file mode 100755 index 00000000000..6b3270270ce --- /dev/null +++ b/samples/client/petstore/bash/petstore-cli @@ -0,0 +1,3317 @@ +#!/usr/bin/env bash + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Generated on: 2017-02-06T21:48:13.013+01:00 +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +# +# This is a Bash client for Swagger Petstore. +# +# LICENSE: +# http://www.apache.org/licenses/LICENSE-2.0.html +# +# CONTACT: +# apiteam@swagger.io +# +# MORE INFORMATION: +# http://swagger.io +# + +############################################################################### +# +# Make sure Bash is at least in version 4.3 +# +############################################################################### +if ! ( (("${BASH_VERSION:0:1}" == "4")) && (("${BASH_VERSION:2:1}" >= "3")) ) \ + && ! (("${BASH_VERSION:0:1}" >= "5")); then + echo "" + echo "Sorry - your Bash version is ${BASH_VERSION}" + echo "" + echo "You need at least Bash 4.3 to run this script." + echo "" + exit 1 +fi + +############################################################################### +# +# Global variables +# +############################################################################### + +## +# The filename of this script for help messages +script_name=`basename "$0"` + +## +# Map for headers passed after operation as KEY:VALUE +declare -A header_arguments + + +## +# Map for operation parameters passed after operation as PARAMETER=VALUE +# These will be mapped to appropriate path or query parameters +# The values in operation_parameters are arrays, so that multiple values +# can be provided for the same parameter if allowed by API specification +declare -A operation_parameters + +## +# This array stores the minimum number of required occurences for parameter +# 0 - optional +# 1 - required +declare -A operation_parameters_minimum_occurences +operation_parameters_minimum_occurences["testClientModel:::body"]=1 +operation_parameters_minimum_occurences["testEndpointParameters:::number"]=1 +operation_parameters_minimum_occurences["testEndpointParameters:::double"]=1 +operation_parameters_minimum_occurences["testEndpointParameters:::pattern_without_delimiter"]=1 +operation_parameters_minimum_occurences["testEndpointParameters:::byte"]=1 +operation_parameters_minimum_occurences["testEndpointParameters:::integer"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::int32"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::int64"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::float"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::string"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::binary"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::date"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::dateTime"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::password"]=0 +operation_parameters_minimum_occurences["testEndpointParameters:::callback"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_form_string_array"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_form_string"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_header_string_array"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_header_string"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_query_string_array"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_query_string"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_query_integer"]=0 +operation_parameters_minimum_occurences["testEnumParameters:::enum_query_double"]=0 +operation_parameters_minimum_occurences["addPet:::body"]=1 +operation_parameters_minimum_occurences["deletePet:::petId"]=1 +operation_parameters_minimum_occurences["deletePet:::api_key"]=0 +operation_parameters_minimum_occurences["findPetsByStatus:::status"]=1 +operation_parameters_minimum_occurences["findPetsByTags:::tags"]=1 +operation_parameters_minimum_occurences["getPetById:::petId"]=1 +operation_parameters_minimum_occurences["updatePet:::body"]=1 +operation_parameters_minimum_occurences["updatePetWithForm:::petId"]=1 +operation_parameters_minimum_occurences["updatePetWithForm:::name"]=0 +operation_parameters_minimum_occurences["updatePetWithForm:::status"]=0 +operation_parameters_minimum_occurences["uploadFile:::petId"]=1 +operation_parameters_minimum_occurences["uploadFile:::additionalMetadata"]=0 +operation_parameters_minimum_occurences["uploadFile:::file"]=0 +operation_parameters_minimum_occurences["deleteOrder:::orderId"]=1 +operation_parameters_minimum_occurences["getOrderById:::orderId"]=1 +operation_parameters_minimum_occurences["placeOrder:::body"]=1 +operation_parameters_minimum_occurences["createUser:::body"]=1 +operation_parameters_minimum_occurences["createUsersWithArrayInput:::body"]=1 +operation_parameters_minimum_occurences["createUsersWithListInput:::body"]=1 +operation_parameters_minimum_occurences["deleteUser:::username"]=1 +operation_parameters_minimum_occurences["getUserByName:::username"]=1 +operation_parameters_minimum_occurences["loginUser:::username"]=1 +operation_parameters_minimum_occurences["loginUser:::password"]=1 +operation_parameters_minimum_occurences["updateUser:::username"]=1 +operation_parameters_minimum_occurences["updateUser:::body"]=1 + +## +# This array stores the maximum number of allowed occurences for parameter +# 1 - single value +# 2 - 2 values +# N - N values +# 0 - unlimited +declare -A operation_parameters_maximum_occurences +operation_parameters_maximum_occurences["testClientModel:::body"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::number"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::double"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::pattern_without_delimiter"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::byte"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::integer"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::int32"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::int64"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::float"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::string"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::binary"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::date"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::dateTime"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::password"]=0 +operation_parameters_maximum_occurences["testEndpointParameters:::callback"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_form_string_array"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_form_string"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_header_string_array"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_header_string"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_query_string_array"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_query_string"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_query_integer"]=0 +operation_parameters_maximum_occurences["testEnumParameters:::enum_query_double"]=0 +operation_parameters_maximum_occurences["addPet:::body"]=0 +operation_parameters_maximum_occurences["deletePet:::petId"]=0 +operation_parameters_maximum_occurences["deletePet:::api_key"]=0 +operation_parameters_maximum_occurences["findPetsByStatus:::status"]=0 +operation_parameters_maximum_occurences["findPetsByTags:::tags"]=0 +operation_parameters_maximum_occurences["getPetById:::petId"]=0 +operation_parameters_maximum_occurences["updatePet:::body"]=0 +operation_parameters_maximum_occurences["updatePetWithForm:::petId"]=0 +operation_parameters_maximum_occurences["updatePetWithForm:::name"]=0 +operation_parameters_maximum_occurences["updatePetWithForm:::status"]=0 +operation_parameters_maximum_occurences["uploadFile:::petId"]=0 +operation_parameters_maximum_occurences["uploadFile:::additionalMetadata"]=0 +operation_parameters_maximum_occurences["uploadFile:::file"]=0 +operation_parameters_maximum_occurences["deleteOrder:::orderId"]=0 +operation_parameters_maximum_occurences["getOrderById:::orderId"]=0 +operation_parameters_maximum_occurences["placeOrder:::body"]=0 +operation_parameters_maximum_occurences["createUser:::body"]=0 +operation_parameters_maximum_occurences["createUsersWithArrayInput:::body"]=0 +operation_parameters_maximum_occurences["createUsersWithListInput:::body"]=0 +operation_parameters_maximum_occurences["deleteUser:::username"]=0 +operation_parameters_maximum_occurences["getUserByName:::username"]=0 +operation_parameters_maximum_occurences["loginUser:::username"]=0 +operation_parameters_maximum_occurences["loginUser:::password"]=0 +operation_parameters_maximum_occurences["updateUser:::username"]=0 +operation_parameters_maximum_occurences["updateUser:::body"]=0 + +## +# The type of collection for specifying multiple values for parameter: +# - multi, csv, ssv, tsv +declare -A operation_parameters_collection_type +operation_parameters_collection_type["testClientModel:::body"]="" +operation_parameters_collection_type["testEndpointParameters:::number"]="" +operation_parameters_collection_type["testEndpointParameters:::double"]="" +operation_parameters_collection_type["testEndpointParameters:::pattern_without_delimiter"]="" +operation_parameters_collection_type["testEndpointParameters:::byte"]="" +operation_parameters_collection_type["testEndpointParameters:::integer"]="" +operation_parameters_collection_type["testEndpointParameters:::int32"]="" +operation_parameters_collection_type["testEndpointParameters:::int64"]="" +operation_parameters_collection_type["testEndpointParameters:::float"]="" +operation_parameters_collection_type["testEndpointParameters:::string"]="" +operation_parameters_collection_type["testEndpointParameters:::binary"]="" +operation_parameters_collection_type["testEndpointParameters:::date"]="" +operation_parameters_collection_type["testEndpointParameters:::dateTime"]="" +operation_parameters_collection_type["testEndpointParameters:::password"]="" +operation_parameters_collection_type["testEndpointParameters:::callback"]="" +operation_parameters_collection_type["testEnumParameters:::enum_form_string_array"]= +operation_parameters_collection_type["testEnumParameters:::enum_form_string"]="" +operation_parameters_collection_type["testEnumParameters:::enum_header_string_array"]= +operation_parameters_collection_type["testEnumParameters:::enum_header_string"]="" +operation_parameters_collection_type["testEnumParameters:::enum_query_string_array"]= +operation_parameters_collection_type["testEnumParameters:::enum_query_string"]="" +operation_parameters_collection_type["testEnumParameters:::enum_query_integer"]="" +operation_parameters_collection_type["testEnumParameters:::enum_query_double"]="" +operation_parameters_collection_type["addPet:::body"]="" +operation_parameters_collection_type["deletePet:::petId"]="" +operation_parameters_collection_type["deletePet:::api_key"]="" +operation_parameters_collection_type["findPetsByStatus:::status"]="csv" +operation_parameters_collection_type["findPetsByTags:::tags"]="csv" +operation_parameters_collection_type["getPetById:::petId"]="" +operation_parameters_collection_type["updatePet:::body"]="" +operation_parameters_collection_type["updatePetWithForm:::petId"]="" +operation_parameters_collection_type["updatePetWithForm:::name"]="" +operation_parameters_collection_type["updatePetWithForm:::status"]="" +operation_parameters_collection_type["uploadFile:::petId"]="" +operation_parameters_collection_type["uploadFile:::additionalMetadata"]="" +operation_parameters_collection_type["uploadFile:::file"]="" +operation_parameters_collection_type["deleteOrder:::orderId"]="" +operation_parameters_collection_type["getOrderById:::orderId"]="" +operation_parameters_collection_type["placeOrder:::body"]="" +operation_parameters_collection_type["createUser:::body"]="" +operation_parameters_collection_type["createUsersWithArrayInput:::body"]= +operation_parameters_collection_type["createUsersWithListInput:::body"]= +operation_parameters_collection_type["deleteUser:::username"]="" +operation_parameters_collection_type["getUserByName:::username"]="" +operation_parameters_collection_type["loginUser:::username"]="" +operation_parameters_collection_type["loginUser:::password"]="" +operation_parameters_collection_type["updateUser:::username"]="" +operation_parameters_collection_type["updateUser:::body"]="" + + +## +# Map for body parameters passed after operation as +# PARAMETER==STRING_VALUE or PARAMETER:=NUMERIC_VALUE +# These will be mapped to top level json keys ( { "PARAMETER": "VALUE" }) +declare -A body_parameters + +## +# These arguments will be directly passed to cURL +curl_arguments="" + +## +# The host for making the request +host="$PETSTORE_HOST" + +## +# The user credentials for basic authentication +basic_auth_credential="$PETSTORE_BASIC_AUTH" + +## +# The user API key +apikey_auth_credential="$PETSTORE_API_KEY" + +## +# If true, the script will only output the actual cURL command that would be +# used +print_curl=false + +## +# The operation ID passed on the command line +operation="" + +## +# The provided Accept header value +header_accept="" + +## +# The provided Content-type header value +header_content_type="" + +## +# If there is any body content on the stdin pass it to the body of the request +body_content_temp_file="" + +## +# If this variable is set to true, the request will be performed even +# if parameters for required query, header or body values are not provided +# (path parameters are still required). +force=false + +## +# Declare some mime types abbreviations for easier content-type and accepts +# headers specification +declare -A mime_type_abbreviations +# text/* +mime_type_abbreviations["text"]="text/plain" +mime_type_abbreviations["html"]="text/html" +mime_type_abbreviations["md"]="text/x-markdown" +mime_type_abbreviations["csv"]="text/csv" +mime_type_abbreviations["css"]="text/css" +mime_type_abbreviations["rtf"]="text/rtf" +# application/* +mime_type_abbreviations["json"]="application/json" +mime_type_abbreviations["xml"]="application/xml" +mime_type_abbreviations["yaml"]="application/yaml" +mime_type_abbreviations["js"]="application/javascript" +mime_type_abbreviations["bin"]="application/octet-stream" +mime_type_abbreviations["rdf"]="application/rdf+xml" +# image/* +mime_type_abbreviations["jpg"]="image/jpeg" +mime_type_abbreviations["png"]="image/png" +mime_type_abbreviations["gif"]="image/gif" +mime_type_abbreviations["bmp"]="image/bmp" +mime_type_abbreviations["tiff"]="image/tiff" + + +############################################################################## +# +# Escape special URL characters +# Based on table at http://www.w3schools.com/tags/ref_urlencode.asp +# +############################################################################## +url_escape() { + local raw_url="$1" + + value=$(sed -e 's/ /%20/g' \ + -e 's/!/%21/g' \ + -e 's/"/%22/g' \ + -e 's/#/%23/g' \ + -e 's/\&/%26/g' \ + -e 's/'\''/%28/g' \ + -e 's/(/%28/g' \ + -e 's/)/%29/g' \ + -e 's/:/%3A/g' \ + -e 's/?/%3F/g' <<<$raw_url); + + echo $value +} + +############################################################################## +# +# Lookup the mime type abbreviation in the mime_type_abbreviations array. +# If not present assume the user provided a valid mime type +# +############################################################################## +lookup_mime_type() { + local mime_type=$1 + + if [[ ${mime_type_abbreviations[$mime_type]} ]]; then + echo ${mime_type_abbreviations[$mime_type]} + else + echo $1 + fi +} + +############################################################################## +# +# Converts an associative array into a list of cURL header +# arguments (-H "KEY: VALUE") +# +############################################################################## +header_arguments_to_curl() { + local headers_curl="" + local api_key_header="" + local api_key_header_in_cli="" + api_key_header="api_key" + + for key in "${!header_arguments[@]}"; do + headers_curl+="-H \"${key}: ${header_arguments[${key}]}\" " + if [[ "${key}XX" == "${api_key_header}XX" ]]; then + api_key_header_in_cli="YES" + fi + done + # + # If the api_key was not provided in the header, try one from the + # environment variable + # + if [[ -z $api_key_header_in_cli && -n $apikey_auth_credential ]]; then + headers_curl+="-H \"${api_key_header}: ${apikey_auth_credential}\"" + fi + headers_curl+=" " + + echo "${headers_curl}" +} + +############################################################################## +# +# Converts an associative array into a simple JSON with keys as top +# level object attributes +# +# \todo Add convertion of more complex attributes using paths +# +############################################################################## +body_parameters_to_json() { + local body_json="-d '{" + local body_parameter_count=${#body_parameters[@]} + local count=0 + for key in "${!body_parameters[@]}"; do + body_json+="\"${key}\": ${body_parameters[${key}]}" + if [[ $count -lt $body_parameter_count-1 ]]; then + body_json+=", " + fi + count+=1 + done + body_json+="}'" + + if [[ "${#body_parameters[@]}" -eq 0 ]]; then + echo "" + else + echo "${body_json}" + fi +} + +############################################################################## +# +# Check if provided parameters match specification requirements +# +############################################################################## +validate_request_parameters() { + local path_template=$1 + local -n path_params=$2 + local -n query_params=$3 + + # First replace all path parameters in the path + for pparam in "${path_params[@]}"; do + regexp="(.*)(\{$pparam\})(.*)" + if [[ $path_template =~ $regexp ]]; then + path_template=${BASH_REMATCH[1]}${operation_parameters[$pparam]}${BASH_REMATCH[3]} + fi + done + + # Now append query parameters - if any + if [[ ${#query_params[@]} -gt 0 ]]; then + path_template+="?" + fi + + local query_parameter_count=${#query_params[@]} + local count=0 + for qparam in "${query_params[@]}"; do + # Get the array of parameter values + local parameter_values=($(echo "${operation_parameters[$qparam]}" | sed -e 's/'":::"'/\n/g' | while read line; do echo $line | sed 's/[\t ]/'":::"'/g'; done)) + + # + # Check if the number of provided values is not less than minimum + # required + # + if [[ "$force" = false ]]; then + if [[ ${#parameter_values[@]} -lt ${operation_parameters_minimum_occurences["${operation}:::${qparam}"]} ]]; then + echo "Error: Too few values provided for '${qparam}' parameter" + exit 1 + fi + + # + # Check if the number of provided values is not more than maximum + # + if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + if [[ "$force" = false ]]; then + echo "Error: Too many values provided for '${qparam}' parameter" + exit 1 + fi + fi + fi + + if [[ "${operation_parameters_collection_type[${operation}:::${qparam}]}" == "" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="&" + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "multi" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="&" + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "csv" ]]; then + path_template+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="," + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "ssv" ]]; then + path_template+="${qparam}=" + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+=" " + fi + vcount+=1 + done + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "tsv" ]]; then + path_template+="${qparam}=" + for qvalue in "${parameter_values[@]}"; do + path_template+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + path_template+="\t" + fi + vcount+=1 + done + else + echo -e "" + echo -e "Error: Unsupported collection format " + echo -e "" + exit 1 + fi + + + if [[ $count -lt $query_parameter_count-1 ]]; then + path_template+="&" + fi + count+=1 + done + +} + + + +############################################################################## +# +# Build request path including query parameters +# +############################################################################## +build_request_path() { + local path_template=$1 + local -n path_params=$2 + local -n query_params=$3 + + + # First replace all path parameters in the path + for pparam in "${path_params[@]}"; do + regexp="(.*)(\{$pparam\})(.*)" + if [[ $path_template =~ $regexp ]]; then + path_template=${BASH_REMATCH[1]}${operation_parameters[$pparam]}${BASH_REMATCH[3]} + fi + done + + local query_request_part="" + + local query_parameter_count=${#query_params[@]} + local count=0 + for qparam in "${query_params[@]}"; do + # Get the array of parameter values + local parameter_values=($(echo "${operation_parameters[$qparam]}" | sed -e 's/'":::"'/\n/g' | while read line; do echo $line | sed 's/[\t ]/'":::"'/g'; done)) + local parameter_value="" + + # + # Check if the number of provided values is not less than minimum + # required + # + if [[ "$force" = false ]]; then + if [[ ${#parameter_values[@]} -lt ${operation_parameters_minimum_occurences["${operation}:::${qparam}"]} ]]; then + echo "Error: Too few values provided for '${qparam}' parameter" + exit 1 + fi + + # + # Check if the number of provided values is not more than maximum + # + if [[ ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} -gt 0 \ + && ${#parameter_values[@]} -gt ${operation_parameters_maximum_occurences["${operation}:::${qparam}"]} ]]; then + if [[ "$force" = false ]]; then + echo "Error: Too many values provided for '${qparam}' parameter" + exit 1 + fi + fi + fi + + # + # Append parameters without specific cardinality + # + if [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="&" + fi + vcount+=1 + done + # + # Append parameters specified as 'mutli' collections i.e. param=value1¶m=value2&... + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "multi" ]]; then + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qparam}=${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="&" + fi + vcount+=1 + done + # + # Append parameters specified as 'csv' collections i.e. param=value1,value2,... + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "csv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="," + fi + vcount+=1 + done + # + # Append parameters specified as 'ssv' collections i.e. param="value1 value2 ..." + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "ssv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+=" " + fi + vcount+=1 + done + # + # Append parameters specified as 'tsv' collections i.e. param="value1\tvalue2\t..." + # + elif [[ "${operation_parameters_collection_type["${operation}:::${qparam}"]}" == "tsv" ]]; then + parameter_value+="${qparam}=" + local vcount=0 + for qvalue in "${parameter_values[@]}"; do + parameter_value+="${qvalue}" + + if [[ $vcount -lt ${#parameter_values[@]}-1 ]]; then + parameter_value+="\t" + fi + vcount+=1 + done + fi + + if [[ -n "${parameter_value}" ]]; then + query_request_part+="${parameter_value}" + fi + + if [[ $count -lt $query_parameter_count-1 && -n "${parameter_value}" ]]; then + query_request_part+="&" + fi + + count+=1 + + done + + + # Now append query parameters - if any + if [[ -n "${query_request_part}" ]]; then + path_template+="?$(echo ${query_request_part} | sed s'/&$//')" + fi + + echo $path_template +} + + + +############################################################################### +# +# Print main help message +# +############################################################################### +print_help() { +cat <$(tput sgr0)] + [-ac|--accept $(tput setaf 2)$(tput sgr0)] [-ct,--content-type $(tput setaf 2)$(tput sgr0)] + [--host $(tput setaf 6)$(tput sgr0)] [--dry-run] $(tput setaf 3)$(tput sgr0) [-h|--help] [$(tput setaf 4)$(tput sgr0)] + [$(tput setaf 5)$(tput sgr0)] [$(tput setaf 5)$(tput sgr0)] + + - $(tput setaf 6)$(tput sgr0) - endpoint of the REST service without basepath + Can also be specified in PETSTORE_HOST environment variable. + - $(tput setaf 1)$(tput sgr0) - any valid cURL options can be passed before $(tput setaf 3)$(tput sgr0) + - $(tput setaf 2)$(tput sgr0) - either full mime-type or one of supported abbreviations: + (text, html, md, csv, css, rtf, json, xml, yaml, js, bin, + rdf, jpg, png, gif, bmp, tiff) + - $(tput setaf 4)$(tput sgr0) - HTTP headers can be passed in the form $(tput setaf 3)HEADER$(tput sgr0):$(tput setaf 4)VALUE$(tput sgr0) + - $(tput setaf 5)$(tput sgr0) - REST operation parameters can be passed in the following + forms: + * $(tput setaf 3)KEY$(tput sgr0)=$(tput setaf 4)VALUE$(tput sgr0) - path or query parameters + - $(tput setaf 5)$(tput sgr0) - simple JSON body content (first level only) can be build + using the following arguments: + * $(tput setaf 3)KEY$(tput sgr0)==$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": "$(tput setaf 4)VALUE$(tput sgr0)", ... }' + * $(tput setaf 3)KEY$(tput sgr0):=$(tput setaf 4)VALUE$(tput sgr0) - body parameters which will be added to body + JSON as '{ ..., "$(tput setaf 3)KEY$(tput sgr0)": $(tput setaf 4)VALUE$(tput sgr0), ... }' + +EOF + echo -e "$(tput bold)$(tput setaf 7)Authentication methods$(tput sgr0)" + echo -e "" + echo -e " - $(tput setaf 4)Api-key$(tput sgr0) - add '$(tput setaf 1)api_key:$(tput sgr0)' after $(tput setaf 3)$(tput sgr0)" + echo -e " or export $(tput setaf 1)PETSTORE_API_KEY=''$(tput sgr0)" + echo -e " - $(tput setaf 4)Basic AUTH$(tput sgr0) - add '-u :' before $(tput setaf 3)$(tput sgr0)" + echo -e " or export $(tput setaf 1)PETSTORE_BASIC_AUTH=':'$(tput sgr0)" + echo -e " - $(tput setaf 5)OAuth2 (flow: implicit)$(tput sgr0)" + echo -e " Authorization URL: " + echo -e " * http://petstore.swagger.io/api/oauth/dialog" + echo -e " Scopes:" + echo -e " * write:pets - modify pets in your account" + echo -e " * read:pets - read your pets" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Operations (grouped by tags)$(tput sgr0)" + echo "" + echo -e "$(tput bold)$(tput setaf 7)[fake]$(tput sgr0)" +read -d '' ops <$(tput sgr0)\t\t\t\tSpecify the host URL " +echo -e " \t\t\t\t(e.g. 'https://petstore.swagger.io')" + + echo -e " --force\t\t\t\tForce command invocation in spite of missing" + echo -e " \t\t\t\trequired parameters or wrong content type" + echo -e " --dry-run\t\t\t\tPrint out the cURL command without" + echo -e " \t\t\t\texecuting it" + echo -e " -ac,--accept $(tput setaf 3)$(tput sgr0)\t\tSet the 'Accept' header in the request" + echo -e " -ct,--content-type $(tput setaf 3)$(tput sgr0)\tSet the 'Content-type' header in " + echo -e " \tthe request" + echo "" +} + + +############################################################################## +# +# Print REST service description +# +############################################################################## +print_about() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)Swagger Petstore command line client (API version 1.0.0)$(tput sgr0)" + echo "" + echo -e "License: Apache 2.0" + echo -e "Contact: apiteam@swagger.io" + echo "" +read -d '' appdescription < 10. Other values will generated exceptions" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)orderId$(tput sgr0) $(tput setaf 4)[Integer]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - ID of pet that needs to be fetched $(tput setaf 3)Specify as: orderId=value$(tput sgr0)" | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 200 in + 1*) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid ID supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 404 in + 1*) + echo -e "$(tput setaf 7) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 404;Order not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for placeOrder operation +# +############################################################################## +print_placeOrder_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)placeOrder - Place an order for a pet$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)body$(tput sgr0) $(tput setaf 4)[]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - order placed for purchasing the pet" | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 200 in + 1*) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid Order$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for createUser operation +# +############################################################################## +print_createUser_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)createUser - Create user$(tput sgr0)" + echo -e "" + echo -e "This can only be done by the logged in user." | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)body$(tput sgr0) $(tput setaf 4)[]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - Created user object" | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 0 in + 1*) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for createUsersWithArrayInput operation +# +############################################################################## +print_createUsersWithArrayInput_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)createUsersWithArrayInput - Creates list of users with given input array$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)body$(tput sgr0) $(tput setaf 4)[]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - List of user object" | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 0 in + 1*) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for createUsersWithListInput operation +# +############################################################################## +print_createUsersWithListInput_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)createUsersWithListInput - Creates list of users with given input array$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)body$(tput sgr0) $(tput setaf 4)[]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - List of user object" | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 0 in + 1*) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for deleteUser operation +# +############################################################################## +print_deleteUser_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)deleteUser - Delete user$(tput sgr0)" + echo -e "" + echo -e "This can only be done by the logged in user." | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)username$(tput sgr0) $(tput setaf 4)[String]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - The name that needs to be deleted $(tput setaf 3)Specify as: username=value$(tput sgr0)" | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 404 in + 1*) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for getUserByName operation +# +############################################################################## +print_getUserByName_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)getUserByName - Get user by user name$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)username$(tput sgr0) $(tput setaf 4)[String]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - The name that needs to be fetched. Use user1 for testing. $(tput setaf 3)Specify as: username=value$(tput sgr0)" | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 200 in + 1*) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid username supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 404 in + 1*) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for loginUser operation +# +############################################################################## +print_loginUser_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)loginUser - Logs user into the system$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)username$(tput sgr0) $(tput setaf 4)[String]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - The user name for login$(tput setaf 3) Specify as: username=value$(tput sgr0)" \ + | fold -sw 80 | sed '2,$s/^/ /' + echo -e " * $(tput setaf 2)password$(tput sgr0) $(tput setaf 4)[String]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - The password for login in clear text$(tput setaf 3) Specify as: password=value$(tput sgr0)" \ + | fold -sw 80 | sed '2,$s/^/ /' + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 200 in + 1*) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 200;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + echo -e " $(tput bold)$(tput setaf 7)Response headers$(tput sgr0)" + echo -e " $(tput setaf 4)X-Rate-Limit$(tput sgr0) - calls per hour allowed by the user" | fold -sw 80 | sed '2,$s/^/ /' + echo -e " $(tput setaf 4)X-Expires-After$(tput sgr0) - date in UTC when toekn expires" | fold -sw 80 | sed '2,$s/^/ /' + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid username/password supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for logoutUser operation +# +############################################################################## +print_logoutUser_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)logoutUser - Logs out current logged in user session$(tput sgr0)" + echo -e "" + echo -e "" | fold -sw 80 + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 0 in + 1*) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 0;successful operation$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} +############################################################################## +# +# Print help for updateUser operation +# +############################################################################## +print_updateUser_help() { + echo "" + echo -e "$(tput bold)$(tput setaf 7)updateUser - Updated user$(tput sgr0)" + echo -e "" + echo -e "This can only be done by the logged in user." | fold -sw 80 + echo -e "" + echo -e "$(tput bold)$(tput setaf 7)Parameters$(tput sgr0)" + echo -e " * $(tput setaf 2)username$(tput sgr0) $(tput setaf 4)[String]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - name that need to be deleted $(tput setaf 3)Specify as: username=value$(tput sgr0)" | fold -sw 80 | sed '2,$s/^/ /' + echo -e " * $(tput setaf 2)body$(tput sgr0) $(tput setaf 4)[]$(tput sgr0) $(tput setaf 1)(required)$(tput sgr0)$(tput sgr0) - Updated user object" | fold -sw 80 | sed '2,$s/^/ /' + echo -e "" + echo "" + echo -e "$(tput bold)$(tput setaf 7)Responses$(tput sgr0)" + case 400 in + 1*) + echo -e "$(tput setaf 7) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 400;Invalid user supplied$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac + case 404 in + 1*) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 2*) + echo -e "$(tput setaf 2) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 3*) + echo -e "$(tput setaf 3) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 4*) + echo -e "$(tput setaf 1) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + 5*) + echo -e "$(tput setaf 5) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + *) + echo -e "$(tput setaf 7) 404;User not found$(tput sgr0)" | column -t -s ';' | fold -sw 80 | sed '2,$s/^/ /' + ;; + esac +} + + +############################################################################## +# +# Call testClientModel operation +# +############################################################################## +call_testClientModel() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/fake" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/fake" path_parameter_names query_parameter_names) + local method="PATCH" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + if [[ -z $header_content_type ]]; then + header_content_type="application/json" + fi + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + echo "Error: Request's content-type not specified!!!" + echo "This operation expects content-type in one of the following formats:" + echo -e "\t- application/json" + echo "" + echo "Use '--content-type' to set proper content type" + exit 1 + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call testEndpointParameters operation +# +############################################################################## +call_testEndpointParameters() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/fake" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/fake" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call testEnumParameters operation +# +############################################################################## +call_testEnumParameters() { + local path_parameter_names=() + local query_parameter_names=(enum_query_string_array enum_query_string enum_query_integer) + + if [[ $force = false ]]; then + validate_request_parameters "/v2/fake" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/fake" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call addPet operation +# +############################################################################## +call_addPet() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + echo "Error: Request's content-type not specified!!!" + echo "This operation expects content-type in one of the following formats:" + echo -e "\t- application/json" + echo -e "\t- application/xml" + echo "" + echo "Use '--content-type' to set proper content type" + exit 1 + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call deletePet operation +# +############################################################################## +call_deletePet() { + local path_parameter_names=(petId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/{petId}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/{petId}" path_parameter_names query_parameter_names) + local method="DELETE" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call findPetsByStatus operation +# +############################################################################## +call_findPetsByStatus() { + local path_parameter_names=() + local query_parameter_names=(status) + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/findByStatus" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/findByStatus" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call findPetsByTags operation +# +############################################################################## +call_findPetsByTags() { + local path_parameter_names=() + local query_parameter_names=(tags) + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/findByTags" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/findByTags" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call getPetById operation +# +############################################################################## +call_getPetById() { + local path_parameter_names=(petId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/{petId}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/{petId}" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call updatePet operation +# +############################################################################## +call_updatePet() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet" path_parameter_names query_parameter_names) + local method="PUT" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + echo "Error: Request's content-type not specified!!!" + echo "This operation expects content-type in one of the following formats:" + echo -e "\t- application/json" + echo -e "\t- application/xml" + echo "" + echo "Use '--content-type' to set proper content type" + exit 1 + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call updatePetWithForm operation +# +############################################################################## +call_updatePetWithForm() { + local path_parameter_names=(petId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/{petId}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/{petId}" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call uploadFile operation +# +############################################################################## +call_uploadFile() { + local path_parameter_names=(petId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/pet/{petId}/uploadImage" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/pet/{petId}/uploadImage" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call deleteOrder operation +# +############################################################################## +call_deleteOrder() { + local path_parameter_names=(orderId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/store/order/{orderId}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/store/order/{orderId}" path_parameter_names query_parameter_names) + local method="DELETE" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call getInventory operation +# +############################################################################## +call_getInventory() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/store/inventory" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/store/inventory" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call getOrderById operation +# +############################################################################## +call_getOrderById() { + local path_parameter_names=(orderId) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/store/order/{orderId}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/store/order/{orderId}" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call placeOrder operation +# +############################################################################## +call_placeOrder() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/store/order" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/store/order" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call createUser operation +# +############################################################################## +call_createUser() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call createUsersWithArrayInput operation +# +############################################################################## +call_createUsersWithArrayInput() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/createWithArray" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/createWithArray" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call createUsersWithListInput operation +# +############################################################################## +call_createUsersWithListInput() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/createWithList" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/createWithList" path_parameter_names query_parameter_names) + local method="POST" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + +############################################################################## +# +# Call deleteUser operation +# +############################################################################## +call_deleteUser() { + local path_parameter_names=(username) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/{username}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/{username}" path_parameter_names query_parameter_names) + local method="DELETE" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call getUserByName operation +# +############################################################################## +call_getUserByName() { + local path_parameter_names=(username) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/{username}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/{username}" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call loginUser operation +# +############################################################################## +call_loginUser() { + local path_parameter_names=() + local query_parameter_names=(username password) + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/login" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/login" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call logoutUser operation +# +############################################################################## +call_logoutUser() { + local path_parameter_names=() + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/logout" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/logout" path_parameter_names query_parameter_names) + local method="GET" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\"" + fi +} + +############################################################################## +# +# Call updateUser operation +# +############################################################################## +call_updateUser() { + local path_parameter_names=(username) + local query_parameter_names=() + + if [[ $force = false ]]; then + validate_request_parameters "/v2/user/{username}" path_parameter_names query_parameter_names + fi + + local path=$(build_request_path "/v2/user/{username}" path_parameter_names query_parameter_names) + local method="PUT" + local headers_curl=$(header_arguments_to_curl) + if [[ -n $header_accept ]]; then + headers_curl="${headers_curl} -H 'Accept: ${header_accept}'" + fi + + local basic_auth_option="" + if [[ -n $basic_auth_credential ]]; then + basic_auth_option="-u ${basic_auth_credential}" + fi + local body_json_curl="" + + # + # Check if the user provided 'Content-type' headers in the + # command line. If not try to set them based on the Swagger specification + # if values produces and consumes are defined unambigously + # + + + if [[ -z $header_content_type && "$force" = false ]]; then + : + else + headers_curl="${headers_curl} -H 'Content-type: ${header_content_type}'" + fi + + + # + # If we have received some body content over pipe, pass it from the + # temporary file to cURL + # + if [[ -n $body_content_temp_file ]]; then + if [[ "$print_curl" = true ]]; then + echo "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + else + eval "cat ${body_content_temp_file} | curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} \"${host}${path}\" -d @-" + fi + rm "${body_content_temp_file}" + # + # If not, try to build the content body from arguments KEY==VALUE and KEY:=VALUE + # + else + body_json_curl=$(body_parameters_to_json) + if [[ "$print_curl" = true ]]; then + echo "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + else + eval "curl ${basic_auth_option} ${curl_arguments} ${headers_curl} -X ${method} ${body_json_curl} \"${host}${path}\"" + fi + fi +} + + + +############################################################################## +# +# Main +# +############################################################################## + + +# Check dependencies +type curl >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'cURL' installed."; exit 1; } +type sed >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'sed' installed."; exit 1; } +type column >/dev/null 2>&1 || { echo >&2 "Error: You do not have 'bsdmainutils' installed."; exit 1; } + +# +# Process command line +# +# Pass all arguemnts before 'operation' to cURL except the ones we override +# +take_user=false +take_host=false +take_accept_header=false +take_contenttype_header=false + +for key in "$@"; do +# Take the value of -u|--user argument +if [[ "$take_user" = true ]]; then + basic_auth_credential="$key" + take_user=false + continue +fi +# Take the value of --host argument +if [[ "$take_host" = true ]]; then + host="$key" + take_host=false + continue +fi +# Take the value of --accept argument +if [[ "$take_accept_header" = true ]]; then + header_accept=$(lookup_mime_type "$key") + take_accept_header=false + continue +fi +# Take the value of --content-type argument +if [[ "$take_contenttype_header" = true ]]; then + header_content_type=$(lookup_mime_type "$key") + take_contenttype_header=false + continue +fi +case $key in + -h|--help) + if [[ "x$operation" == "x" ]]; then + print_help + exit 0 + else + eval "print_${operation}_help" + exit 0 + fi + ;; + -V|--version) + print_version + exit 0 + ;; + --about) + print_about + exit 0 + ;; + -u|--user) + take_user=true + ;; + --host) + take_host=true + ;; + --force) + force=true + ;; + -ac|--accept) + take_accept_header=true + ;; + -ct|--content-type) + take_contenttype_header=true + ;; + --dry-run) + print_curl=true + ;; + testClientModel) + operation="testClientModel" + ;; + testEndpointParameters) + operation="testEndpointParameters" + ;; + testEnumParameters) + operation="testEnumParameters" + ;; + addPet) + operation="addPet" + ;; + deletePet) + operation="deletePet" + ;; + findPetsByStatus) + operation="findPetsByStatus" + ;; + findPetsByTags) + operation="findPetsByTags" + ;; + getPetById) + operation="getPetById" + ;; + updatePet) + operation="updatePet" + ;; + updatePetWithForm) + operation="updatePetWithForm" + ;; + uploadFile) + operation="uploadFile" + ;; + deleteOrder) + operation="deleteOrder" + ;; + getInventory) + operation="getInventory" + ;; + getOrderById) + operation="getOrderById" + ;; + placeOrder) + operation="placeOrder" + ;; + createUser) + operation="createUser" + ;; + createUsersWithArrayInput) + operation="createUsersWithArrayInput" + ;; + createUsersWithListInput) + operation="createUsersWithListInput" + ;; + deleteUser) + operation="deleteUser" + ;; + getUserByName) + operation="getUserByName" + ;; + loginUser) + operation="loginUser" + ;; + logoutUser) + operation="logoutUser" + ;; + updateUser) + operation="updateUser" + ;; + *==*) + # Parse body arguments and convert them into top level + # JSON properties passed in the body content as strings + if [[ "$operation" ]]; then + IFS='==' read body_key sep body_value <<< "$key" + body_parameters[${body_key}]="\"${body_value}\"" + fi + ;; + *:=*) + # Parse body arguments and convert them into top level + # JSON properties passed in the body content without qoutes + if [[ "$operation" ]]; then + IFS=':=' read body_key sep body_value <<< "$key" + body_parameters[${body_key}]=${body_value} + fi + ;; + *:*) + # Parse header arguments and convert them into curl + # only after the operation argument + if [[ "$operation" ]]; then + IFS=':' read header_name header_value <<< "$key" + # + # If the header key is the same as the api_key expected by API in the + # header, override the ${apikey_auth_credential} variable + # + if [[ $header_name == "api_key" ]]; then + apikey_auth_credential=$header_value + fi + header_arguments[$header_name]=$header_value + else + curl_arguments+=" $key" + fi + ;; + -) + body_content_temp_file=$(mktemp) + cat - > $body_content_temp_file + ;; + *=*) + # Parse operation arguments and convert them into curl + # only after the operation argument + if [[ "$operation" ]]; then + IFS='=' read parameter_name parameter_value <<< "$key" + if [[ -z "${operation_parameters[$parameter_name]+foo}" ]]; then + operation_parameters[$parameter_name]=$(url_escape "${parameter_value}") + else + operation_parameters[$parameter_name]+=":::"$(url_escape "${parameter_value}") + fi + else + curl_arguments+=" $key" + fi + ;; + *) + # If we are before the operation, treat the arguments as cURL arguments + if [[ "x$operation" == "x" ]]; then + # Maintain quotes around cURL arguments if necessary + space_regexp="[[:space:]]" + if [[ $key =~ $space_regexp ]]; then + curl_arguments+=" \"$key\"" + else + curl_arguments+=" $key" + fi + fi + ;; +esac +done + + +# Check if user provided host name +if [[ -z "$host" ]]; then + echo "Error: No hostname provided!!!" + echo "Check usage: '${script_name} --help'" + exit 1 +fi + +# Check if user specified operation ID +if [[ -z "$operation" ]]; then + echo "Error: No operation specified!" + echo "Check available operations: '${script_name} --help'" + exit 1 +fi + + +# Run cURL command based on the operation ID +case $operation in + testClientModel) + call_testClientModel + ;; + testEndpointParameters) + call_testEndpointParameters + ;; + testEnumParameters) + call_testEnumParameters + ;; + addPet) + call_addPet + ;; + deletePet) + call_deletePet + ;; + findPetsByStatus) + call_findPetsByStatus + ;; + findPetsByTags) + call_findPetsByTags + ;; + getPetById) + call_getPetById + ;; + updatePet) + call_updatePet + ;; + updatePetWithForm) + call_updatePetWithForm + ;; + uploadFile) + call_uploadFile + ;; + deleteOrder) + call_deleteOrder + ;; + getInventory) + call_getInventory + ;; + getOrderById) + call_getOrderById + ;; + placeOrder) + call_placeOrder + ;; + createUser) + call_createUser + ;; + createUsersWithArrayInput) + call_createUsersWithArrayInput + ;; + createUsersWithListInput) + call_createUsersWithListInput + ;; + deleteUser) + call_deleteUser + ;; + getUserByName) + call_getUserByName + ;; + loginUser) + call_loginUser + ;; + logoutUser) + call_logoutUser + ;; + updateUser) + call_updateUser + ;; + *) + echo "Error: Unknown operation: $operation" + echo "" + print_help + exit 1 +esac diff --git a/samples/client/petstore/bash/petstore-cli.bash-completion b/samples/client/petstore/bash/petstore-cli.bash-completion new file mode 100644 index 00000000000..f8b11cde5b2 --- /dev/null +++ b/samples/client/petstore/bash/petstore-cli.bash-completion @@ -0,0 +1,287 @@ +# petstore-cli completion -*- shell-script -*- + +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! +# ! +# ! Note: +# ! +# ! THIS SCRIPT HAS BEEN AUTOMATICALLY GENERATED USING +# ! swagger-codegen (https://github.com/swagger-api/swagger-codegen) +# ! FROM SWAGGER SPECIFICATION IN JSON. +# ! +# ! Generated on: 2017-02-06T21:48:13.013+01:00 +# ! +# ! +# ! System wide installation: +# ! +# ! $ sudo cp petstore-cli.bash-completion /etc/bash-completion.d/petstore-cli +# ! +# ! +# ! User home installation (add this line to .bash_profile): +# ! +# ! [ -r ~/petstore-cli.bash-completion ] && source ~/petstore-cli.bash-completion +# ! +# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +declare -A mime_type_abbreviations +# text/* +mime_type_abbreviations["text"]="text/plain" +mime_type_abbreviations["html"]="text/html" +mime_type_abbreviations["md"]="text/x-markdown" +mime_type_abbreviations["csv"]="text/csv" +mime_type_abbreviations["css"]="text/css" +mime_type_abbreviations["rtf"]="text/rtf" +# application/* +mime_type_abbreviations["json"]="application/json" +mime_type_abbreviations["xml"]="application/xml" +mime_type_abbreviations["yaml"]="application/yaml" +mime_type_abbreviations["js"]="application/javascript" +mime_type_abbreviations["bin"]="application/octet-stream" +mime_type_abbreviations["rdf"]="application/rdf+xml" +# image/* +mime_type_abbreviations["jpg"]="image/jpeg" +mime_type_abbreviations["png"]="image/png" +mime_type_abbreviations["gif"]="image/gif" +mime_type_abbreviations["bmp"]="image/bmp" +mime_type_abbreviations["tiff"]="image/tiff" + + +# +# Check if this is OSX, if so defined custom init_completion +# +if [[ `uname` =~ "Darwin" ]]; then + __osx_init_completion() + { + COMPREPLY=() + _get_comp_words_by_ref cur prev words cword + } +fi + +_petstore-cli() +{ + local cur + local prev + local words + local cword + + # The reference of currently selected REST operation + local operation="" + + # The list of available operation in the REST service + # It's modelled as an associative array for efficient key lookup + declare -A operations + operations["testClientModel"]=1 + operations["testEndpointParameters"]=1 + operations["testEnumParameters"]=1 + operations["addPet"]=1 + operations["deletePet"]=1 + operations["findPetsByStatus"]=1 + operations["findPetsByTags"]=1 + operations["getPetById"]=1 + operations["updatePet"]=1 + operations["updatePetWithForm"]=1 + operations["uploadFile"]=1 + operations["deleteOrder"]=1 + operations["getInventory"]=1 + operations["getOrderById"]=1 + operations["placeOrder"]=1 + operations["createUser"]=1 + operations["createUsersWithArrayInput"]=1 + operations["createUsersWithListInput"]=1 + operations["deleteUser"]=1 + operations["getUserByName"]=1 + operations["loginUser"]=1 + operations["logoutUser"]=1 + operations["updateUser"]=1 + + # An associative array of operations to their parameters + # Only include path, query and header parameters + declare -A operation_parameters + operation_parameters["testClientModel"]="" + operation_parameters["testEndpointParameters"]="" + operation_parameters["testEnumParameters"]="enum_query_string_array= enum_query_string= enum_query_integer= enum_header_string_array: enum_header_string: " + operation_parameters["addPet"]="" + operation_parameters["deletePet"]="petId= api_key: " + operation_parameters["findPetsByStatus"]="status= " + operation_parameters["findPetsByTags"]="tags= " + operation_parameters["getPetById"]="petId= " + operation_parameters["updatePet"]="" + operation_parameters["updatePetWithForm"]="petId= " + operation_parameters["uploadFile"]="petId= " + operation_parameters["deleteOrder"]="orderId= " + operation_parameters["getInventory"]="" + operation_parameters["getOrderById"]="orderId= " + operation_parameters["placeOrder"]="" + operation_parameters["createUser"]="" + operation_parameters["createUsersWithArrayInput"]="" + operation_parameters["createUsersWithListInput"]="" + operation_parameters["deleteUser"]="username= " + operation_parameters["getUserByName"]="username= " + operation_parameters["loginUser"]="username= password= " + operation_parameters["logoutUser"]="" + operation_parameters["updateUser"]="username= " + + # An associative array of possible values for enum parameters + declare -A operation_parameters_enum_values + + # + # Check if this is OSX and use special __osx_init_completion function + # + if [[ `uname` =~ "Darwin" ]]; then + __osx_init_completion || return + else + _init_completion -s || return + fi + + + # Check if operation is already in the command line provided + for word in "${words[@]}"; do + if [[ -n $word && ${operations[$word]} ]]; then + operation="${word}" + fi + done + + if [[ -z $operation ]]; then + case $prev in + --ciphers|--connect-timeout|-C|--continue-at|-F|--form|--form-string|\ + --ftp-account|--ftp-alternative-to-user|-P|--ftp-port|-H|--header|-h|\ + --help|--hostpubmd5|--keepalive-time|--krb|--limit-rate|--local-port|\ + --mail-from|--mail-rcpt|--max-filesize|--max-redirs|-m|--max-time|\ + --pass|--proto|--proto-redir|--proxy-user|--proxy1.0|-Q|--quote|-r|\ + --range|-X|--request|--retry|--retry-delay|--retry-max-time|\ + --socks5-gssapi-service|-t|--telnet-option|--tftp-blksize|-z|\ + --time-cond|--url|-u|--user|-A|--user-agent|-V|--version|-w|\ + --write-out|--resolve|--tlsuser|--tlspassword|--about) + return + ;; + -K|--config|-b|--cookie|-c|--cookie-jar|-D|--dump-header|--egd-file|\ + --key|--libcurl|-o|--output|--random-file|-T|--upload-file|--trace|\ + --trace-ascii|--netrc-file) + _filedir + return + ;; + --cacert|-E|--cert) + _filedir '@(c?(e)rt|cer|pem|der)' + return + ;; + --capath) + _filedir -d + return + ;; + --cert-type|--key-type) + COMPREPLY=( $( compgen -W 'DER PEM ENG' -- "$cur" ) ) + return + ;; + --crlfile) + _filedir crl + return + ;; + -d|--data|--data-ascii|--data-binary|--data-urlencode) + if [[ $cur == \@* ]]; then + cur=${cur:1} + _filedir + COMPREPLY=( "${COMPREPLY[@]/#/@}" ) + fi + return + ;; + --delegation) + COMPREPLY=( $( compgen -W 'none policy always' -- "$cur" ) ) + return + ;; + --engine) + COMPREPLY=( $( compgen -W 'list' -- "$cur" ) ) + return + ;; + --ftp-method) + COMPREPLY=( $( compgen -W 'multicwd nocwd singlecwd' -- "$cur" ) ) + return + ;; + --ftp-ssl-ccc-mode) + COMPREPLY=( $( compgen -W 'active passive' -- "$cur" ) ) + return + ;; + --interface) + _available_interfaces -a + return + ;; + -x|--proxy|--socks4|--socks4a|--socks5|--socks5-hostname) + _known_hosts_real + return + ;; + --pubkey) + _filedir pub + return + ;; + --stderr) + COMPREPLY=( $( compgen -W '-' -- "$cur" ) ) + _filedir + return + ;; + --tlsauthtype) + COMPREPLY=( $( compgen -W 'SRP' -- "$cur" ) ) + return + ;; + --host) + COMPREPLY=( $( compgen -W 'http:// https://' -- "$cur" ) ) + return + ;; + -ct|--content-type|-ac|--accept) + COMPREPLY=( $( compgen -W '${!mime_type_abbreviations[*]}' -- "$cur" ) ) + return + ;; + esac + fi + + # + # Complete the server address based on ~/.ssh/known_hosts + # and ~/.ssh/config + # + local prefix=${COMP_WORDS[COMP_CWORD-2]} + local colon=${COMP_WORDS[COMP_CWORD-1]} + if [[ "$colon" == ":" && ( $prefix == "https" || $prefix == "http" ) ]]; then + COMPREPLY=() + local comp_ssh_hosts=`[[ -f ~/.ssh/known_hosts ]] && \ + ( cat ~/.ssh/known_hosts | \ + grep '^[a-zA-Z0-9]' | \ + cut -f 1 -d ' ' | \ + sed -e s/,.*//g | \ + grep -v ^# | \ + uniq | \ + grep -v "\[" ) ; + [[ -f ~/.ssh/config ]] && \ + ( cat ~/.ssh/config | \ + grep "^Host " | \ + awk '{print $2}' )` + COMPREPLY=( $( compgen -P '//' -W '${comp_ssh_hosts}' -- "${cur:2}") ) + return + fi + + # + # Complete the petstore-cli and cURL's arguments + # + if [[ $cur == -* ]]; then + COMPREPLY=( $( compgen -W '$(_parse_help curl) $(_parse_help $1)' -- "$cur" ) ) + return + fi + + # + # If the argument starts with a letter this could be either an operation + # or an operation parameter + # When $cur is empty, suggest the list of operations by default + # + if [[ $cur =~ ^[A-Za-z_0-9]* ]]; then + # If operation has not been yet selected, suggest the list of operations + # otherwise suggest arguments of this operation as declared in the + # Swagger specification + if [[ -z $operation ]]; then + COMPREPLY=( $(compgen -W '${!operations[*]}' -- ${cur}) ) + else + COMPREPLY=( $(compgen -W '${operation_parameters[$operation]}' -- ${cur}) ) + compopt -o nospace + fi + return + fi + +} && +complete -F _petstore-cli petstore-cli + +# ex: ts=4 sw=4 et filetype=sh diff --git a/samples/client/petstore/bash/pom.xml b/samples/client/petstore/bash/pom.xml new file mode 100644 index 00000000000..fc8237d186c --- /dev/null +++ b/samples/client/petstore/bash/pom.xml @@ -0,0 +1,47 @@ + + 4.0.0 + io.swagger + BashPetstoreClientTests + pom + 1.0-SNAPSHOT + Bash Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + bats-test + integration-test + + exec + + + bats + + --tap + tests/petstore_test.sh + + + + + + + + diff --git a/samples/client/petstore/bash/tests/petstore_test.sh b/samples/client/petstore/bash/tests/petstore_test.sh new file mode 100644 index 00000000000..139679eb3ee --- /dev/null +++ b/samples/client/petstore/bash/tests/petstore_test.sh @@ -0,0 +1,102 @@ +#!/usr/bin/env bats + + +export PETSTORE_CLI="petstore-cli" + +export PETSTORE_HOST="http://petstore.swagger.io" + + +# +# Tests for parameter handling and validation +# +@test "addPet without host" { + unset PETSTORE_HOST + run bash $PETSTORE_CLI -ac xml -ct json \ + addPet id:=123321 name==lucky status==available + [[ "$output" =~ "Error: No hostname provided!!!" ]] +} + +@test "addPet without content type" { + run bash $PETSTORE_CLI -ac xml --host $PETSTORE_HOST \ + addPet id:=123321 name==lucky status==available + [[ "$output" =~ "Error: Request's content-type not specified!" ]] +} + +@test "fakeOperation invalid operation name" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io fakeOperation" + [[ "$output" =~ "Error: No operation specified!" ]] +} + +@test "findPetsByStatus basic auth" { + run bash \ + -c "bash $PETSTORE_CLI -u alice:secret --host http://petstore.swagger.io findPetsByStatus status=s1 --dry-run" + [[ "$output" =~ "-u alice:secret" ]] +} + +@test "findPetsByStatus api key" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus status=s1 api_key:1234 --dry-run" + [[ "$output" =~ "-H \"api_key: 1234\"" ]] +} + +@test "findPetsByStatus empty api key" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus status=s1 --dry-run" + [[ ! "$output" =~ "-H \"api_key:" ]] +} + + + + +@test "findPetsByStatus too few values" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus" + [[ "$output" =~ "Error: Too few values" ]] +} + +@test "findPetsByTags too few values" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByTags" + [[ "$output" =~ "Error: Too few values" ]] +} + +@test "findPetsByStatus status with space" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByStatus \ + status=available status=\"gone test\" --dry-run" + [[ "$output" =~ "status=available,gone%20test" ]] +} + +@test "findPetsByStatus collection csv" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByTags \ + tags=TAG1 tags=TAG2 --dry-run" + [[ "$output" =~ "tags=TAG1,TAG2" ]] +} + +@test "findPetsByStatus collection csv with space and question mark" { + run bash \ + -c "bash $PETSTORE_CLI --host http://petstore.swagger.io findPetsByTags \ + tags=TAG1 tags=\"TAG2 TEST\" tags=TAG3?TEST --dry-run" + [[ "$output" =~ "tags=TAG1,TAG2%20TEST,TAG3%3FTEST" ]] +} + +# +# Operations calling the service and checking result +# +@test "addPet from parameters" { + run bash $PETSTORE_CLI -ct json -ac xml \ + addPet id:=123321 name==lucky status==available + [[ "$output" =~ "123321" ]] +} + +@test "addPet from pipe" { + run bash \ + -c "echo '{\"id\": 37567, \"name\": \"lucky\", \"status\": \"available\"}' | \ + bash $PETSTORE_CLI -ct json -ac xml addPet -" + [[ "$output" =~ "37567" ]] +} + + + diff --git a/samples/client/petstore/cpprest/ApiClient.cpp b/samples/client/petstore/cpprest/ApiClient.cpp index c7687e2851b..00798258261 100644 --- a/samples/client/petstore/cpprest/ApiClient.cpp +++ b/samples/client/petstore/cpprest/ApiClient.cpp @@ -52,6 +52,11 @@ utility::string_t ApiClient::parameterToString(int32_t value) return utility::conversions::to_string_t(std::to_string(value)); } +utility::string_t ApiClient::parameterToString(const utility::datetime &value) +{ + return utility::conversions::to_string_t(value.to_string(utility::datetime::ISO_8601)); +} + pplx::task ApiClient::callApi( const utility::string_t& path, const utility::string_t& method, diff --git a/samples/client/petstore/cpprest/ApiClient.h b/samples/client/petstore/cpprest/ApiClient.h index 81b38cb09c5..1678e9e8c51 100644 --- a/samples/client/petstore/cpprest/ApiClient.h +++ b/samples/client/petstore/cpprest/ApiClient.h @@ -50,6 +50,7 @@ public: static utility::string_t parameterToString(utility::string_t value); static utility::string_t parameterToString(int32_t value); static utility::string_t parameterToString(int64_t value); + static utility::string_t parameterToString(const utility::datetime &value); template static utility::string_t parameterToArrayString(std::vector value) diff --git a/samples/client/petstore/cpprest/api/PetApi.cpp b/samples/client/petstore/cpprest/api/PetApi.cpp index aa9aab9d89c..c423c43e173 100644 --- a/samples/client/petstore/cpprest/api/PetApi.cpp +++ b/samples/client/petstore/cpprest/api/PetApi.cpp @@ -438,7 +438,7 @@ pplx::task>> PetApi::findPetsByTags(std::vector { - queryParams[U("tags")] = ApiClient::parameterToArrayString(tags); + queryParams[U("tags")] = ApiClient::parameterToArrayString<>(tags); } std::shared_ptr httpBody; diff --git a/samples/client/petstore/cpprest/api/PetApi.h b/samples/client/petstore/cpprest/api/PetApi.h index d60c3c80fca..0a783c66a29 100644 --- a/samples/client/petstore/cpprest/api/PetApi.h +++ b/samples/client/petstore/cpprest/api/PetApi.h @@ -22,10 +22,10 @@ #include "ApiClient.h" -#include "ApiResponse.h" -#include "HttpContent.h" #include "Pet.h" #include +#include "ApiResponse.h" +#include "HttpContent.h" namespace io { namespace swagger { diff --git a/samples/client/petstore/cpprest/api/StoreApi.h b/samples/client/petstore/cpprest/api/StoreApi.h index 60ec088b326..99cbedea460 100644 --- a/samples/client/petstore/cpprest/api/StoreApi.h +++ b/samples/client/petstore/cpprest/api/StoreApi.h @@ -22,9 +22,9 @@ #include "ApiClient.h" -#include "Order.h" -#include #include +#include +#include "Order.h" namespace io { namespace swagger { diff --git a/samples/client/petstore/cpprest/model/Category.cpp b/samples/client/petstore/cpprest/model/Category.cpp index bdb6d8e894a..9c0f21b3b22 100644 --- a/samples/client/petstore/cpprest/model/Category.cpp +++ b/samples/client/petstore/cpprest/model/Category.cpp @@ -21,7 +21,7 @@ namespace model { Category::Category() { - m_Id = 0; + m_Id = 0L; m_IdIsSet = false; m_Name = U(""); m_NameIsSet = false; diff --git a/samples/client/petstore/cpprest/model/Order.cpp b/samples/client/petstore/cpprest/model/Order.cpp index e21d867cd7e..07e815fa90c 100644 --- a/samples/client/petstore/cpprest/model/Order.cpp +++ b/samples/client/petstore/cpprest/model/Order.cpp @@ -21,9 +21,9 @@ namespace model { Order::Order() { - m_Id = 0; + m_Id = 0L; m_IdIsSet = false; - m_PetId = 0; + m_PetId = 0L; m_PetIdIsSet = false; m_Quantity = 0; m_QuantityIsSet = false; diff --git a/samples/client/petstore/cpprest/model/Pet.cpp b/samples/client/petstore/cpprest/model/Pet.cpp index 51dd6d883e9..74b707a4c26 100644 --- a/samples/client/petstore/cpprest/model/Pet.cpp +++ b/samples/client/petstore/cpprest/model/Pet.cpp @@ -21,7 +21,7 @@ namespace model { Pet::Pet() { - m_Id = 0; + m_Id = 0L; m_IdIsSet = false; m_CategoryIsSet = false; m_Name = U(""); diff --git a/samples/client/petstore/cpprest/model/Pet.h b/samples/client/petstore/cpprest/model/Pet.h index 91704dc9ed7..065c46bdb93 100644 --- a/samples/client/petstore/cpprest/model/Pet.h +++ b/samples/client/petstore/cpprest/model/Pet.h @@ -22,10 +22,10 @@ #include "ModelBase.h" -#include "Category.h" -#include -#include #include "Tag.h" +#include +#include "Category.h" +#include namespace io { namespace swagger { diff --git a/samples/client/petstore/cpprest/model/Tag.cpp b/samples/client/petstore/cpprest/model/Tag.cpp index 3cb0798c99e..466ca0d29da 100644 --- a/samples/client/petstore/cpprest/model/Tag.cpp +++ b/samples/client/petstore/cpprest/model/Tag.cpp @@ -21,7 +21,7 @@ namespace model { Tag::Tag() { - m_Id = 0; + m_Id = 0L; m_IdIsSet = false; m_Name = U(""); m_NameIsSet = false; diff --git a/samples/client/petstore/cpprest/model/User.cpp b/samples/client/petstore/cpprest/model/User.cpp index 1ea09f35b50..e9c5e969673 100644 --- a/samples/client/petstore/cpprest/model/User.cpp +++ b/samples/client/petstore/cpprest/model/User.cpp @@ -21,7 +21,7 @@ namespace model { User::User() { - m_Id = 0; + m_Id = 0L; m_IdIsSet = false; m_Username = U(""); m_UsernameIsSet = false; diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md index 6cd17fe5c76..edb62683e0f 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/README.md @@ -6,8 +6,8 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build date: 2016-12-09T16:46:08.135+08:00 -- Build package: class io.swagger.codegen.languages.CsharpDotNet2ClientCodegen +- Build date: 2017-01-22T16:52:29.599+08:00 +- Build package: io.swagger.codegen.languages.CsharpDotNet2ClientCodegen ## Frameworks supported diff --git a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln index b7c1013e434..4e593616590 100644 --- a/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClient/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{959A8039-E3B9-4660-A666-840955E4520C}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{45175ABF-4F24-48D0-B481-B1A2D9B8649E}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{959A8039-E3B9-4660-A666-840955E4520C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{959A8039-E3B9-4660-A666-840955E4520C}.Debug|Any CPU.Build.0 = Debug|Any CPU -{959A8039-E3B9-4660-A666-840955E4520C}.Release|Any CPU.ActiveCfg = Release|Any CPU -{959A8039-E3B9-4660-A666-840955E4520C}.Release|Any CPU.Build.0 = Release|Any CPU +{45175ABF-4F24-48D0-B481-B1A2D9B8649E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{45175ABF-4F24-48D0-B481-B1A2D9B8649E}.Debug|Any CPU.Build.0 = Debug|Any CPU +{45175ABF-4F24-48D0-B481-B1A2D9B8649E}.Release|Any CPU.ActiveCfg = Release|Any CPU +{45175ABF-4F24-48D0-B481-B1A2D9B8649E}.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 diff --git a/samples/client/petstore/csharp/SwaggerClient/README.md b/samples/client/petstore/csharp/SwaggerClient/README.md index 67a001aa0cf..ab8b4d19139 100644 --- a/samples/client/petstore/csharp/SwaggerClient/README.md +++ b/samples/client/petstore/csharp/SwaggerClient/README.md @@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build package: class io.swagger.codegen.languages.CSharpClientCodegen +- Build package: io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -38,6 +38,20 @@ using IO.Swagger.Api; using IO.Swagger.Client; using IO.Swagger.Model; ``` + + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out IO.Swagger.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + ## Getting Started @@ -115,6 +129,7 @@ Class | Method | HTTP request | Description - [Model.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [Model.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [Model.ArrayTest](docs/ArrayTest.md) + - [Model.Capitalization](docs/Capitalization.md) - [Model.Cat](docs/Cat.md) - [Model.Category](docs/Category.md) - [Model.ClassModel](docs/ClassModel.md) diff --git a/samples/client/petstore/csharp/SwaggerClient/docs/Capitalization.md b/samples/client/petstore/csharp/SwaggerClient/docs/Capitalization.md new file mode 100644 index 00000000000..87d14f03e0d --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/docs/Capitalization.md @@ -0,0 +1,14 @@ +# IO.Swagger.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/SwaggerClient/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md index de9d842ee06..44699db1dc2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/SwaggerClient/docs/FakeApi.md @@ -15,6 +15,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```csharp using System; @@ -166,6 +168,8 @@ void (empty response body) To test enum parameters +To test enum parameters + ### Example ```csharp using System; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CapitalizationTests.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CapitalizationTests.cs new file mode 100644 index 00000000000..30ed8700f74 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger.Test/Model/CapitalizationTests.cs @@ -0,0 +1,118 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + + +using NUnit.Framework; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using IO.Swagger.Api; +using IO.Swagger.Model; +using IO.Swagger.Client; +using System.Reflection; + +namespace IO.Swagger.Test +{ + /// + /// Class for testing Capitalization + /// + /// + /// This file is automatically generated by Swagger Codegen. + /// Please update the test case below to test the model. + /// + [TestFixture] + public class CapitalizationTests + { + // TODO uncomment below to declare an instance variable for Capitalization + //private Capitalization instance; + + /// + /// Setup before each test + /// + [SetUp] + public void Init() + { + // TODO uncomment below to create an instance of Capitalization + //instance = new Capitalization(); + } + + /// + /// Clean up after each test + /// + [TearDown] + public void Cleanup() + { + + } + + /// + /// Test an instance of Capitalization + /// + [Test] + public void CapitalizationInstanceTest() + { + // TODO uncomment below to test "IsInstanceOfType" Capitalization + //Assert.IsInstanceOfType (instance, "variable 'instance' is a Capitalization"); + } + + /// + /// Test the property 'SmallCamel' + /// + [Test] + public void SmallCamelTest() + { + // TODO unit test for the property 'SmallCamel' + } + /// + /// Test the property 'CapitalCamel' + /// + [Test] + public void CapitalCamelTest() + { + // TODO unit test for the property 'CapitalCamel' + } + /// + /// Test the property 'SmallSnake' + /// + [Test] + public void SmallSnakeTest() + { + // TODO unit test for the property 'SmallSnake' + } + /// + /// Test the property 'CapitalSnake' + /// + [Test] + public void CapitalSnakeTest() + { + // TODO unit test for the property 'CapitalSnake' + } + /// + /// Test the property 'SCAETHFlowPoints' + /// + [Test] + public void SCAETHFlowPointsTest() + { + // TODO unit test for the property 'SCAETHFlowPoints' + } + /// + /// Test the property 'ATT_NAME' + /// + [Test] + public void ATT_NAMETest() + { + // TODO unit test for the property 'ATT_NAME' + } + + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs index 52a26a00dbf..502deb884fd 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Api/FakeApi.cs @@ -28,7 +28,7 @@ namespace IO.Swagger.Api /// To test \"client\" model /// /// - /// + /// To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -39,7 +39,7 @@ namespace IO.Swagger.Api /// To test \"client\" model ///
    /// - /// + /// To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -96,7 +96,7 @@ namespace IO.Swagger.Api /// To test enum parameters ///
    /// - /// + /// To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -114,7 +114,7 @@ namespace IO.Swagger.Api /// To test enum parameters ///
    /// - /// + /// To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -133,7 +133,7 @@ namespace IO.Swagger.Api /// To test \"client\" model ///
    /// - /// + /// To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -144,7 +144,7 @@ namespace IO.Swagger.Api /// To test \"client\" model ///
    /// - /// + /// To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -201,7 +201,7 @@ namespace IO.Swagger.Api /// To test enum parameters /// /// - /// + /// To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -219,7 +219,7 @@ namespace IO.Swagger.Api /// To test enum parameters /// /// - /// + /// To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -345,7 +345,7 @@ namespace IO.Swagger.Api } /// - /// To test \"client\" model + /// To test \"client\" model To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -357,7 +357,7 @@ namespace IO.Swagger.Api } /// - /// To test \"client\" model + /// To test \"client\" model To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -423,7 +423,7 @@ namespace IO.Swagger.Api } /// - /// To test \"client\" model + /// To test \"client\" model To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -436,7 +436,7 @@ namespace IO.Swagger.Api } /// - /// To test \"client\" model + /// To test \"client\" model To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -756,7 +756,7 @@ namespace IO.Swagger.Api } /// - /// To test enum parameters + /// To test enum parameters To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -774,7 +774,7 @@ namespace IO.Swagger.Api } /// - /// To test enum parameters + /// To test enum parameters To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -844,7 +844,7 @@ namespace IO.Swagger.Api } /// - /// To test enum parameters + /// To test enum parameters To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -863,7 +863,7 @@ namespace IO.Swagger.Api } /// - /// To test enum parameters + /// To test enum parameters To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs index 2cb84a0c076..fce50ae0b74 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/Configuration.cs @@ -243,7 +243,7 @@ namespace IO.Swagger.Client return apiKeyValue; } - private string _tempFolderPath = Path.GetTempPath(); + private string _tempFolderPath; /// /// Gets or sets the temporary folder path to store the files downloaded from the server. @@ -251,7 +251,15 @@ namespace IO.Swagger.Client /// Folder path. public String TempFolderPath { - get { return _tempFolderPath; } + get + { + // default to Path.GetTempPath() if _tempFolderPath is not set + if (String.IsNullOrEmpty(_tempFolderPath)) + { + _tempFolderPath = Path.GetTempPath(); + } + return _tempFolderPath; + } set { diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs index 31b270ea0ff..0f16ee365e5 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Client/ExceptionFactory.cs @@ -19,6 +19,6 @@ namespace IO.Swagger.Client /// /// Method name /// Response - /// Exceptions + /// Exceptions public delegate Exception ExceptionFactory(string methodName, IRestResponse response); } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj index 43a0d972a0d..e1d4f2f595d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.csproj @@ -11,7 +11,7 @@ Contact: apiteam@swagger.io Debug AnyCPU - {959A8039-E3B9-4660-A666-840955E4520C} + {45175ABF-4F24-48D0-B481-B1A2D9B8649E} Library Properties IO.Swagger diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.nuspec b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.nuspec new file mode 100644 index 00000000000..4762df88d9c --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/IO.Swagger.nuspec @@ -0,0 +1,40 @@ + + + + + $id$ + Swagger Library + + + $version$ + + + $author$ + + + $author$ + false + false + + + A library generated from a Swagger doc + http://swagger.io/terms/ + http://www.apache.org/licenses/LICENSE-2.0.html + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AdditionalPropertiesClass.cs index 3ee30aa66c3..1abea7e7c14 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/AdditionalPropertiesClass.cs @@ -34,7 +34,7 @@ namespace IO.Swagger.Model /// /// MapProperty. /// MapOfMapProperty. - public AdditionalPropertiesClass(Dictionary MapProperty = null, Dictionary> MapOfMapProperty = null) + public AdditionalPropertiesClass(Dictionary MapProperty = default(Dictionary), Dictionary> MapOfMapProperty = default(Dictionary>)) { this.MapProperty = MapProperty; this.MapOfMapProperty = MapOfMapProperty; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs index 645c91cbef9..16ce4bc5af6 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Animal.cs @@ -39,7 +39,7 @@ namespace IO.Swagger.Model /// /// ClassName (required). /// Color (default to "red"). - public Animal(string ClassName = null, string Color = null) + public Animal(string ClassName = default(string), string Color = "red") { // to ensure "ClassName" is required (not null) if (ClassName == null) diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs index a45534c222f..7d7e0f15e29 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ApiResponse.cs @@ -35,7 +35,7 @@ namespace IO.Swagger.Model /// Code. /// Type. /// Message. - public ApiResponse(int? Code = null, string Type = null, string Message = null) + public ApiResponse(int? Code = default(int?), string Type = default(string), string Message = default(string)) { this.Code = Code; this.Type = Type; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs index a1a09c7cc0b..7580c01639d 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// ArrayArrayNumber. - public ArrayOfArrayOfNumberOnly(List> ArrayArrayNumber = null) + public ArrayOfArrayOfNumberOnly(List> ArrayArrayNumber = default(List>)) { this.ArrayArrayNumber = ArrayArrayNumber; } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfNumberOnly.cs index 8fcd0d6dcf5..2bdef12ebed 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayOfNumberOnly.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// ArrayNumber. - public ArrayOfNumberOnly(List ArrayNumber = null) + public ArrayOfNumberOnly(List ArrayNumber = default(List)) { this.ArrayNumber = ArrayNumber; } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs index 07a94aba71f..6ebb5ef7256 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ArrayTest.cs @@ -35,7 +35,7 @@ namespace IO.Swagger.Model /// ArrayOfString. /// ArrayArrayOfInteger. /// ArrayArrayOfModel. - public ArrayTest(List ArrayOfString = null, List> ArrayArrayOfInteger = null, List> ArrayArrayOfModel = null) + public ArrayTest(List ArrayOfString = default(List), List> ArrayArrayOfInteger = default(List>), List> ArrayArrayOfModel = default(List>)) { this.ArrayOfString = ArrayOfString; this.ArrayArrayOfInteger = ArrayArrayOfInteger; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Capitalization.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Capitalization.cs new file mode 100644 index 00000000000..240e3c461cb --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Capitalization.cs @@ -0,0 +1,197 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +using System; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Runtime.Serialization; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System.ComponentModel.DataAnnotations; + +namespace IO.Swagger.Model +{ + /// + /// Capitalization + /// + [DataContract] + 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 ATT_NAME = default(string)) + { + this.SmallCamel = SmallCamel; + this.CapitalCamel = CapitalCamel; + this.SmallSnake = SmallSnake; + this.CapitalSnake = CapitalSnake; + this.SCAETHFlowPoints = SCAETHFlowPoints; + this.ATT_NAME = ATT_NAME; + } + + /// + /// Gets or Sets SmallCamel + /// + [DataMember(Name="smallCamel", EmitDefaultValue=false)] + public string SmallCamel { get; set; } + /// + /// Gets or Sets CapitalCamel + /// + [DataMember(Name="CapitalCamel", EmitDefaultValue=false)] + public string CapitalCamel { get; set; } + /// + /// Gets or Sets SmallSnake + /// + [DataMember(Name="small_Snake", EmitDefaultValue=false)] + public string SmallSnake { get; set; } + /// + /// Gets or Sets CapitalSnake + /// + [DataMember(Name="Capital_Snake", EmitDefaultValue=false)] + public string CapitalSnake { get; set; } + /// + /// Gets or Sets SCAETHFlowPoints + /// + [DataMember(Name="SCA_ETH_Flow_Points", EmitDefaultValue=false)] + public string SCAETHFlowPoints { get; set; } + /// + /// Name of the pet + /// + /// Name of the pet + [DataMember(Name="ATT_NAME", EmitDefaultValue=false)] + public string ATT_NAME { 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("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() + { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object obj) + { + // credit: http://stackoverflow.com/a/10454552/677735 + return this.Equals(obj as Capitalization); + } + + /// + /// Returns true if Capitalization instances are equal + /// + /// Instance of Capitalization to be compared + /// Boolean + public bool Equals(Capitalization other) + { + // credit: http://stackoverflow.com/a/10454552/677735 + if (other == null) + return false; + + return + ( + this.SmallCamel == other.SmallCamel || + this.SmallCamel != null && + this.SmallCamel.Equals(other.SmallCamel) + ) && + ( + this.CapitalCamel == other.CapitalCamel || + this.CapitalCamel != null && + this.CapitalCamel.Equals(other.CapitalCamel) + ) && + ( + this.SmallSnake == other.SmallSnake || + this.SmallSnake != null && + this.SmallSnake.Equals(other.SmallSnake) + ) && + ( + this.CapitalSnake == other.CapitalSnake || + this.CapitalSnake != null && + this.CapitalSnake.Equals(other.CapitalSnake) + ) && + ( + this.SCAETHFlowPoints == other.SCAETHFlowPoints || + this.SCAETHFlowPoints != null && + this.SCAETHFlowPoints.Equals(other.SCAETHFlowPoints) + ) && + ( + this.ATT_NAME == other.ATT_NAME || + this.ATT_NAME != null && + this.ATT_NAME.Equals(other.ATT_NAME) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + // credit: http://stackoverflow.com/a/263416/677735 + unchecked // Overflow is fine, just wrap + { + int hash = 41; + // Suitable nullity checks etc, of course :) + if (this.SmallCamel != null) + hash = hash * 59 + this.SmallCamel.GetHashCode(); + if (this.CapitalCamel != null) + hash = hash * 59 + this.CapitalCamel.GetHashCode(); + if (this.SmallSnake != null) + hash = hash * 59 + this.SmallSnake.GetHashCode(); + if (this.CapitalSnake != null) + hash = hash * 59 + this.CapitalSnake.GetHashCode(); + if (this.SCAETHFlowPoints != null) + hash = hash * 59 + this.SCAETHFlowPoints.GetHashCode(); + if (this.ATT_NAME != null) + hash = hash * 59 + this.ATT_NAME.GetHashCode(); + return hash; + } + } + + public IEnumerable Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs index 577643ebce0..d5de574aba4 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Cat.cs @@ -40,7 +40,7 @@ namespace IO.Swagger.Model /// ClassName (required). /// Color (default to "red"). /// Declawed. - public Cat(string ClassName = null, string Color = null, bool? Declawed = null) + public Cat(string ClassName = default(string), string Color = "red", bool? Declawed = default(bool?)) { // to ensure "ClassName" is required (not null) if (ClassName == null) diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs index 427718eff0f..d459fb8adeb 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Category.cs @@ -34,7 +34,7 @@ namespace IO.Swagger.Model /// /// Id. /// Name. - public Category(long? Id = null, string Name = null) + public Category(long? Id = default(long?), string Name = default(string)) { this.Id = Id; this.Name = Name; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ClassModel.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ClassModel.cs index d7947c69aba..1bddfb9efbc 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ClassModel.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ClassModel.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// _Class. - public ClassModel(string _Class = null) + public ClassModel(string _Class = default(string)) { this._Class = _Class; } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs index b7b3e30c3ce..f2b4e1fbd65 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Dog.cs @@ -40,7 +40,7 @@ namespace IO.Swagger.Model /// ClassName (required). /// Color (default to "red"). /// Breed. - public Dog(string ClassName = null, string Color = null, string Breed = null) + public Dog(string ClassName = default(string), string Color = "red", string Breed = default(string)) { // to ensure "ClassName" is required (not null) if (ClassName == null) diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumArrays.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumArrays.cs index 075550ac040..b280c80fcb1 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumArrays.cs @@ -85,7 +85,7 @@ namespace IO.Swagger.Model /// /// JustSymbol. /// ArrayEnum. - public EnumArrays(JustSymbolEnum? JustSymbol = null, List ArrayEnum = null) + public EnumArrays(JustSymbolEnum? JustSymbol = default(JustSymbolEnum?), List ArrayEnum = default(List)) { this.JustSymbol = JustSymbol; this.ArrayEnum = ArrayEnum; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs index b486563bcaa..832c3d7808b 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/EnumTest.cs @@ -46,7 +46,13 @@ namespace IO.Swagger.Model /// Enum Lower for "lower" /// [EnumMember(Value = "lower")] - Lower + Lower, + + /// + /// Enum Empty for "" + /// + [EnumMember(Value = "")] + Empty } /// @@ -111,7 +117,7 @@ namespace IO.Swagger.Model /// EnumInteger. /// EnumNumber. /// OuterEnum. - public EnumTest(EnumStringEnum? EnumString = null, EnumIntegerEnum? EnumInteger = null, EnumNumberEnum? EnumNumber = null, OuterEnum? OuterEnum = null) + public EnumTest(EnumStringEnum? EnumString = default(EnumStringEnum?), EnumIntegerEnum? EnumInteger = default(EnumIntegerEnum?), EnumNumberEnum? EnumNumber = default(EnumNumberEnum?), OuterEnum OuterEnum = default(OuterEnum)) { this.EnumString = EnumString; this.EnumInteger = EnumInteger; @@ -123,7 +129,7 @@ namespace IO.Swagger.Model /// Gets or Sets OuterEnum /// [DataMember(Name="outerEnum", EmitDefaultValue=false)] - public OuterEnum? OuterEnum { get; set; } + public OuterEnum OuterEnum { get; set; } /// /// Returns the string presentation of the object /// diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs index de5cde20807..b7ff2effe52 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/FormatTest.cs @@ -50,7 +50,7 @@ namespace IO.Swagger.Model /// DateTime. /// Uuid. /// Password (required). - public FormatTest(int? Integer = null, int? Int32 = null, long? Int64 = null, decimal? Number = null, float? _Float = null, double? _Double = null, string _String = null, byte[] _Byte = null, byte[] Binary = null, DateTime? Date = null, DateTime? DateTime = null, Guid? Uuid = null, string Password = null) + 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?), string _String = default(string), byte[] _Byte = default(byte[]), byte[] Binary = default(byte[]), DateTime? Date = default(DateTime?), DateTime? DateTime = default(DateTime?), Guid? Uuid = default(Guid?), string Password = default(string)) { // to ensure "Number" is required (not null) if (Number == null) diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/List.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/List.cs index 7d4a145ee05..7eecb028ac3 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/List.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/List.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// _123List. - public List(string _123List = null) + public List(string _123List = default(string)) { this._123List = _123List; } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MapTest.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MapTest.cs index c5ff9fe92b3..6f5bc36ced6 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MapTest.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MapTest.cs @@ -60,7 +60,7 @@ namespace IO.Swagger.Model /// /// MapMapOfString. /// MapOfEnumString. - public MapTest(Dictionary> MapMapOfString = null, Dictionary MapOfEnumString = null) + public MapTest(Dictionary> MapMapOfString = default(Dictionary>), Dictionary MapOfEnumString = default(Dictionary)) { this.MapMapOfString = MapMapOfString; this.MapOfEnumString = MapOfEnumString; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 65bf2a60c4f..f59f9e082e6 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -35,7 +35,7 @@ namespace IO.Swagger.Model /// Uuid. /// DateTime. /// Map. - public MixedPropertiesAndAdditionalPropertiesClass(Guid? Uuid = null, DateTime? DateTime = null, Dictionary Map = null) + public MixedPropertiesAndAdditionalPropertiesClass(Guid? Uuid = default(Guid?), DateTime? DateTime = default(DateTime?), Dictionary Map = default(Dictionary)) { this.Uuid = Uuid; this.DateTime = DateTime; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs index 05f3eaeec76..b436cae32a2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Model200Response.cs @@ -34,7 +34,7 @@ namespace IO.Swagger.Model /// /// Name. /// _Class. - public Model200Response(int? Name = null, string _Class = null) + public Model200Response(int? Name = default(int?), string _Class = default(string)) { this.Name = Name; this._Class = _Class; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelClient.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelClient.cs index 43d0c8ecd64..64102139c55 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelClient.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelClient.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// _Client. - public ModelClient(string _Client = null) + public ModelClient(string _Client = default(string)) { this._Client = _Client; } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs index 6f3d68cb756..1169a11349c 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ModelReturn.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// _Return. - public ModelReturn(int? _Return = null) + public ModelReturn(int? _Return = default(int?)) { this._Return = _Return; } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs index dcf4010dcc6..db51691dcdb 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Name.cs @@ -39,7 +39,7 @@ namespace IO.Swagger.Model /// /// _Name (required). /// Property. - public Name(int? _Name = null, string Property = null) + public Name(int? _Name = default(int?), string Property = default(string)) { // to ensure "_Name" is required (not null) if (_Name == null) diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/NumberOnly.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/NumberOnly.cs index 9131b5b9260..ed8a5396cb2 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/NumberOnly.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// JustNumber. - public NumberOnly(decimal? JustNumber = null) + public NumberOnly(decimal? JustNumber = default(decimal?)) { this.JustNumber = JustNumber; } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs index 5beb95c11fd..0e98fc723a8 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Order.cs @@ -71,7 +71,7 @@ namespace IO.Swagger.Model /// ShipDate. /// Order Status. /// Complete (default to false). - public Order(long? Id = null, long? PetId = null, int? Quantity = null, DateTime? ShipDate = null, StatusEnum? Status = null, bool? Complete = null) + 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; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs index 6c1fb0b05c3..eb2cc52194c 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Pet.cs @@ -76,7 +76,7 @@ namespace IO.Swagger.Model /// PhotoUrls (required). /// Tags. /// pet status in the store. - public Pet(long? Id = null, Category Category = null, string Name = null, List PhotoUrls = null, List Tags = null, StatusEnum? Status = null) + 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) if (Name == null) diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ReadOnlyFirst.cs index a64db248d66..07deb7f1fe3 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/ReadOnlyFirst.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// Baz. - public ReadOnlyFirst(string Baz = null) + public ReadOnlyFirst(string Baz = default(string)) { this.Baz = Baz; } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs index 6b75943bff1..07eb8341294 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/SpecialModelName.cs @@ -33,7 +33,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// SpecialPropertyName. - public SpecialModelName(long? SpecialPropertyName = null) + public SpecialModelName(long? SpecialPropertyName = default(long?)) { this.SpecialPropertyName = SpecialPropertyName; } diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs index bc8b3c83a52..2820259d455 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/Tag.cs @@ -34,7 +34,7 @@ namespace IO.Swagger.Model /// /// Id. /// Name. - public Tag(long? Id = null, string Name = null) + public Tag(long? Id = default(long?), string Name = default(string)) { this.Id = Id; this.Name = Name; diff --git a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs index f2cc6d8246e..f0b4301a075 100644 --- a/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs +++ b/samples/client/petstore/csharp/SwaggerClient/src/IO.Swagger/Model/User.cs @@ -40,7 +40,7 @@ namespace IO.Swagger.Model /// Password. /// Phone. /// User Status. - public User(long? Id = null, string Username = null, string FirstName = null, string LastName = null, string Email = null, string Password = null, string Phone = null, int? UserStatus = null) + 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?)) { this.Id = Id; this.Username = Username; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/IO.Swagger.sln b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/IO.Swagger.sln index 8c223bc624d..d5879e565e7 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/IO.Swagger.sln +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{4B8145C1-32ED-46D4-9DD5-10A82B5B0013}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{5B61D15D-DCEB-42AF-89A6-6AE15FB9548F}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger.Test", "src\IO.Swagger.Test\IO.Swagger.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{4B8145C1-32ED-46D4-9DD5-10A82B5B0013}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{4B8145C1-32ED-46D4-9DD5-10A82B5B0013}.Debug|Any CPU.Build.0 = Debug|Any CPU -{4B8145C1-32ED-46D4-9DD5-10A82B5B0013}.Release|Any CPU.ActiveCfg = Release|Any CPU -{4B8145C1-32ED-46D4-9DD5-10A82B5B0013}.Release|Any CPU.Build.0 = Release|Any CPU +{5B61D15D-DCEB-42AF-89A6-6AE15FB9548F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{5B61D15D-DCEB-42AF-89A6-6AE15FB9548F}.Debug|Any CPU.Build.0 = Debug|Any CPU +{5B61D15D-DCEB-42AF-89A6-6AE15FB9548F}.Release|Any CPU.ActiveCfg = Release|Any CPU +{5B61D15D-DCEB-42AF-89A6-6AE15FB9548F}.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 diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/README.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/README.md index 67a001aa0cf..ab8b4d19139 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/README.md +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/README.md @@ -6,7 +6,7 @@ This C# SDK is automatically generated by the [Swagger Codegen](https://github.c - API version: 1.0.0 - SDK version: 1.0.0 -- Build package: class io.swagger.codegen.languages.CSharpClientCodegen +- Build package: io.swagger.codegen.languages.CSharpClientCodegen ## Frameworks supported @@ -38,6 +38,20 @@ using IO.Swagger.Api; using IO.Swagger.Client; using IO.Swagger.Model; ``` + + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out IO.Swagger.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + ## Getting Started @@ -115,6 +129,7 @@ Class | Method | HTTP request | Description - [Model.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [Model.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [Model.ArrayTest](docs/ArrayTest.md) + - [Model.Capitalization](docs/Capitalization.md) - [Model.Cat](docs/Cat.md) - [Model.Category](docs/Category.md) - [Model.ClassModel](docs/ClassModel.md) diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FakeApi.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FakeApi.md index 8dd5de759ee..44699db1dc2 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FakeApi.md +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/FakeApi.md @@ -15,6 +15,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```csharp using System; @@ -166,6 +168,8 @@ void (empty response body) To test enum parameters +To test enum parameters + ### Example ```csharp using System; @@ -209,11 +213,11 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **enumFormStringArray** | [**List**](string.md)| Form parameter enum test (string array) | [optional] + **enumFormStringArray** | [**List<string>**](string.md)| Form parameter enum test (string array) | [optional] **enumFormString** | **string**| Form parameter enum test (string) | [optional] [default to -efg] - **enumHeaderStringArray** | [**List**](string.md)| Header parameter enum test (string array) | [optional] + **enumHeaderStringArray** | [**List<string>**](string.md)| Header parameter enum test (string array) | [optional] **enumHeaderString** | **string**| Header parameter enum test (string) | [optional] [default to -efg] - **enumQueryStringArray** | [**List**](string.md)| Query parameter enum test (string array) | [optional] + **enumQueryStringArray** | [**List<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] diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/PetApi.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/PetApi.md index de9223ef7a4..da77647d5d8 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/PetApi.md +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/PetApi.md @@ -192,7 +192,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **status** | [**List**](string.md)| Status values that need to be considered for filter | + **status** | [**List<string>**](string.md)| Status values that need to be considered for filter | ### Return type @@ -257,7 +257,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **tags** | [**List**](string.md)| Tags to filter by | + **tags** | [**List<string>**](string.md)| Tags to filter by | ### Return type diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/UserApi.md b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/UserApi.md index e016a7a5e30..b7fc0343d20 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/UserApi.md +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/docs/UserApi.md @@ -119,7 +119,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**List**](User.md)| List of user object | + **body** | [**List<User>**](User.md)| List of user object | ### Return type @@ -180,7 +180,7 @@ namespace Example Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | [**List**](User.md)| List of user object | + **body** | [**List<User>**](User.md)| List of user object | ### Return type diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/IO.Swagger.Test.csproj b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/IO.Swagger.Test.csproj index b5bb96e8e4b..02c13c1a05b 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/IO.Swagger.Test.csproj +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger.Test/IO.Swagger.Test.csproj @@ -74,7 +74,7 @@ Contact: apiteam@swagger.io - {4B8145C1-32ED-46D4-9DD5-10A82B5B0013} + {5B61D15D-DCEB-42AF-89A6-6AE15FB9548F} IO.Swagger diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/FakeApi.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/FakeApi.cs index 52a26a00dbf..502deb884fd 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Api/FakeApi.cs @@ -28,7 +28,7 @@ namespace IO.Swagger.Api /// To test \"client\" model /// /// - /// + /// To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -39,7 +39,7 @@ namespace IO.Swagger.Api /// To test \"client\" model /// /// - /// + /// To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -96,7 +96,7 @@ namespace IO.Swagger.Api /// To test enum parameters /// /// - /// + /// To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -114,7 +114,7 @@ namespace IO.Swagger.Api /// To test enum parameters /// /// - /// + /// To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -133,7 +133,7 @@ namespace IO.Swagger.Api /// To test \"client\" model /// /// - /// + /// To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -144,7 +144,7 @@ namespace IO.Swagger.Api /// To test \"client\" model /// /// - /// + /// To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -201,7 +201,7 @@ namespace IO.Swagger.Api /// To test enum parameters /// /// - /// + /// To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -219,7 +219,7 @@ namespace IO.Swagger.Api /// To test enum parameters /// /// - /// + /// To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -345,7 +345,7 @@ namespace IO.Swagger.Api } /// - /// To test \"client\" model + /// To test \"client\" model To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -357,7 +357,7 @@ namespace IO.Swagger.Api } /// - /// To test \"client\" model + /// To test \"client\" model To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -423,7 +423,7 @@ namespace IO.Swagger.Api } /// - /// To test \"client\" model + /// To test \"client\" model To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -436,7 +436,7 @@ namespace IO.Swagger.Api } /// - /// To test \"client\" model + /// To test \"client\" model To test \"client\" model /// /// Thrown when fails to make API call /// client model @@ -756,7 +756,7 @@ namespace IO.Swagger.Api } /// - /// To test enum parameters + /// To test enum parameters To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -774,7 +774,7 @@ namespace IO.Swagger.Api } /// - /// To test enum parameters + /// To test enum parameters To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -844,7 +844,7 @@ namespace IO.Swagger.Api } /// - /// To test enum parameters + /// To test enum parameters To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) @@ -863,7 +863,7 @@ namespace IO.Swagger.Api } /// - /// To test enum parameters + /// To test enum parameters To test enum parameters /// /// Thrown when fails to make API call /// Form parameter enum test (string array) (optional) diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/Configuration.cs index 2cb84a0c076..fce50ae0b74 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/Configuration.cs @@ -243,7 +243,7 @@ namespace IO.Swagger.Client return apiKeyValue; } - private string _tempFolderPath = Path.GetTempPath(); + private string _tempFolderPath; /// /// Gets or sets the temporary folder path to store the files downloaded from the server. @@ -251,7 +251,15 @@ namespace IO.Swagger.Client /// Folder path. public String TempFolderPath { - get { return _tempFolderPath; } + get + { + // default to Path.GetTempPath() if _tempFolderPath is not set + if (String.IsNullOrEmpty(_tempFolderPath)) + { + _tempFolderPath = Path.GetTempPath(); + } + return _tempFolderPath; + } set { diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ExceptionFactory.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ExceptionFactory.cs index 31b270ea0ff..0f16ee365e5 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ExceptionFactory.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Client/ExceptionFactory.cs @@ -19,6 +19,6 @@ namespace IO.Swagger.Client /// /// Method name /// Response - /// Exceptions + /// Exceptions public delegate Exception ExceptionFactory(string methodName, IRestResponse response); } diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/IO.Swagger.csproj b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/IO.Swagger.csproj index 29b0fdbc6f1..f119b58e6d0 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/IO.Swagger.csproj @@ -11,7 +11,7 @@ Contact: apiteam@swagger.io Debug AnyCPU - {4B8145C1-32ED-46D4-9DD5-10A82B5B0013} + {5B61D15D-DCEB-42AF-89A6-6AE15FB9548F} Library Properties IO.Swagger diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AdditionalPropertiesClass.cs index 03f64731a5c..9ad0f1602c9 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/AdditionalPropertiesClass.cs @@ -37,7 +37,7 @@ namespace IO.Swagger.Model /// /// MapProperty. /// MapOfMapProperty. - public AdditionalPropertiesClass(Dictionary MapProperty = null, Dictionary> MapOfMapProperty = null) + public AdditionalPropertiesClass(Dictionary MapProperty = default(Dictionary), Dictionary> MapOfMapProperty = default(Dictionary>)) { this.MapProperty = MapProperty; this.MapOfMapProperty = MapOfMapProperty; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Animal.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Animal.cs index 204454aa060..3c1d8fee403 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Animal.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Animal.cs @@ -42,7 +42,7 @@ namespace IO.Swagger.Model /// /// ClassName (required). /// Color (default to "red"). - public Animal(string ClassName = null, string Color = null) + public Animal(string ClassName = default(string), string Color = "red") { // to ensure "ClassName" is required (not null) if (ClassName == null) diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ApiResponse.cs index 62fd27efd83..4de9acbb568 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ApiResponse.cs @@ -38,7 +38,7 @@ namespace IO.Swagger.Model /// Code. /// Type. /// Message. - public ApiResponse(int? Code = null, string Type = null, string Message = null) + public ApiResponse(int? Code = default(int?), string Type = default(string), string Message = default(string)) { this.Code = Code; this.Type = Type; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs index 94f61cac428..6458c985ec2 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfArrayOfNumberOnly.cs @@ -36,7 +36,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// ArrayArrayNumber. - public ArrayOfArrayOfNumberOnly(List> ArrayArrayNumber = null) + public ArrayOfArrayOfNumberOnly(List> ArrayArrayNumber = default(List>)) { this.ArrayArrayNumber = ArrayArrayNumber; } diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfNumberOnly.cs index 1f7c93a7118..ad2ea068a1f 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayOfNumberOnly.cs @@ -36,7 +36,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// ArrayNumber. - public ArrayOfNumberOnly(List ArrayNumber = null) + public ArrayOfNumberOnly(List ArrayNumber = default(List)) { this.ArrayNumber = ArrayNumber; } diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayTest.cs index 9fd2075fdc7..66d04bc0d0f 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ArrayTest.cs @@ -38,7 +38,7 @@ namespace IO.Swagger.Model /// ArrayOfString. /// ArrayArrayOfInteger. /// ArrayArrayOfModel. - public ArrayTest(List ArrayOfString = null, List> ArrayArrayOfInteger = null, List> ArrayArrayOfModel = null) + public ArrayTest(List ArrayOfString = default(List), List> ArrayArrayOfInteger = default(List>), List> ArrayArrayOfModel = default(List>)) { this.ArrayOfString = ArrayOfString; this.ArrayArrayOfInteger = ArrayArrayOfInteger; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Cat.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Cat.cs index 797bfd287be..1f0d9f2880a 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Cat.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Cat.cs @@ -43,7 +43,7 @@ namespace IO.Swagger.Model /// ClassName (required). /// Color (default to "red"). /// Declawed. - public Cat(string ClassName = null, string Color = null, bool? Declawed = null) + public Cat(string ClassName = default(string), string Color = "red", bool? Declawed = default(bool?)) { // to ensure "ClassName" is required (not null) if (ClassName == null) diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Category.cs index 38dac8187e0..81cd316af8f 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Category.cs @@ -37,7 +37,7 @@ namespace IO.Swagger.Model /// /// Id. /// Name. - public Category(long? Id = null, string Name = null) + public Category(long? Id = default(long?), string Name = default(string)) { this.Id = Id; this.Name = Name; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ClassModel.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ClassModel.cs index 369efd6a4d8..2583cbdf9a5 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ClassModel.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ClassModel.cs @@ -36,7 +36,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// _Class. - public ClassModel(string _Class = null) + public ClassModel(string _Class = default(string)) { this._Class = _Class; } diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Dog.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Dog.cs index 1f116a03efc..27de3c23e05 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Dog.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Dog.cs @@ -43,7 +43,7 @@ namespace IO.Swagger.Model /// ClassName (required). /// Color (default to "red"). /// Breed. - public Dog(string ClassName = null, string Color = null, string Breed = null) + public Dog(string ClassName = default(string), string Color = "red", string Breed = default(string)) { // to ensure "ClassName" is required (not null) if (ClassName == null) diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumArrays.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumArrays.cs index f41fd9845ac..bbb807405e6 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumArrays.cs @@ -88,7 +88,7 @@ namespace IO.Swagger.Model /// /// JustSymbol. /// ArrayEnum. - public EnumArrays(JustSymbolEnum? JustSymbol = null, List ArrayEnum = null) + public EnumArrays(JustSymbolEnum? JustSymbol = default(JustSymbolEnum?), List ArrayEnum = default(List)) { this.JustSymbol = JustSymbol; this.ArrayEnum = ArrayEnum; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs index b4e8247da55..ea76fc4bf12 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/EnumTest.cs @@ -49,7 +49,13 @@ namespace IO.Swagger.Model /// Enum Lower for "lower" /// [EnumMember(Value = "lower")] - Lower + Lower, + + /// + /// Enum Empty for "" + /// + [EnumMember(Value = "")] + Empty } /// @@ -114,7 +120,7 @@ namespace IO.Swagger.Model /// EnumInteger. /// EnumNumber. /// OuterEnum. - public EnumTest(EnumStringEnum? EnumString = null, EnumIntegerEnum? EnumInteger = null, EnumNumberEnum? EnumNumber = null, OuterEnum? OuterEnum = null) + public EnumTest(EnumStringEnum? EnumString = default(EnumStringEnum?), EnumIntegerEnum? EnumInteger = default(EnumIntegerEnum?), EnumNumberEnum? EnumNumber = default(EnumNumberEnum?), OuterEnum OuterEnum = default(OuterEnum)) { this.EnumString = EnumString; this.EnumInteger = EnumInteger; @@ -126,7 +132,7 @@ namespace IO.Swagger.Model /// Gets or Sets OuterEnum /// [DataMember(Name="outerEnum", EmitDefaultValue=false)] - public OuterEnum? OuterEnum { get; set; } + public OuterEnum OuterEnum { get; set; } /// /// Returns the string presentation of the object /// diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/FormatTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/FormatTest.cs index e415fa64925..9bd73ccff4a 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/FormatTest.cs @@ -53,7 +53,7 @@ namespace IO.Swagger.Model /// DateTime. /// Uuid. /// Password (required). - public FormatTest(int? Integer = null, int? Int32 = null, long? Int64 = null, decimal? Number = null, float? _Float = null, double? _Double = null, string _String = null, byte[] _Byte = null, byte[] Binary = null, DateTime? Date = null, DateTime? DateTime = null, Guid? Uuid = null, string Password = null) + 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?), string _String = default(string), byte[] _Byte = default(byte[]), byte[] Binary = default(byte[]), DateTime? Date = default(DateTime?), DateTime? DateTime = default(DateTime?), Guid? Uuid = default(Guid?), string Password = default(string)) { // to ensure "Number" is required (not null) if (Number == null) diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/List.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/List.cs index 95d18430713..c0910cf4ea9 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/List.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/List.cs @@ -36,7 +36,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// _123List. - public List(string _123List = null) + public List(string _123List = default(string)) { this._123List = _123List; } diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MapTest.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MapTest.cs index f2dfce4e57f..3f59092fe2a 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MapTest.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MapTest.cs @@ -63,7 +63,7 @@ namespace IO.Swagger.Model /// /// MapMapOfString. /// MapOfEnumString. - public MapTest(Dictionary> MapMapOfString = null, Dictionary MapOfEnumString = null) + public MapTest(Dictionary> MapMapOfString = default(Dictionary>), Dictionary MapOfEnumString = default(Dictionary)) { this.MapMapOfString = MapMapOfString; this.MapOfEnumString = MapOfEnumString; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index d0c7a54f1df..7f57c3965e8 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -38,7 +38,7 @@ namespace IO.Swagger.Model /// Uuid. /// DateTime. /// Map. - public MixedPropertiesAndAdditionalPropertiesClass(Guid? Uuid = null, DateTime? DateTime = null, Dictionary Map = null) + public MixedPropertiesAndAdditionalPropertiesClass(Guid? Uuid = default(Guid?), DateTime? DateTime = default(DateTime?), Dictionary Map = default(Dictionary)) { this.Uuid = Uuid; this.DateTime = DateTime; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Model200Response.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Model200Response.cs index b838abe9f73..79f58cf1f00 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Model200Response.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Model200Response.cs @@ -37,7 +37,7 @@ namespace IO.Swagger.Model /// /// Name. /// _Class. - public Model200Response(int? Name = null, string _Class = null) + public Model200Response(int? Name = default(int?), string _Class = default(string)) { this.Name = Name; this._Class = _Class; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelClient.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelClient.cs index 675b3b82fc5..4b7d6f06312 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelClient.cs @@ -36,7 +36,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// _Client. - public ModelClient(string _Client = null) + public ModelClient(string _Client = default(string)) { this._Client = _Client; } diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelReturn.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelReturn.cs index fad3b1eab8a..83fcf72c2dc 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelReturn.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ModelReturn.cs @@ -36,7 +36,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// _Return. - public ModelReturn(int? _Return = null) + public ModelReturn(int? _Return = default(int?)) { this._Return = _Return; } diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Name.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Name.cs index c561bcb3408..a04fbdf8d53 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Name.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Name.cs @@ -42,7 +42,7 @@ namespace IO.Swagger.Model /// /// _Name (required). /// Property. - public Name(int? _Name = null, string Property = null) + public Name(int? _Name = default(int?), string Property = default(string)) { // to ensure "_Name" is required (not null) if (_Name == null) diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/NumberOnly.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/NumberOnly.cs index 379ecb93c79..7f9069d29a0 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/NumberOnly.cs @@ -36,7 +36,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// JustNumber. - public NumberOnly(decimal? JustNumber = null) + public NumberOnly(decimal? JustNumber = default(decimal?)) { this.JustNumber = JustNumber; } diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Order.cs index a8e7af069b8..f9d403f0ecf 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Order.cs @@ -74,7 +74,7 @@ namespace IO.Swagger.Model /// ShipDate. /// Order Status. /// Complete (default to false). - public Order(long? Id = null, long? PetId = null, int? Quantity = null, DateTime? ShipDate = null, StatusEnum? Status = null, bool? Complete = null) + 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; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs index ea6243170c1..0c6d9258d43 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Pet.cs @@ -79,7 +79,7 @@ namespace IO.Swagger.Model /// PhotoUrls (required). /// Tags. /// pet status in the store. - public Pet(long? Id = null, Category Category = null, string Name = null, List PhotoUrls = null, List Tags = null, StatusEnum? Status = null) + 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) if (Name == null) diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ReadOnlyFirst.cs index 961cf1eb13e..4eddf1acca0 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/ReadOnlyFirst.cs @@ -36,7 +36,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// Baz. - public ReadOnlyFirst(string Baz = null) + public ReadOnlyFirst(string Baz = default(string)) { this.Baz = Baz; } diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/SpecialModelName.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/SpecialModelName.cs index 2c0013cf6f3..142a82bc34e 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/SpecialModelName.cs @@ -36,7 +36,7 @@ namespace IO.Swagger.Model /// Initializes a new instance of the class. /// /// SpecialPropertyName. - public SpecialModelName(long? SpecialPropertyName = null) + public SpecialModelName(long? SpecialPropertyName = default(long?)) { this.SpecialPropertyName = SpecialPropertyName; } diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Tag.cs index 1c0597818ae..7fd441065b7 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/Tag.cs @@ -37,7 +37,7 @@ namespace IO.Swagger.Model /// /// Id. /// Name. - public Tag(long? Id = null, string Name = null) + public Tag(long? Id = default(long?), string Name = default(string)) { this.Id = Id; this.Name = Name; diff --git a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/User.cs index 316b7feb2cc..fd2019dfb50 100644 --- a/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/User.cs +++ b/samples/client/petstore/csharp/SwaggerClientWithPropertyChanged/src/IO.Swagger/Model/User.cs @@ -43,7 +43,7 @@ namespace IO.Swagger.Model /// Password. /// Phone. /// User Status. - public User(long? Id = null, string Username = null, string FirstName = null, string LastName = null, string Email = null, string Password = null, string Phone = null, int? UserStatus = null) + 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?)) { this.Id = Id; this.Username = Username; diff --git a/samples/client/petstore/elixir/.swagger-codegen-ignore b/samples/client/petstore/elixir/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/elixir/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/elixir/README.md b/samples/client/petstore/elixir/README.md new file mode 100644 index 00000000000..a436a5e0063 --- /dev/null +++ b/samples/client/petstore/elixir/README.md @@ -0,0 +1,18 @@ +# SwaggerPetstore + +**TODO: Add description** + +## Installation + +If [available in Hex](https://hex.pm/docs/publish), the package can be installed +by adding `swagger_petstore` to your list of dependencies in `mix.exs`: + +```elixir +def deps do + [{:swagger_petstore, "~> 0.1.0"}] +end +``` + +Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) +and published on [HexDocs](https://hexdocs.pm). Once published, the docs can +be found at [https://hexdocs.pm/swagger_petstore](https://hexdocs.pm/swagger_petstore). diff --git a/samples/client/petstore/elixir/config/config.exs b/samples/client/petstore/elixir/config/config.exs new file mode 100644 index 00000000000..7ce1553ff17 --- /dev/null +++ b/samples/client/petstore/elixir/config/config.exs @@ -0,0 +1,30 @@ +# This file is responsible for configuring your application +# and its dependencies with the aid of the Mix.Config module. +use Mix.Config + +# This configuration is loaded before any dependency and is restricted +# to this project. If another project depends on this project, this +# file won't be loaded nor affect the parent project. For this reason, +# if you want to provide default values for your application for +# 3rd-party users, it should be done in your "mix.exs" file. + +# You can configure for your application as: +# +# config :swagger_petstore, key: :value +# +# And access this configuration in your application as: +# +# Application.get_env(:swagger_petstore, :key) +# +# Or configure a 3rd-party app: +# +# config :logger, level: :info +# + +# It is also possible to import configuration files, relative to this +# directory. For example, you can emulate configuration per environment +# by uncommenting the line below and defining dev.exs, test.exs and such. +# Configuration from the imported file will override the ones defined +# here (which is why it is important to import them last). +# +# import_config "#{Mix.env}.exs" diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/api/fake.ex b/samples/client/petstore/elixir/lib/swagger_petstore/api/fake.ex new file mode 100644 index 00000000000..707744d861e --- /dev/null +++ b/samples/client/petstore/elixir/lib/swagger_petstore/api/fake.ex @@ -0,0 +1,52 @@ +defmodule SwaggerPetstore.Api.Fake do + @moduledoc """ + Documentation for SwaggerPetstore.Api.Fake. + """ + + use Tesla + + plug Tesla.Middleware.BaseUrl, "http://petstore.swagger.io/v2" + plug Tesla.Middleware.JSON + + def test_client_model(body) do + method = [method: :patch] + url = [url: "/fake"] + query_params = [] + header_params = [] + body_params = [body: body] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback) do + method = [method: :post] + url = [url: "/fake"] + query_params = [] + header_params = [] + body_params = [] + form_params = [body: Enum.map_join([{:"integer", integer}, {:"int32", int32}, {:"int64", int64}, {:"number", number}, {:"float", float}, {:"double", double}, {:"string", string}, {:"patternWithoutDelimiter", pattern_without_delimiter}, {:"byte", byte}, {:"binary", binary}, {:"date", date}, {:"dateTime", date_time}, {:"password", password}, {:"callback", callback}], "&", &("#{elem(&1, 0)}=#{elem(&1, 1)}"))] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def test_enum_parameters(enum_form_string_array, enum_form_string, enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double) do + method = [method: :get] + url = [url: "/fake"] + query_params = [query: [{:"enumQueryStringArray", enum_query_string_array}, {:"enumQueryString", enum_query_string}, {:"enumQueryInteger", enum_query_integer}]] + header_params = [header: [{:"enumHeaderStringArray", enum_header_string_array}, {:"enumHeaderString", enum_header_string}]] + body_params = [] + form_params = [body: Enum.map_join([{:"enumFormStringArray", enum_form_string_array}, {:"enumFormString", enum_form_string}, {:"enumQueryDouble", enum_query_double}], "&", &("#{elem(&1, 0)}=#{elem(&1, 1)}"))] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end +end diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/api/pet.ex b/samples/client/petstore/elixir/lib/swagger_petstore/api/pet.ex new file mode 100644 index 00000000000..b0ca76c91f0 --- /dev/null +++ b/samples/client/petstore/elixir/lib/swagger_petstore/api/pet.ex @@ -0,0 +1,122 @@ +defmodule SwaggerPetstore.Api.Pet do + @moduledoc """ + Documentation for SwaggerPetstore.Api.Pet. + """ + + use Tesla + + plug Tesla.Middleware.BaseUrl, "http://petstore.swagger.io/v2" + plug Tesla.Middleware.JSON + + def add_pet(body) do + method = [method: :post] + url = [url: "/pet"] + query_params = [] + header_params = [] + body_params = [body: body] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def delete_pet(pet_id, api_key) do + method = [method: :delete] + url = [url: "/pet/#{pet_id}"] + query_params = [] + header_params = [header: [{:"apiKey", api_key}]] + body_params = [] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def find_pets_by_status(status) do + method = [method: :get] + url = [url: "/pet/findByStatus"] + query_params = [query: [{:"status", status}]] + header_params = [] + body_params = [] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def find_pets_by_tags(tags) do + method = [method: :get] + url = [url: "/pet/findByTags"] + query_params = [query: [{:"tags", tags}]] + header_params = [] + body_params = [] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def get_pet_by_id(pet_id) do + method = [method: :get] + url = [url: "/pet/#{pet_id}"] + query_params = [] + header_params = [] + body_params = [] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def update_pet(body) do + method = [method: :put] + url = [url: "/pet"] + query_params = [] + header_params = [] + body_params = [body: body] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def update_pet_with_form(pet_id, name, status) do + method = [method: :post] + url = [url: "/pet/#{pet_id}"] + query_params = [] + header_params = [] + body_params = [] + form_params = [body: Enum.map_join([{:"name", name}, {:"status", status}], "&", &("#{elem(&1, 0)}=#{elem(&1, 1)}"))] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def upload_file(pet_id, additional_metadata, file) do + method = [method: :post] + url = [url: "/pet/#{pet_id}/uploadImage"] + query_params = [] + header_params = [] + body_params = [] + form_params = [body: Enum.map_join([{:"additionalMetadata", additional_metadata}, {:"file", file}], "&", &("#{elem(&1, 0)}=#{elem(&1, 1)}"))] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end +end diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/api/store.ex b/samples/client/petstore/elixir/lib/swagger_petstore/api/store.ex new file mode 100644 index 00000000000..420fa465580 --- /dev/null +++ b/samples/client/petstore/elixir/lib/swagger_petstore/api/store.ex @@ -0,0 +1,66 @@ +defmodule SwaggerPetstore.Api.Store do + @moduledoc """ + Documentation for SwaggerPetstore.Api.Store. + """ + + use Tesla + + plug Tesla.Middleware.BaseUrl, "http://petstore.swagger.io/v2" + plug Tesla.Middleware.JSON + + def delete_order(order_id) do + method = [method: :delete] + url = [url: "/store/order/#{order_id}"] + query_params = [] + header_params = [] + body_params = [] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def get_inventory() do + method = [method: :get] + url = [url: "/store/inventory"] + query_params = [] + header_params = [] + body_params = [] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def get_order_by_id(order_id) do + method = [method: :get] + url = [url: "/store/order/#{order_id}"] + query_params = [] + header_params = [] + body_params = [] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def place_order(body) do + method = [method: :post] + url = [url: "/store/order"] + query_params = [] + header_params = [] + body_params = [body: body] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end +end diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/api/user.ex b/samples/client/petstore/elixir/lib/swagger_petstore/api/user.ex new file mode 100644 index 00000000000..c69844482a8 --- /dev/null +++ b/samples/client/petstore/elixir/lib/swagger_petstore/api/user.ex @@ -0,0 +1,122 @@ +defmodule SwaggerPetstore.Api.User do + @moduledoc """ + Documentation for SwaggerPetstore.Api.User. + """ + + use Tesla + + plug Tesla.Middleware.BaseUrl, "http://petstore.swagger.io/v2" + plug Tesla.Middleware.JSON + + def create_user(body) do + method = [method: :post] + url = [url: "/user"] + query_params = [] + header_params = [] + body_params = [body: body] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def create_users_with_array_input(body) do + method = [method: :post] + url = [url: "/user/createWithArray"] + query_params = [] + header_params = [] + body_params = [body: body] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def create_users_with_list_input(body) do + method = [method: :post] + url = [url: "/user/createWithList"] + query_params = [] + header_params = [] + body_params = [body: body] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def delete_user(username) do + method = [method: :delete] + url = [url: "/user/#{username}"] + query_params = [] + header_params = [] + body_params = [] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def get_user_by_name(username) do + method = [method: :get] + url = [url: "/user/#{username}"] + query_params = [] + header_params = [] + body_params = [] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def login_user(username, password) do + method = [method: :get] + url = [url: "/user/login"] + query_params = [query: [{:"username", username}, {:"password", password}]] + header_params = [] + body_params = [] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def logout_user() do + method = [method: :get] + url = [url: "/user/logout"] + query_params = [] + header_params = [] + body_params = [] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end + + def update_user(username, body) do + method = [method: :put] + url = [url: "/user/#{username}"] + query_params = [] + header_params = [] + body_params = [body: body] + form_params = [] + params = query_params ++ header_params ++ body_params ++ form_params + opts = [] + options = method ++ url ++ params ++ opts + + request(options) + end +end diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/$special[model.name].ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/$special[model.name].ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/200_response.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/200_response.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/additionalPropertiesClass.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/additionalPropertiesClass.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/animal.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/animal.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/animalFarm.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/animalFarm.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/apiResponse.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/apiResponse.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/arrayOfArrayOfNumberOnly.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/arrayOfArrayOfNumberOnly.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/arrayOfNumberOnly.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/arrayOfNumberOnly.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/arrayTest.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/arrayTest.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/capitalization.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/capitalization.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/cat.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/cat.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/category.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/category.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/classModel.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/classModel.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/client.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/client.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/dog.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/dog.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/enumArrays.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/enumArrays.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/enumClass.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/enumClass.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/enum_Test.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/enum_Test.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/format_test.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/format_test.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/hasOnlyReadOnly.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/hasOnlyReadOnly.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/mapTest.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/mapTest.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/mixedPropertiesAndAdditionalPropertiesClass.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/mixedPropertiesAndAdditionalPropertiesClass.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/name.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/name.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/numberOnly.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/numberOnly.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/order.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/order.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/outerEnum.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/outerEnum.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/pet.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/pet.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/readOnlyFirst.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/readOnlyFirst.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/return.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/return.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/tag.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/tag.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/lib/swagger_petstore/model/user.ex b/samples/client/petstore/elixir/lib/swagger_petstore/model/user.ex new file mode 100644 index 00000000000..e69de29bb2d diff --git a/samples/client/petstore/elixir/mix.exs b/samples/client/petstore/elixir/mix.exs new file mode 100644 index 00000000000..82717f770be --- /dev/null +++ b/samples/client/petstore/elixir/mix.exs @@ -0,0 +1,36 @@ +defmodule SwaggerPetstore.Mixfile do + use Mix.Project + + def project do + [app: :swagger_petstore, + version: "0.1.0", + elixir: "~> 1.4", + build_embedded: Mix.env == :prod, + start_permanent: Mix.env == :prod, + deps: deps()] + end + + # Configuration for the OTP application + # + # Type "mix help compile.app" for more information + def application do + # Specify extra applications you'll use from Erlang/Elixir + [extra_applications: [:logger]] + end + + # Dependencies can be Hex packages: + # + # {:my_dep, "~> 0.3.0"} + # + # Or git/path repositories: + # + # {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} + # + # Type "mix help deps" for more examples and options + defp deps do + [ + {:tesla, "~> 0.5.0"}, + {:poison, ">= 1.0.0"} + ] + end +end diff --git a/samples/client/petstore/elixir/test/test_helper.exs b/samples/client/petstore/elixir/test/test_helper.exs new file mode 100644 index 00000000000..869559e709e --- /dev/null +++ b/samples/client/petstore/elixir/test/test_helper.exs @@ -0,0 +1 @@ +ExUnit.start() diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index 2c80b9050fc..64441ed3d92 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/README.md @@ -55,6 +55,7 @@ Class | Method | HTTP request | Description - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [ArrayTest](docs/ArrayTest.md) + - [Capitalization](docs/Capitalization.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) - [ClassModel](docs/ClassModel.md) diff --git a/samples/client/petstore/go/go-petstore/animal.go b/samples/client/petstore/go/go-petstore/animal.go index f385f78a41c..0b14ac8d2c0 100644 --- a/samples/client/petstore/go/go-petstore/animal.go +++ b/samples/client/petstore/go/go-petstore/animal.go @@ -12,7 +12,7 @@ package petstore type Animal struct { - ClassName string `json:"className,omitempty"` + ClassName string `json:"className"` Color string `json:"color,omitempty"` } diff --git a/samples/client/petstore/go/go-petstore/capitalization.go b/samples/client/petstore/go/go-petstore/capitalization.go new file mode 100644 index 00000000000..0c4631e3282 --- /dev/null +++ b/samples/client/petstore/go/go-petstore/capitalization.go @@ -0,0 +1,27 @@ +/* + * Swagger Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +package petstore + +type Capitalization struct { + + SmallCamel string `json:"smallCamel,omitempty"` + + CapitalCamel string `json:"CapitalCamel,omitempty"` + + SmallSnake string `json:"small_Snake,omitempty"` + + CapitalSnake string `json:"Capital_Snake,omitempty"` + + SCAETHFlowPoints string `json:"SCA_ETH_Flow_Points,omitempty"` + + // Name of the pet + ATT_NAME string `json:"ATT_NAME,omitempty"` +} diff --git a/samples/client/petstore/go/go-petstore/cat.go b/samples/client/petstore/go/go-petstore/cat.go index 6469034b1fc..72f3a77fd18 100644 --- a/samples/client/petstore/go/go-petstore/cat.go +++ b/samples/client/petstore/go/go-petstore/cat.go @@ -12,7 +12,7 @@ package petstore type Cat struct { - ClassName string `json:"className,omitempty"` + ClassName string `json:"className"` Color string `json:"color,omitempty"` diff --git a/samples/client/petstore/go/go-petstore/docs/Capitalization.md b/samples/client/petstore/go/go-petstore/docs/Capitalization.md new file mode 100644 index 00000000000..760ada1db2d --- /dev/null +++ b/samples/client/petstore/go/go-petstore/docs/Capitalization.md @@ -0,0 +1,15 @@ +# Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**SmallCamel** | **string** | | [optional] [default to null] +**CapitalCamel** | **string** | | [optional] [default to null] +**SmallSnake** | **string** | | [optional] [default to null] +**CapitalSnake** | **string** | | [optional] [default to null] +**SCAETHFlowPoints** | **string** | | [optional] [default to null] +**ATT_NAME** | **string** | Name of the pet | [optional] [default to null] + +[[Back to Model list]](../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/go/go-petstore/dog.go b/samples/client/petstore/go/go-petstore/dog.go index 5b404801abb..a2d91c6e6a1 100644 --- a/samples/client/petstore/go/go-petstore/dog.go +++ b/samples/client/petstore/go/go-petstore/dog.go @@ -12,7 +12,7 @@ package petstore type Dog struct { - ClassName string `json:"className,omitempty"` + ClassName string `json:"className"` Color string `json:"color,omitempty"` diff --git a/samples/client/petstore/go/go-petstore/fake_api.go b/samples/client/petstore/go/go-petstore/fake_api.go index 80e9fc235ca..2e2638e076d 100644 --- a/samples/client/petstore/go/go-petstore/fake_api.go +++ b/samples/client/petstore/go/go-petstore/fake_api.go @@ -1,4 +1,4 @@ -/* +/* * Swagger Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ @@ -11,10 +11,10 @@ package petstore import ( + "encoding/json" "net/url" "strings" "time" - "encoding/json" ) type FakeApi struct { @@ -62,7 +62,7 @@ func (a FakeApi) TestClientModel(body Client) (*Client, *APIResponse, error) { } // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/json", } + localVarHttpContentTypes := []string{"application/json"} // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) @@ -72,7 +72,7 @@ func (a FakeApi) TestClientModel(body Client) (*Client, *APIResponse, error) { // to determine the Accept header localVarHttpHeaderAccepts := []string{ "application/json", - } + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) @@ -100,8 +100,8 @@ func (a FakeApi) TestClientModel(body Client) (*Client, *APIResponse, error) { } /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * * @param number None * @param double None @@ -118,7 +118,7 @@ func (a FakeApi) TestClientModel(body Client) (*Client, *APIResponse, error) { * @param "dateTime" (time.Time) None * @param "password" (string) None * @param "callback" (string) None - * @return + * @return */ func (a FakeApi) TestEndpointParameters(number float32, double float64, patternWithoutDelimiter string, byte_ string, localVarOptionals map[string]interface{}) (*APIResponse, error) { @@ -134,8 +134,8 @@ func (a FakeApi) TestEndpointParameters(number float32, double float64, patternW var localVarFileBytes []byte // authentication '(http_basic_test)' required // http basic authentication required - if a.Configuration.Username != "" || a.Configuration.Password != ""{ - localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() + if a.Configuration.Username != "" || a.Configuration.Password != "" { + localVarHeaderParams["Authorization"] = "Basic " + a.Configuration.GetBasicAuthEncodedString() } // add default headers if any for key := range a.Configuration.DefaultHeader { @@ -143,7 +143,7 @@ func (a FakeApi) TestEndpointParameters(number float32, double float64, patternW } // to determine the Content-Type header - localVarHttpContentTypes := []string{ "application/xml; charset=utf-8", "application/json; charset=utf-8", } + localVarHttpContentTypes := []string{"application/xml; charset=utf-8", "application/json; charset=utf-8"} // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) @@ -154,7 +154,7 @@ func (a FakeApi) TestEndpointParameters(number float32, double float64, patternW localVarHttpHeaderAccepts := []string{ "application/xml; charset=utf-8", "application/json; charset=utf-8", - } + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) @@ -224,7 +224,7 @@ func (a FakeApi) TestEndpointParameters(number float32, double float64, patternW * @param "enumQueryString" (string) Query parameter enum test (string) * @param "enumQueryInteger" (int32) Query parameter enum test (double) * @param "enumQueryDouble" (float64) Query parameter enum test (double) - * @return + * @return */ func (a FakeApi) TestEnumParameters(localVarOptionals map[string]interface{}) (*APIResponse, error) { @@ -254,7 +254,7 @@ func (a FakeApi) TestEnumParameters(localVarOptionals map[string]interface{}) (* } // to determine the Content-Type header - localVarHttpContentTypes := []string{ "*/*", } + localVarHttpContentTypes := []string{"*/*"} // set Content-Type header localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) @@ -264,7 +264,7 @@ func (a FakeApi) TestEnumParameters(localVarOptionals map[string]interface{}) (* // to determine the Accept header localVarHttpHeaderAccepts := []string{ "*/*", - } + } // set Accept header localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) @@ -301,4 +301,3 @@ func (a FakeApi) TestEnumParameters(localVarOptionals map[string]interface{}) (* } return localVarAPIResponse, err } - diff --git a/samples/client/petstore/go/go-petstore/format_test.go b/samples/client/petstore/go/go-petstore/format_test.go index a4c8b307443..43125b9df34 100644 --- a/samples/client/petstore/go/go-petstore/format_test.go +++ b/samples/client/petstore/go/go-petstore/format_test.go @@ -22,7 +22,7 @@ type FormatTest struct { Int64_ int64 `json:"int64,omitempty"` - Number float32 `json:"number,omitempty"` + Number float32 `json:"number"` Float float32 `json:"float,omitempty"` @@ -30,15 +30,15 @@ type FormatTest struct { String_ string `json:"string,omitempty"` - Byte_ string `json:"byte,omitempty"` + Byte_ string `json:"byte"` Binary string `json:"binary,omitempty"` - Date time.Time `json:"date,omitempty"` + Date time.Time `json:"date"` DateTime time.Time `json:"dateTime,omitempty"` Uuid string `json:"uuid,omitempty"` - Password string `json:"password,omitempty"` + Password string `json:"password"` } diff --git a/samples/client/petstore/go/go-petstore/name.go b/samples/client/petstore/go/go-petstore/name.go index c29919ccb18..cd427f8a861 100644 --- a/samples/client/petstore/go/go-petstore/name.go +++ b/samples/client/petstore/go/go-petstore/name.go @@ -13,7 +13,7 @@ package petstore // Model for testing model name same as property name type Name struct { - Name int32 `json:"name,omitempty"` + Name int32 `json:"name"` SnakeCase int32 `json:"snake_case,omitempty"` diff --git a/samples/client/petstore/go/go-petstore/pet.go b/samples/client/petstore/go/go-petstore/pet.go index 7e44791e180..83763f9c2c7 100644 --- a/samples/client/petstore/go/go-petstore/pet.go +++ b/samples/client/petstore/go/go-petstore/pet.go @@ -16,9 +16,9 @@ type Pet struct { Category Category `json:"category,omitempty"` - Name string `json:"name,omitempty"` + Name string `json:"name"` - PhotoUrls []string `json:"photoUrls,omitempty"` + PhotoUrls []string `json:"photoUrls"` Tags []Tag `json:"tags,omitempty"` diff --git a/samples/client/petstore/go/go-petstore/pet_api.go b/samples/client/petstore/go/go-petstore/pet_api.go index a7c5d55d635..84984745dd5 100644 --- a/samples/client/petstore/go/go-petstore/pet_api.go +++ b/samples/client/petstore/go/go-petstore/pet_api.go @@ -203,8 +203,8 @@ func (a PetApi) FindPetsByStatus(status []string) ([]Pet, *APIResponse, error) { for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - var collectionFormat = "csv" - localVarQueryParams.Add("status", a.Configuration.APIClient.ParameterToString(status, collectionFormat)) + var statusCollectionFormat = "csv" + localVarQueryParams.Add("status", a.Configuration.APIClient.ParameterToString(status, statusCollectionFormat)) // to determine the Content-Type header localVarHttpContentTypes := []string{ } @@ -271,8 +271,8 @@ func (a PetApi) FindPetsByTags(tags []string) ([]Pet, *APIResponse, error) { for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] } - var collectionFormat = "csv" - localVarQueryParams.Add("tags", a.Configuration.APIClient.ParameterToString(tags, collectionFormat)) + var tagsCollectionFormat = "csv" + localVarQueryParams.Add("tags", a.Configuration.APIClient.ParameterToString(tags, tagsCollectionFormat)) // to determine the Content-Type header localVarHttpContentTypes := []string{ } diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index 565a50373fb..02f01a201ae 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -6,8 +6,10 @@ jar swagger-petstore-feign 1.0.0 + https://github.com/swagger-api/swagger-codegen + Swagger Java - scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git scm:git:git@github.com:swagger-api/swagger-codegen.git https://github.com/swagger-api/swagger-codegen @@ -23,6 +25,15 @@ + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + @@ -107,9 +118,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index 71c53530f48..73511cfb0d6 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -43,11 +43,11 @@ public class ApiClient { this(); for(String authName : authNames) { RequestInterceptor auth; - if (authName == "api_key") { + if ("api_key".equals(authName)) { auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "http_basic_test") { + } else if ("http_basic_test".equals(authName)) { auth = new HttpBasicAuth(); - } else if (authName == "petstore_auth") { + } else if ("petstore_auth".equals(authName)) { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); @@ -155,6 +155,9 @@ public class ApiClient { * apiClient.setBasePath("http://localhost:8080"); * XYZApi api = apiClient.buildClient(XYZApi.class); * XYZResponse response = api.someMethod(...); + * @param Type + * @param clientClass Client class + * @return The Client */ public T buildClient(Class clientClass) { return feignBuilder.target(clientClass, basePath); @@ -192,7 +195,7 @@ public class ApiClient { /** * Helper method to configure the first api key found - * @param apiKey + * @param apiKey API key */ public void setApiKey(String apiKey) { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -207,8 +210,8 @@ public class ApiClient { /** * Helper method to configure the username/password for basic auth or password OAuth - * @param username - * @param password + * @param username Username + * @param password Password */ public void setCredentials(String username, String password) { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -228,7 +231,7 @@ public class ApiClient { /** * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Token request builder */ public TokenRequestBuilder getTokenEndPoint() { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -242,7 +245,7 @@ public class ApiClient { /** * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Authentication request builder */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -256,8 +259,8 @@ public class ApiClient { /** * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken - * @param expiresIn : validity period in seconds + * @param accessToken Access Token + * @param expiresIn Validity period in seconds */ public void setAccessToken(String accessToken, Long expiresIn) { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -271,9 +274,9 @@ public class ApiClient { /** * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId - * @param clientSecret - * @param redirectURI + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -293,7 +296,7 @@ public class ApiClient { /** * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener + * @param accessTokenListener Acesss token listener */ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { @@ -305,14 +308,19 @@ public class ApiClient { } } + /** + * Gets request interceptor based on authentication name + * @param authName Authentiation name + * @return Request Interceptor + */ public RequestInterceptor getAuthorization(String authName) { return apiAuthorizations.get(authName); } /** * Adds an authorization to be used by the client - * @param authName - * @param authorization + * @param authName Authentication name + * @param authorization Request interceptor */ public void addAuthorization(String authName, RequestInterceptor authorization) { if (apiAuthorizations.containsKey(authName)) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java index 7829b25fec7..fdace62d9b0 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/FakeApi.java @@ -20,7 +20,7 @@ public interface FakeApi extends ApiClient.Api { /** * To test \"client\" model * To test \"client\" model - * @param body client model (required) + * @param body client model (required) * @return Client */ @RequestLine("PATCH /fake") @@ -33,21 +33,20 @@ public interface FakeApi extends ApiClient.Api { /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @return void + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) */ @RequestLine("POST /fake") @Headers({ @@ -59,15 +58,14 @@ public interface FakeApi extends ApiClient.Api { /** * To test enum parameters * To test enum parameters - * @param enumFormStringArray Form parameter enum test (string array) (optional) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @param enumHeaderStringArray Header parameter enum test (string array) (optional) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return void + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) */ @RequestLine("GET /fake?enum_query_string_array={enumQueryStringArray}&enum_query_string={enumQueryString}&enum_query_integer={enumQueryInteger}") @Headers({ diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java deleted file mode 100644 index d715f9a6918..00000000000 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java +++ /dev/null @@ -1,29 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.client.ApiClient; - -import io.swagger.client.model.Client; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import feign.*; - - -public interface Fake_classname_tags123Api extends ApiClient.Api { - - - /** - * To test class name in snake case - * - * @param body client model (required) - * @return Client - */ - @RequestLine("PATCH /fake_classname_test") - @Headers({ - "Content-Type: application/json", - "Accept: application/json", - }) - Client testClassname(Client body); -} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index b2b713992e3..05133620f82 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -19,8 +19,7 @@ public interface PetApi extends ApiClient.Api { /** * Add a new pet to the store * - * @param body Pet object that needs to be added to the store (required) - * @return void + * @param body Pet object that needs to be added to the store (required) */ @RequestLine("POST /pet") @Headers({ @@ -32,9 +31,8 @@ public interface PetApi extends ApiClient.Api { /** * Deletes a pet * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return void + * @param petId Pet id to delete (required) + * @param apiKey (optional) */ @RequestLine("DELETE /pet/{petId}") @Headers({ @@ -47,8 +45,8 @@ public interface PetApi extends ApiClient.Api { /** * 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) - * @return List + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> */ @RequestLine("GET /pet/findByStatus?status={status}") @Headers({ @@ -60,8 +58,8 @@ public interface PetApi extends ApiClient.Api { /** * 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) - * @return List + * @param tags Tags to filter by (required) + * @return List<Pet> */ @RequestLine("GET /pet/findByTags?tags={tags}") @Headers({ @@ -73,7 +71,7 @@ public interface PetApi extends ApiClient.Api { /** * Find pet by ID * Returns a single pet - * @param petId ID of pet to return (required) + * @param petId ID of pet to return (required) * @return Pet */ @RequestLine("GET /pet/{petId}") @@ -86,8 +84,7 @@ public interface PetApi extends ApiClient.Api { /** * Update an existing pet * - * @param body Pet object that needs to be added to the store (required) - * @return void + * @param body Pet object that needs to be added to the store (required) */ @RequestLine("PUT /pet") @Headers({ @@ -99,10 +96,9 @@ public interface PetApi extends ApiClient.Api { /** * 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 (optional) - * @param status Updated status of the pet (optional) - * @return void + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) */ @RequestLine("POST /pet/{petId}") @Headers({ @@ -114,9 +110,9 @@ public interface PetApi extends ApiClient.Api { /** * uploads an image * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) * @return ModelApiResponse */ @RequestLine("POST /pet/{petId}/uploadImage") diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java index a0d06d34dd8..9e1ecddbece 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java @@ -17,8 +17,7 @@ public interface StoreApi extends ApiClient.Api { /** * 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) - * @return void + * @param orderId ID of the order that needs to be deleted (required) */ @RequestLine("DELETE /store/order/{orderId}") @Headers({ @@ -30,7 +29,7 @@ public interface StoreApi extends ApiClient.Api { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Map + * @return Map<String, Integer> */ @RequestLine("GET /store/inventory") @Headers({ @@ -42,7 +41,7 @@ public interface StoreApi extends ApiClient.Api { /** * 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) + * @param orderId ID of pet that needs to be fetched (required) * @return Order */ @RequestLine("GET /store/order/{orderId}") @@ -55,7 +54,7 @@ public interface StoreApi extends ApiClient.Api { /** * Place an order for a pet * - * @param body order placed for purchasing the pet (required) + * @param body order placed for purchasing the pet (required) * @return Order */ @RequestLine("POST /store/order") diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java index d4f59bffc4c..ae2ea06f9b6 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java @@ -17,8 +17,7 @@ public interface UserApi extends ApiClient.Api { /** * Create user * This can only be done by the logged in user. - * @param body Created user object (required) - * @return void + * @param body Created user object (required) */ @RequestLine("POST /user") @Headers({ @@ -30,8 +29,7 @@ public interface UserApi extends ApiClient.Api { /** * Creates list of users with given input array * - * @param body List of user object (required) - * @return void + * @param body List of user object (required) */ @RequestLine("POST /user/createWithArray") @Headers({ @@ -43,8 +41,7 @@ public interface UserApi extends ApiClient.Api { /** * Creates list of users with given input array * - * @param body List of user object (required) - * @return void + * @param body List of user object (required) */ @RequestLine("POST /user/createWithList") @Headers({ @@ -56,8 +53,7 @@ public interface UserApi extends ApiClient.Api { /** * Delete user * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return void + * @param username The name that needs to be deleted (required) */ @RequestLine("DELETE /user/{username}") @Headers({ @@ -69,7 +65,7 @@ public interface UserApi extends ApiClient.Api { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param username The name that needs to be fetched. Use user1 for testing. (required) * @return User */ @RequestLine("GET /user/{username}") @@ -82,8 +78,8 @@ public interface UserApi extends ApiClient.Api { /** * Logs user into the system * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) + * @param username The user name for login (required) + * @param password The password for login in clear text (required) * @return String */ @RequestLine("GET /user/login?username={username}&password={password}") @@ -96,7 +92,6 @@ public interface UserApi extends ApiClient.Api { /** * Logs out current logged in user session * - * @return void */ @RequestLine("GET /user/logout") @Headers({ @@ -108,9 +103,8 @@ public interface UserApi extends ApiClient.Api { /** * Updated user * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return void + * @param username name that need to be deleted (required) + * @param body Updated user object (required) */ @RequestLine("PUT /user/{username}") @Headers({ diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java index 8fc61b6891a..7c570ce933d 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Animal.java @@ -24,10 +24,12 @@ import io.swagger.annotations.ApiModelProperty; /** * Animal */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) -@JsonSubTypes({ - @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), +@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"), }) + public class Animal { @JsonProperty("className") private String className = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Capitalization.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Capitalization.java new file mode 100644 index 00000000000..1466f669520 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Capitalization.java @@ -0,0 +1,204 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(example = "null", value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(example = "null", value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java index 3c43e963b04..c2c9d6b084b 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/EnumTest.java @@ -31,7 +31,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/jersey1/docs/Capitalization.md b/samples/client/petstore/java/jersey1/docs/Capitalization.md new file mode 100644 index 00000000000..0f3064c1996 --- /dev/null +++ b/samples/client/petstore/java/jersey1/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] + + + diff --git a/samples/client/petstore/java/jersey1/docs/EnumTest.md b/samples/client/petstore/java/jersey1/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/jersey1/docs/EnumTest.md +++ b/samples/client/petstore/java/jersey1/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/jersey1/pom.xml b/samples/client/petstore/java/jersey1/pom.xml index 55e69510b52..4b77db8722b 100644 --- a/samples/client/petstore/java/jersey1/pom.xml +++ b/samples/client/petstore/java/jersey1/pom.xml @@ -6,7 +6,13 @@ jar swagger-java-client 1.0.0 - + https://github.com/swagger-api/swagger-codegen + Swagger Java + + scm:git:git@github.com:swagger-api/swagger-codegen.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + 2.2.0 @@ -19,6 +25,15 @@ + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + @@ -113,9 +128,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java index 4530c4900bf..cd3bdff27d9 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/ApiClient.java @@ -109,6 +109,7 @@ public class ApiClient { * Build the Client used to make HTTP requests with the latest settings, * i.e. objectMapper and debugging. * TODO: better to use the Builder Pattern? + * @return API client */ public ApiClient rebuildHttpClient() { // Add the JSON serialization support to Jersey @@ -129,6 +130,7 @@ public class ApiClient { * Note: If you make changes to the object mapper, remember to set it back via * setObjectMapper in order to trigger HTTP client rebuilding. *

    + * @return Object mapper */ public ObjectMapper getObjectMapper() { return objectMapper; @@ -161,6 +163,7 @@ public class ApiClient { /** * Gets the status code of the previous request + * @return Status code */ public int getStatusCode() { return statusCode; @@ -168,6 +171,7 @@ public class ApiClient { /** * Gets the response headers of the previous request + * @return Response headers */ public Map> getResponseHeaders() { return responseHeaders; @@ -175,6 +179,7 @@ public class ApiClient { /** * Get authentications (key: authentication name, value: authentication). + * @return Map of authentication */ public Map getAuthentications() { return authentications; @@ -192,6 +197,7 @@ public class ApiClient { /** * Helper method to set username for the first HTTP basic authentication. + * @param username Username */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { @@ -205,6 +211,7 @@ public class ApiClient { /** * Helper method to set password for the first HTTP basic authentication. + * @param password Password */ public void setPassword(String password) { for (Authentication auth : authentications.values()) { @@ -218,6 +225,7 @@ public class ApiClient { /** * Helper method to set API key value for the first API key authentication. + * @param apiKey API key */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { @@ -231,6 +239,7 @@ public class ApiClient { /** * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix API key prefix */ public void setApiKeyPrefix(String apiKeyPrefix) { for (Authentication auth : authentications.values()) { @@ -244,6 +253,7 @@ public class ApiClient { /** * Helper method to set access token for the first OAuth2 authentication. + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for (Authentication auth : authentications.values()) { @@ -257,6 +267,8 @@ public class ApiClient { /** * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent User agent + * @return API client */ public ApiClient setUserAgent(String userAgent) { addDefaultHeader("User-Agent", userAgent); @@ -268,6 +280,7 @@ public class ApiClient { * * @param key The header's key * @param value The header's value + * @return API client */ public ApiClient addDefaultHeader(String key, String value) { defaultHeaderMap.put(key, value); @@ -276,6 +289,7 @@ public class ApiClient { /** * Check that whether debugging is enabled for this API client. + * @return True if debugging is on */ public boolean isDebugging() { return debugging; @@ -285,6 +299,7 @@ public class ApiClient { * Enable/disable debugging for this API client. * * @param debugging To enable (true) or disable (false) debugging + * @return API client */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; @@ -295,6 +310,7 @@ public class ApiClient { /** * Connect timeout (in milliseconds). + * @return Connection timeout */ public int getConnectTimeout() { return connectionTimeout; @@ -304,6 +320,8 @@ public class ApiClient { * Set the connect timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and * {@link Integer#MAX_VALUE}. + * @param connectionTimeout Connection timeout in milliseconds + * @return API client */ public ApiClient setConnectTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; @@ -313,6 +331,7 @@ public class ApiClient { /** * Get the date format used to parse/format date parameters. + * @return Date format */ public DateFormat getDateFormat() { return dateFormat; @@ -320,6 +339,8 @@ public class ApiClient { /** * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client */ public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; @@ -332,6 +353,8 @@ public class ApiClient { /** * Parse the given string into Date object. + * @param str String + * @return Date */ public Date parseDate(String str) { try { @@ -343,6 +366,8 @@ public class ApiClient { /** * Format the given Date object into string. + * @param date Date + * @return Date in string format */ public String formatDate(Date date) { return dateFormat.format(date); @@ -350,6 +375,8 @@ public class ApiClient { /** * Format the given parameter object into string. + * @param param Object + * @return Object in string format */ public String parameterToString(Object param) { if (param == null) { @@ -371,8 +398,12 @@ public class ApiClient { } /* - Format to {@code Pair} objects. - */ + * Format to {@code Pair} objects. + * @param collectionFormat Collection format + * @param name Name + * @param value Value + * @return List of pair + */ public List parameterToPairs(String collectionFormat, String name, Object value){ List params = new ArrayList(); @@ -432,6 +463,8 @@ public class ApiClient { * application/json * application/json; charset=UTF8 * APPLICATION/JSON + * @param mime MIME + * @return True if MIME type is boolean */ public boolean isJsonMime(String mime) { return mime != null && mime.matches("(?i)application\\/json(;.*)?"); @@ -481,6 +514,8 @@ public class ApiClient { /** * Escape the given string to be used as URL query value. + * @param str String + * @return Escaped string */ public String escapeString(String str) { try { @@ -493,6 +528,11 @@ public class ApiClient { /** * Serialize the given Java object into string according the given * Content-Type (only JSON is supported for now). + * @param obj Object + * @param contentType Content type + * @param formParams Form parameters + * @return Object + * @throws ApiException API exception */ public Object serialize(Object obj, String contentType, Map formParams) throws ApiException { if (contentType.startsWith("multipart/form-data")) { @@ -598,6 +638,7 @@ public class ApiClient { /** * Invoke API by sending HTTP request with the given options. * + * @param Type * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param queryParams The query parameters @@ -607,7 +648,9 @@ public class ApiClient { * @param accept The request's Accept header * @param contentType The request's Content-Type header * @param authNames The authentications to apply + * @param returnType Return type * @return The response body in type of string + * @throws ApiException API exception */ public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { @@ -646,6 +689,8 @@ public class ApiClient { * Update query and header parameters based on authentication settings. * * @param authNames The authentications to apply + * @param queryParams Query parameters + * @param headerParams Header parameters */ private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { for (String authName : authNames) { @@ -657,6 +702,8 @@ public class ApiClient { /** * Encode the given form parameters as request body. + * @param formParams Form parameters + * @return HTTP form encoded parameters */ private String getXWWWFormUrlencodedParams(Map formParams) { StringBuilder formParamBuilder = new StringBuilder(); diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java deleted file mode 100644 index 9c1fc66b19a..00000000000 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - -package io.swagger.client.api; - -import com.sun.jersey.api.client.GenericType; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.model.*; -import io.swagger.client.Pair; - -import io.swagger.client.model.Client; - - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class Fake_classname_tags123Api { - private ApiClient apiClient; - - public Fake_classname_tags123Api() { - this(Configuration.getDefaultApiClient()); - } - - public Fake_classname_tags123Api(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * To test class name in snake case - * - * @param body client model (required) - * @return Client - * @throws ApiException if fails to make API call - */ - public Client testClassname(Client 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 testClassname"); - } - - // create path and map variables - String localVarPath = "/fake_classname_test".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } -} diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java index 301e4efe99c..2d67203c51e 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/PetApi.java @@ -138,7 +138,7 @@ public class PetApi { * 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) - * @return List + * @return List<Pet> * @throws ApiException if fails to make API call */ public List findPetsByStatus(List status) throws ApiException { @@ -180,7 +180,7 @@ public class PetApi { * 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) - * @return List + * @return List<Pet> * @throws ApiException if fails to make API call */ public List findPetsByTags(List tags) throws ApiException { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java index d6ab1a49e7c..74bd29b88b0 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/api/StoreApi.java @@ -92,7 +92,7 @@ public class StoreApi { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Map + * @return Map<String, Integer> * @throws ApiException if fails to make API call */ public Map getInventory() throws ApiException { diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java index 8fc61b6891a..7c570ce933d 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Animal.java @@ -24,10 +24,12 @@ import io.swagger.annotations.ApiModelProperty; /** * Animal */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) -@JsonSubTypes({ - @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), +@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"), }) + public class Animal { @JsonProperty("className") private String className = null; diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Capitalization.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Capitalization.java new file mode 100644 index 00000000000..1466f669520 --- /dev/null +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/Capitalization.java @@ -0,0 +1,204 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(example = "null", value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(example = "null", value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java index 3c43e963b04..c2c9d6b084b 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey1/src/main/java/io/swagger/client/model/EnumTest.java @@ -31,7 +31,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/jersey2-java6/docs/EnumTest.md b/samples/client/petstore/java/jersey2-java6/docs/EnumTest.md index deb1951c552..29b6d288c8f 100644 --- a/samples/client/petstore/java/jersey2-java6/docs/EnumTest.md +++ b/samples/client/petstore/java/jersey2-java6/docs/EnumTest.md @@ -15,6 +15,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/jersey2-java6/effective.pom b/samples/client/petstore/java/jersey2-java6/effective.pom new file mode 100644 index 00000000000..70b95f7d5b5 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java6/effective.pom @@ -0,0 +1,431 @@ + + + + + + + + + + + + + + + + 4.0.0 + io.swagger + swagger-petstore-jersey2-java6 + 1.0.0 + swagger-petstore-jersey2-java6 + + 2.2.0 + + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.5 + 3.5 + 2.7.5 + 2.22.2 + 2.9.4 + 4.12 + 1.0.0 + 1.5.9 + + + + io.swagger + swagger-annotations + 1.5.9 + compile + + + org.glassfish.jersey.core + jersey-client + 2.22.2 + compile + + + org.glassfish.jersey.media + jersey-media-multipart + 2.22.2 + compile + + + org.glassfish.jersey.media + jersey-media-json-jackson + 2.22.2 + compile + + + com.fasterxml.jackson.core + jackson-core + 2.7.5 + compile + + + com.fasterxml.jackson.core + jackson-annotations + 2.7.5 + compile + + + com.fasterxml.jackson.core + jackson-databind + 2.7.5 + compile + + + com.fasterxml.jackson.datatype + jackson-datatype-joda + 2.7.5 + compile + + + joda-time + joda-time + 2.9.4 + compile + + + com.brsanthu + migbase64 + 2.2 + compile + + + org.apache.commons + commons-lang3 + 3.5 + compile + + + commons-io + commons-io + 2.5 + compile + + + junit + junit + 4.12 + test + + + + + + false + + central + Central Repository + https://repo.maven.apache.org/maven2 + + + + + + never + + + false + + central + Central Repository + https://repo.maven.apache.org/maven2 + + + + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/src/main/java + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/src/main/scripts + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/src/test/java + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/target/classes + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/target/test-classes + + + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/src/main/resources + + + + + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/src/test/resources + + + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/target + swagger-petstore-jersey2-java6-1.0.0 + + + + maven-antrun-plugin + 1.3 + + + maven-assembly-plugin + 2.2-beta-5 + + + maven-dependency-plugin + 2.8 + + + maven-release-plugin + 2.3.2 + + + + + + maven-surefire-plugin + 2.12 + + + default-test + test + + test + + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + 2.8 + + + package + + copy-dependencies + + + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/target/lib + + + + + + maven-jar-plugin + 2.6 + + + default-jar + package + + jar + + + + + + jar + test-jar + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.12 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + maven-compiler-plugin + 2.5.1 + + + default-compile + compile + + compile + + + 1.7 + 1.7 + + + + default-testCompile + test-compile + + testCompile + + + 1.7 + 1.7 + + + + + 1.7 + 1.7 + + + + maven-javadoc-plugin + 2.10.4 + + + maven-clean-plugin + 2.5 + + + default-clean + clean + + clean + + + + + + maven-resources-plugin + 2.6 + + + default-testResources + process-test-resources + + testResources + + + + default-resources + process-resources + + resources + + + + + + maven-install-plugin + 2.4 + + + default-install + install + + install + + + + + + maven-deploy-plugin + 2.7 + + + default-deploy + deploy + + deploy + + + + + + maven-site-plugin + 3.3 + + + default-site + site + + site + + + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/target/site + + + org.apache.maven.plugins + maven-project-info-reports-plugin + + + + + + default-deploy + site-deploy + + deploy + + + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/target/site + + + org.apache.maven.plugins + maven-project-info-reports-plugin + + + + + + + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/target/site + + + org.apache.maven.plugins + maven-project-info-reports-plugin + + + + + + + + /Users/williamcheng/Code/jan2017/swagger-codegen/samples/client/petstore/java/jersey2-java6/target/site + + \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/model/EnumTest.java index c57488dbf7b..efa77302887 100644 --- a/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2-java6/src/main/java/io/swagger/client/model/EnumTest.java @@ -42,7 +42,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/jersey2-java8/docs/Capitalization.md b/samples/client/petstore/java/jersey2-java8/docs/Capitalization.md new file mode 100644 index 00000000000..0f3064c1996 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/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] + + + diff --git a/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md b/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md +++ b/samples/client/petstore/java/jersey2-java8/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/jersey2-java8/pom.xml b/samples/client/petstore/java/jersey2-java8/pom.xml index 7e8523783d2..be696a53993 100644 --- a/samples/client/petstore/java/jersey2-java8/pom.xml +++ b/samples/client/petstore/java/jersey2-java8/pom.xml @@ -6,8 +6,10 @@ jar swagger-petstore-jersey2 1.0.0 + https://github.com/swagger-api/swagger-codegen + Swagger Java - scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git scm:git:git@github.com:swagger-api/swagger-codegen.git https://github.com/swagger-api/swagger-codegen @@ -22,7 +24,16 @@ repo - + + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + @@ -116,9 +127,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java index adec2801d00..3e2dab9ee91 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/ApiClient.java @@ -86,6 +86,7 @@ public class ApiClient { /** * Gets the JSON instance to do JSON serialization and deserialization. + * @return JSON */ public JSON getJSON() { return json; @@ -111,6 +112,7 @@ public class ApiClient { /** * Gets the status code of the previous request + * @return Status code */ public int getStatusCode() { return statusCode; @@ -118,6 +120,7 @@ public class ApiClient { /** * Gets the response headers of the previous request + * @return Response headers */ public Map> getResponseHeaders() { return responseHeaders; @@ -125,6 +128,7 @@ public class ApiClient { /** * Get authentications (key: authentication name, value: authentication). + * @return Map of authentication object */ public Map getAuthentications() { return authentications; @@ -142,6 +146,7 @@ public class ApiClient { /** * Helper method to set username for the first HTTP basic authentication. + * @param username Username */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { @@ -155,6 +160,7 @@ public class ApiClient { /** * Helper method to set password for the first HTTP basic authentication. + * @param password Password */ public void setPassword(String password) { for (Authentication auth : authentications.values()) { @@ -168,6 +174,7 @@ public class ApiClient { /** * Helper method to set API key value for the first API key authentication. + * @param apiKey API key */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { @@ -181,6 +188,7 @@ public class ApiClient { /** * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix API key prefix */ public void setApiKeyPrefix(String apiKeyPrefix) { for (Authentication auth : authentications.values()) { @@ -194,6 +202,7 @@ public class ApiClient { /** * Helper method to set access token for the first OAuth2 authentication. + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for (Authentication auth : authentications.values()) { @@ -207,6 +216,8 @@ public class ApiClient { /** * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent Http user agent + * @return API client */ public ApiClient setUserAgent(String userAgent) { addDefaultHeader("User-Agent", userAgent); @@ -218,6 +229,7 @@ public class ApiClient { * * @param key The header's key * @param value The header's value + * @return API client */ public ApiClient addDefaultHeader(String key, String value) { defaultHeaderMap.put(key, value); @@ -226,6 +238,7 @@ public class ApiClient { /** * Check that whether debugging is enabled for this API client. + * @return True if debugging is switched on */ public boolean isDebugging() { return debugging; @@ -235,6 +248,7 @@ public class ApiClient { * Enable/disable debugging for this API client. * * @param debugging To enable (true) or disable (false) debugging + * @return API client */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; @@ -248,12 +262,17 @@ public class ApiClient { * with file response. The default value is null, i.e. using * the system's default tempopary folder. * - * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) + * @return Temp folder path */ public String getTempFolderPath() { return tempFolderPath; } + /** + * Set temp folder path + * @param tempFolderPath Temp folder path + * @return API client + */ public ApiClient setTempFolderPath(String tempFolderPath) { this.tempFolderPath = tempFolderPath; return this; @@ -261,6 +280,7 @@ public class ApiClient { /** * Connect timeout (in milliseconds). + * @return Connection timeout */ public int getConnectTimeout() { return connectionTimeout; @@ -270,6 +290,8 @@ public class ApiClient { * Set the connect timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and * {@link Integer#MAX_VALUE}. + * @param connectionTimeout Connection timeout in milliseconds + * @return API client */ public ApiClient setConnectTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; @@ -279,6 +301,7 @@ public class ApiClient { /** * Get the date format used to parse/format date parameters. + * @return Date format */ public DateFormat getDateFormat() { return dateFormat; @@ -286,6 +309,8 @@ public class ApiClient { /** * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client */ public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; @@ -296,6 +321,8 @@ public class ApiClient { /** * Parse the given string into Date object. + * @param str String + * @return Date */ public Date parseDate(String str) { try { @@ -307,6 +334,8 @@ public class ApiClient { /** * Format the given Date object into string. + * @param date Date + * @return Date in string format */ public String formatDate(Date date) { return dateFormat.format(date); @@ -314,6 +343,8 @@ public class ApiClient { /** * Format the given parameter object into string. + * @param param Object + * @return Object in string format */ public String parameterToString(Object param) { if (param == null) { @@ -335,8 +366,12 @@ public class ApiClient { } /* - Format to {@code Pair} objects. - */ + * Format to {@code Pair} objects. + * @param collectionFormat Collection format + * @param name Name + * @param value Value + * @return List of pairs + */ public List parameterToPairs(String collectionFormat, String name, Object value){ List params = new ArrayList(); @@ -355,8 +390,8 @@ public class ApiClient { return params; } - // get the collection format - String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + // get the collection format (default: csv) + String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // create the params based on the collection format if ("multi".equals(format)) { @@ -396,6 +431,8 @@ public class ApiClient { * application/json * application/json; charset=UTF8 * APPLICATION/JSON + * @param mime MIME + * @return True if the MIME type is JSON */ public boolean isJsonMime(String mime) { return mime != null && mime.matches("(?i)application\\/json(;.*)?"); @@ -445,6 +482,8 @@ public class ApiClient { /** * Escape the given string to be used as URL query value. + * @param str String + * @return Escaped string */ public String escapeString(String str) { try { @@ -457,6 +496,11 @@ public class ApiClient { /** * Serialize the given Java object into string entity according the given * Content-Type (only JSON is supported for now). + * @param obj Object + * @param formParams Form parameters + * @param contentType Context type + * @return Entity + * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { Entity entity; @@ -489,6 +533,11 @@ public class ApiClient { /** * Deserialize response body to Java object according to the Content-Type. + * @param Type + * @param response Response + * @param returnType Return type + * @return Deserialize object + * @throws ApiException API exception */ @SuppressWarnings("unchecked") public T deserialize(Response response, GenericType returnType) throws ApiException { @@ -517,6 +566,8 @@ public class ApiClient { /** * Download file from the given response. + * @param response Response + * @return File * @throws ApiException If fail to read file content from response and write to disk */ public File downloadFileFromResponse(Response response) throws ApiException { @@ -567,6 +618,7 @@ public class ApiClient { /** * Invoke API by sending HTTP request with the given options. * + * @param Type * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param queryParams The query parameters @@ -578,6 +630,7 @@ public class ApiClient { * @param authNames The authentications to apply * @param returnType The return type into which to deserialize the response * @return The response body in type of string + * @throws ApiException API exception */ public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); @@ -662,6 +715,8 @@ public class ApiClient { /** * Build the Client used to make HTTP requests. + * @param debugging Debug setting + * @return Client */ private Client buildHttpClient(boolean debugging) { final ClientConfig clientConfig = new ClientConfig(); diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java index 9ac544ae906..f768699c7f6 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/JSON.java @@ -25,6 +25,7 @@ public class JSON implements ContextResolver { /** * Set the date format for JSON (de)serialization with Date properties. + * @param dateFormat Date format */ public void setDateFormat(DateFormat dateFormat) { mapper.setDateFormat(dateFormat); diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java deleted file mode 100644 index de60566e861..00000000000 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java +++ /dev/null @@ -1,78 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; - -import javax.ws.rs.core.GenericType; - -import io.swagger.client.model.Client; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class Fake_classname_tags123Api { - private ApiClient apiClient; - - public Fake_classname_tags123Api() { - this(Configuration.getDefaultApiClient()); - } - - public Fake_classname_tags123Api(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * To test class name in snake case - * - * @param body client model (required) - * @return Client - * @throws ApiException if fails to make API call - */ - public Client testClassname(Client 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 testClassname"); - } - - // create path and map variables - String localVarPath = "/fake_classname_test".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } -} diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java index 131088873d1..e816fce5bad 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/PetApi.java @@ -124,7 +124,7 @@ public class PetApi { * 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) - * @return List + * @return List<Pet> * @throws ApiException if fails to make API call */ public List findPetsByStatus(List status) throws ApiException { @@ -166,7 +166,7 @@ public class PetApi { * 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) - * @return List + * @return List<Pet> * @throws ApiException if fails to make API call */ public List findPetsByTags(List tags) throws ApiException { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java index c0c9a166ad7..41bd6751871 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/api/StoreApi.java @@ -78,7 +78,7 @@ public class StoreApi { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Map + * @return Map<String, Integer> * @throws ApiException if fails to make API call */ public Map getInventory() throws ApiException { diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java index 8fc61b6891a..7c570ce933d 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Animal.java @@ -24,10 +24,12 @@ import io.swagger.annotations.ApiModelProperty; /** * Animal */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) -@JsonSubTypes({ - @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), +@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"), }) + public class Animal { @JsonProperty("className") private String className = null; diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Capitalization.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Capitalization.java new file mode 100644 index 00000000000..1466f669520 --- /dev/null +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/Capitalization.java @@ -0,0 +1,204 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(example = "null", value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(example = "null", value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java index 3c43e963b04..c2c9d6b084b 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/io/swagger/client/model/EnumTest.java @@ -31,7 +31,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/jersey2/docs/Capitalization.md b/samples/client/petstore/java/jersey2/docs/Capitalization.md new file mode 100644 index 00000000000..0f3064c1996 --- /dev/null +++ b/samples/client/petstore/java/jersey2/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] + + + diff --git a/samples/client/petstore/java/jersey2/docs/EnumTest.md b/samples/client/petstore/java/jersey2/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/jersey2/docs/EnumTest.md +++ b/samples/client/petstore/java/jersey2/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/jersey2/pom.xml b/samples/client/petstore/java/jersey2/pom.xml index 69dd6c87f0e..aba408069a9 100644 --- a/samples/client/petstore/java/jersey2/pom.xml +++ b/samples/client/petstore/java/jersey2/pom.xml @@ -6,8 +6,10 @@ jar swagger-petstore-jersey2 1.0.0 + https://github.com/swagger-api/swagger-codegen + Swagger Java - scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git scm:git:git@github.com:swagger-api/swagger-codegen.git https://github.com/swagger-api/swagger-codegen @@ -22,7 +24,16 @@ repo - + + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + @@ -116,9 +127,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index adec2801d00..3e2dab9ee91 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -86,6 +86,7 @@ public class ApiClient { /** * Gets the JSON instance to do JSON serialization and deserialization. + * @return JSON */ public JSON getJSON() { return json; @@ -111,6 +112,7 @@ public class ApiClient { /** * Gets the status code of the previous request + * @return Status code */ public int getStatusCode() { return statusCode; @@ -118,6 +120,7 @@ public class ApiClient { /** * Gets the response headers of the previous request + * @return Response headers */ public Map> getResponseHeaders() { return responseHeaders; @@ -125,6 +128,7 @@ public class ApiClient { /** * Get authentications (key: authentication name, value: authentication). + * @return Map of authentication object */ public Map getAuthentications() { return authentications; @@ -142,6 +146,7 @@ public class ApiClient { /** * Helper method to set username for the first HTTP basic authentication. + * @param username Username */ public void setUsername(String username) { for (Authentication auth : authentications.values()) { @@ -155,6 +160,7 @@ public class ApiClient { /** * Helper method to set password for the first HTTP basic authentication. + * @param password Password */ public void setPassword(String password) { for (Authentication auth : authentications.values()) { @@ -168,6 +174,7 @@ public class ApiClient { /** * Helper method to set API key value for the first API key authentication. + * @param apiKey API key */ public void setApiKey(String apiKey) { for (Authentication auth : authentications.values()) { @@ -181,6 +188,7 @@ public class ApiClient { /** * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix API key prefix */ public void setApiKeyPrefix(String apiKeyPrefix) { for (Authentication auth : authentications.values()) { @@ -194,6 +202,7 @@ public class ApiClient { /** * Helper method to set access token for the first OAuth2 authentication. + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for (Authentication auth : authentications.values()) { @@ -207,6 +216,8 @@ public class ApiClient { /** * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent Http user agent + * @return API client */ public ApiClient setUserAgent(String userAgent) { addDefaultHeader("User-Agent", userAgent); @@ -218,6 +229,7 @@ public class ApiClient { * * @param key The header's key * @param value The header's value + * @return API client */ public ApiClient addDefaultHeader(String key, String value) { defaultHeaderMap.put(key, value); @@ -226,6 +238,7 @@ public class ApiClient { /** * Check that whether debugging is enabled for this API client. + * @return True if debugging is switched on */ public boolean isDebugging() { return debugging; @@ -235,6 +248,7 @@ public class ApiClient { * Enable/disable debugging for this API client. * * @param debugging To enable (true) or disable (false) debugging + * @return API client */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; @@ -248,12 +262,17 @@ public class ApiClient { * with file response. The default value is null, i.e. using * the system's default tempopary folder. * - * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) + * @return Temp folder path */ public String getTempFolderPath() { return tempFolderPath; } + /** + * Set temp folder path + * @param tempFolderPath Temp folder path + * @return API client + */ public ApiClient setTempFolderPath(String tempFolderPath) { this.tempFolderPath = tempFolderPath; return this; @@ -261,6 +280,7 @@ public class ApiClient { /** * Connect timeout (in milliseconds). + * @return Connection timeout */ public int getConnectTimeout() { return connectionTimeout; @@ -270,6 +290,8 @@ public class ApiClient { * Set the connect timeout (in milliseconds). * A value of 0 means no timeout, otherwise values must be between 1 and * {@link Integer#MAX_VALUE}. + * @param connectionTimeout Connection timeout in milliseconds + * @return API client */ public ApiClient setConnectTimeout(int connectionTimeout) { this.connectionTimeout = connectionTimeout; @@ -279,6 +301,7 @@ public class ApiClient { /** * Get the date format used to parse/format date parameters. + * @return Date format */ public DateFormat getDateFormat() { return dateFormat; @@ -286,6 +309,8 @@ public class ApiClient { /** * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client */ public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; @@ -296,6 +321,8 @@ public class ApiClient { /** * Parse the given string into Date object. + * @param str String + * @return Date */ public Date parseDate(String str) { try { @@ -307,6 +334,8 @@ public class ApiClient { /** * Format the given Date object into string. + * @param date Date + * @return Date in string format */ public String formatDate(Date date) { return dateFormat.format(date); @@ -314,6 +343,8 @@ public class ApiClient { /** * Format the given parameter object into string. + * @param param Object + * @return Object in string format */ public String parameterToString(Object param) { if (param == null) { @@ -335,8 +366,12 @@ public class ApiClient { } /* - Format to {@code Pair} objects. - */ + * Format to {@code Pair} objects. + * @param collectionFormat Collection format + * @param name Name + * @param value Value + * @return List of pairs + */ public List parameterToPairs(String collectionFormat, String name, Object value){ List params = new ArrayList(); @@ -355,8 +390,8 @@ public class ApiClient { return params; } - // get the collection format - String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + // get the collection format (default: csv) + String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // create the params based on the collection format if ("multi".equals(format)) { @@ -396,6 +431,8 @@ public class ApiClient { * application/json * application/json; charset=UTF8 * APPLICATION/JSON + * @param mime MIME + * @return True if the MIME type is JSON */ public boolean isJsonMime(String mime) { return mime != null && mime.matches("(?i)application\\/json(;.*)?"); @@ -445,6 +482,8 @@ public class ApiClient { /** * Escape the given string to be used as URL query value. + * @param str String + * @return Escaped string */ public String escapeString(String str) { try { @@ -457,6 +496,11 @@ public class ApiClient { /** * Serialize the given Java object into string entity according the given * Content-Type (only JSON is supported for now). + * @param obj Object + * @param formParams Form parameters + * @param contentType Context type + * @return Entity + * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { Entity entity; @@ -489,6 +533,11 @@ public class ApiClient { /** * Deserialize response body to Java object according to the Content-Type. + * @param Type + * @param response Response + * @param returnType Return type + * @return Deserialize object + * @throws ApiException API exception */ @SuppressWarnings("unchecked") public T deserialize(Response response, GenericType returnType) throws ApiException { @@ -517,6 +566,8 @@ public class ApiClient { /** * Download file from the given response. + * @param response Response + * @return File * @throws ApiException If fail to read file content from response and write to disk */ public File downloadFileFromResponse(Response response) throws ApiException { @@ -567,6 +618,7 @@ public class ApiClient { /** * Invoke API by sending HTTP request with the given options. * + * @param Type * @param path The sub-path of the HTTP URL * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" * @param queryParams The query parameters @@ -578,6 +630,7 @@ public class ApiClient { * @param authNames The authentications to apply * @param returnType The return type into which to deserialize the response * @return The response body in type of string + * @throws ApiException API exception */ public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); @@ -662,6 +715,8 @@ public class ApiClient { /** * Build the Client used to make HTTP requests. + * @param debugging Debug setting + * @return Client */ private Client buildHttpClient(boolean debugging) { final ClientConfig clientConfig = new ClientConfig(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java index 8337b1d39f2..4ade3277cc0 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -30,6 +30,7 @@ public class JSON implements ContextResolver { /** * Set the date format for JSON (de)serialization with Date properties. + * @param dateFormat Date format */ public void setDateFormat(DateFormat dateFormat) { mapper.setDateFormat(dateFormat); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java deleted file mode 100644 index de60566e861..00000000000 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java +++ /dev/null @@ -1,78 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.client.ApiException; -import io.swagger.client.ApiClient; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; - -import javax.ws.rs.core.GenericType; - -import io.swagger.client.model.Client; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class Fake_classname_tags123Api { - private ApiClient apiClient; - - public Fake_classname_tags123Api() { - this(Configuration.getDefaultApiClient()); - } - - public Fake_classname_tags123Api(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /** - * To test class name in snake case - * - * @param body client model (required) - * @return Client - * @throws ApiException if fails to make API call - */ - public Client testClassname(Client 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 testClassname"); - } - - // create path and map variables - String localVarPath = "/fake_classname_test".replaceAll("\\{format\\}","json"); - - // query params - List localVarQueryParams = new ArrayList(); - Map localVarHeaderParams = new HashMap(); - Map localVarFormParams = new HashMap(); - - - - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - - String[] localVarAuthNames = new String[] { }; - - GenericType localVarReturnType = new GenericType() {}; - return apiClient.invokeAPI(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); - } -} diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index 131088873d1..e816fce5bad 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -124,7 +124,7 @@ public class PetApi { * 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) - * @return List + * @return List<Pet> * @throws ApiException if fails to make API call */ public List findPetsByStatus(List status) throws ApiException { @@ -166,7 +166,7 @@ public class PetApi { * 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) - * @return List + * @return List<Pet> * @throws ApiException if fails to make API call */ public List findPetsByTags(List tags) throws ApiException { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java index c0c9a166ad7..41bd6751871 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -78,7 +78,7 @@ public class StoreApi { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Map + * @return Map<String, Integer> * @throws ApiException if fails to make API call */ public Map getInventory() throws ApiException { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java index 8fc61b6891a..7c570ce933d 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Animal.java @@ -24,10 +24,12 @@ import io.swagger.annotations.ApiModelProperty; /** * Animal */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) -@JsonSubTypes({ - @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), +@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"), }) + public class Animal { @JsonProperty("className") private String className = null; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Capitalization.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Capitalization.java new file mode 100644 index 00000000000..1466f669520 --- /dev/null +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Capitalization.java @@ -0,0 +1,204 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(example = "null", value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(example = "null", value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java index 3c43e963b04..c2c9d6b084b 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/EnumTest.java @@ -31,7 +31,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml b/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml index 1ba5649a770..1163f291fcb 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml @@ -6,8 +6,10 @@ jar swagger-petstore-okhttp-gson 1.0.0 + https://github.com/swagger-api/swagger-codegen + Swagger Java - scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git scm:git:git@github.com:swagger-api/swagger-codegen.git https://github.com/swagger-api/swagger-codegen @@ -22,7 +24,16 @@ repo - + + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + @@ -108,9 +119,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeApi.java index fd71abbad68..70699c70e22 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/FakeApi.java @@ -9,512 +9,512 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import java.math.BigDecimal; -import io.swagger.client.model.Client; -import org.threeten.bp.LocalDate; -import org.threeten.bp.OffsetDateTime; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testClientModel */ - private com.squareup.okhttp.Call testClientModelCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call testClientModelValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling testClientModel(Async)"); - } - - - com.squareup.okhttp.Call call = testClientModelCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * To test \"client\" model - * To test \"client\" model - * @param body client model (required) - * @return Client - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Client testClientModel(Client body) throws ApiException { - ApiResponse resp = testClientModelWithHttpInfo(body); - return resp.getData(); - } - - /** - * To test \"client\" model - * To test \"client\" model - * @param body client model (required) - * @return ApiResponse<Client> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testClientModelWithHttpInfo(Client body) throws ApiException { - com.squareup.okhttp.Call call = testClientModelValidateBeforeCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * To test \"client\" model (asynchronously) - * To test \"client\" model - * @param body client model (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testClientModelAsync(Client body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testClientModelValidateBeforeCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for testEndpointParameters */ - private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (integer != null) - localVarFormParams.put("integer", integer); - if (int32 != null) - localVarFormParams.put("int32", int32); - if (int64 != null) - localVarFormParams.put("int64", int64); - if (number != null) - localVarFormParams.put("number", number); - if (_float != null) - localVarFormParams.put("float", _float); - if (_double != null) - localVarFormParams.put("double", _double); - if (string != null) - localVarFormParams.put("string", string); - if (patternWithoutDelimiter != null) - localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); - if (_byte != null) - localVarFormParams.put("byte", _byte); - if (binary != null) - localVarFormParams.put("binary", binary); - if (date != null) - localVarFormParams.put("date", date); - if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); - if (password != null) - localVarFormParams.put("password", password); - if (paramCallback != null) - localVarFormParams.put("callback", paramCallback); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "http_basic_test" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call testEndpointParametersValidateBeforeCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter 'patternWithoutDelimiter' is set - if (patternWithoutDelimiter == null) { - throw new ApiException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); - } - - - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { - testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { - com.squareup.okhttp.Call call = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, null, null); - return apiClient.execute(call); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for testEnumParameters */ - private com.squareup.okhttp.Call testEnumParametersCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (enumQueryStringArray != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); - if (enumQueryString != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); - if (enumQueryInteger != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - Map localVarHeaderParams = new HashMap(); - if (enumHeaderStringArray != null) - localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); - if (enumHeaderString != null) - localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); - - Map localVarFormParams = new HashMap(); - if (enumFormStringArray != null) - localVarFormParams.put("enum_form_string_array", enumFormStringArray); - if (enumFormString != null) - localVarFormParams.put("enum_form_string", enumFormString); - if (enumQueryDouble != null) - localVarFormParams.put("enum_query_double", enumQueryDouble); - - final String[] localVarAccepts = { - "*/*" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "*/*" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call testEnumParametersValidateBeforeCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - - com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * To test enum parameters - * To test enum parameters - * @param enumFormStringArray Form parameter enum test (string array) (optional) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @param enumHeaderStringArray Header parameter enum test (string array) (optional) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { - testEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); - } - - /** - * To test enum parameters - * To test enum parameters - * @param enumFormStringArray Form parameter enum test (string array) (optional) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @param enumHeaderStringArray Header parameter enum test (string array) (optional) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEnumParametersWithHttpInfo(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { - com.squareup.okhttp.Call call = testEnumParametersValidateBeforeCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, null, null); - return apiClient.execute(call); - } - - /** - * To test enum parameters (asynchronously) - * To test enum parameters - * @param enumFormStringArray Form parameter enum test (string array) (optional) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @param enumHeaderStringArray Header parameter enum test (string array) (optional) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEnumParametersAsync(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEnumParametersValidateBeforeCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import java.math.BigDecimal; +import io.swagger.client.model.Client; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for testClientModel */ + private com.squareup.okhttp.Call testClientModelCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testClientModelValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling testClientModel(Async)"); + } + + + com.squareup.okhttp.Call call = testClientModelCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * To test \"client\" model + * To test \"client\" model + * @param body client model (required) + * @return Client + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Client testClientModel(Client body) throws ApiException { + ApiResponse resp = testClientModelWithHttpInfo(body); + return resp.getData(); + } + + /** + * To test \"client\" model + * To test \"client\" model + * @param body client model (required) + * @return ApiResponse<Client> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testClientModelWithHttpInfo(Client body) throws ApiException { + com.squareup.okhttp.Call call = testClientModelValidateBeforeCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * To test \"client\" model (asynchronously) + * To test \"client\" model + * @param body client model (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testClientModelAsync(Client body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testClientModelValidateBeforeCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for testEndpointParameters */ + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (patternWithoutDelimiter != null) + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + if (paramCallback != null) + localVarFormParams.put("callback", paramCallback); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "http_basic_test" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testEndpointParametersValidateBeforeCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for testEnumParameters */ + private com.squareup.okhttp.Call testEnumParametersCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (enumQueryStringArray != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); + if (enumQueryString != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); + if (enumQueryInteger != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + Map localVarHeaderParams = new HashMap(); + if (enumHeaderStringArray != null) + localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); + if (enumHeaderString != null) + localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); + + Map localVarFormParams = new HashMap(); + if (enumFormStringArray != null) + localVarFormParams.put("enum_form_string_array", enumFormStringArray); + if (enumFormString != null) + localVarFormParams.put("enum_form_string", enumFormString); + if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "*/*" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "*/*" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testEnumParametersValidateBeforeCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + + com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * To test enum parameters + * To test enum parameters + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { + testEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /** + * To test enum parameters + * To test enum parameters + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEnumParametersWithHttpInfo(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { + com.squareup.okhttp.Call call = testEnumParametersValidateBeforeCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, null, null); + return apiClient.execute(call); + } + + /** + * To test enum parameters (asynchronously) + * To test enum parameters + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEnumParametersAsync(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEnumParametersValidateBeforeCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/PetApi.java index d86cc92060b..b7119add7d1 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/PetApi.java @@ -9,1012 +9,1012 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import java.io.File; -import io.swagger.client.model.ModelApiResponse; -import io.swagger.client.model.Pet; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for addPet */ - private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call addPetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); - } - - - com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void addPet(Pet body) throws ApiException { - addPetWithHttpInfo(body); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Add a new pet to the store (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deletePet */ - private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call deletePetValidateBeforeCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); - } - - - com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - deletePetWithHttpInfo(petId, apiKey); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { - com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, null, null); - return apiClient.execute(call); - } - - /** - * Deletes a pet (asynchronously) - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for findPetsByStatus */ - private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (status != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call findPetsByStatusValidateBeforeCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); - } - - - com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByStatus(List status) throws ApiException { - ApiResponse> resp = findPetsByStatusWithHttpInfo(status); - return resp.getData(); - } - - /** - * 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) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { - com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * 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 (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for findPetsByTags */ - private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (tags != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call findPetsByTagsValidateBeforeCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); - } - - - com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByTags(List tags) throws ApiException { - ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); - return resp.getData(); - } - - /** - * 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) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { - com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * 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 (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getPetById */ - private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call getPetByIdValidateBeforeCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); - } - - - com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Pet getPetById(Long petId) throws ApiException { - ApiResponse resp = getPetByIdWithHttpInfo(petId); - return resp.getData(); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return ApiResponse<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { - com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find pet by ID (asynchronously) - * Returns a single pet - * @param petId ID of pet to return (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for updatePet */ - private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call updatePetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); - } - - - com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePet(Pet body) throws ApiException { - updatePetWithHttpInfo(body); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Update an existing pet (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updatePetWithForm */ - private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (name != null) - localVarFormParams.put("name", name); - if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call updatePetWithFormValidateBeforeCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); - } - - - com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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 (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - updatePetWithFormWithHttpInfo(petId, name, status); - } - - /** - * 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 (optional) - * @param status Updated status of the pet (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { - com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, null, null); - return apiClient.execute(call); - } - - /** - * Updates a pet in the store with form data (asynchronously) - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for uploadFile */ - private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); - if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call uploadFileValidateBeforeCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); - } - - - com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); - return resp.getData(); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ApiResponse<ModelApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { - com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * uploads an image (asynchronously) - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import io.swagger.client.model.Pet; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call addPetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); + } + + + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call deletePetValidateBeforeCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, null, null); + return apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call findPetsByStatusValidateBeforeCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); + } + + /** + * 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) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * 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 (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call findPetsByTagsValidateBeforeCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); + } + + /** + * 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) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * 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 (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getPetByIdValidateBeforeCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call updatePetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call updatePetWithFormValidateBeforeCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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 (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * 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 (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call uploadFileValidateBeforeCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/StoreApi.java index e2c41fa1aa5..199f2c7b109 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/StoreApi.java @@ -9,511 +9,511 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import io.swagger.client.model.Order; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for deleteOrder */ - private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call deleteOrderValidateBeforeCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); - } - - - com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteOrder(String orderId) throws ApiException { - 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 - * @param orderId ID of the order that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { - com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, null, null); - return apiClient.execute(call); - } - - /** - * 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 (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getInventory */ - private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call getInventoryValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - - com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map<String, Integer> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Map getInventory() throws ApiException { - ApiResponse> resp = getInventoryWithHttpInfo(); - return resp.getData(); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return ApiResponse<Map<String, Integer>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> getInventoryWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Returns pet inventories by status (asynchronously) - * Returns a map of status codes to quantities - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getOrderById */ - private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call getOrderByIdValidateBeforeCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); - } - - - com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order getOrderById(Long orderId) throws ApiException { - ApiResponse resp = getOrderByIdWithHttpInfo(orderId); - return resp.getData(); - } - - /** - * 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) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { - com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * 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 (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for placeOrder */ - private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call placeOrderValidateBeforeCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); - } - - - com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order placeOrder(Order body) throws ApiException { - ApiResponse resp = placeOrderWithHttpInfo(body); - return resp.getData(); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { - com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Place an order for a pet (asynchronously) - * - * @param body order placed for purchasing the pet (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import io.swagger.client.model.Order; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call deleteOrderValidateBeforeCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + 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 + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, null, null); + return apiClient.execute(call); + } + + /** + * 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 (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getInventoryValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getOrderByIdValidateBeforeCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * 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) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * 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 (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call placeOrderValidateBeforeCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/UserApi.java index d79a19a65ca..ea719996a6b 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/api/UserApi.java @@ -9,984 +9,984 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import io.swagger.client.model.User; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for createUser */ - private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call createUserValidateBeforeCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); - } - - - com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUser(User body) throws ApiException { - createUserWithHttpInfo(body); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUserWithHttpInfo(User body) throws ApiException { - com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Create user (asynchronously) - * This can only be done by the logged in user. - * @param body Created user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithArrayInput */ - private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call createUsersWithArrayInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); - } - - - com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithArrayInput(List body) throws ApiException { - createUsersWithArrayInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithListInput */ - private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call createUsersWithListInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); - } - - - com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithListInput(List body) throws ApiException { - createUsersWithListInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deleteUser */ - private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call deleteUserValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); - } - - - com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteUser(String username) throws ApiException { - deleteUserWithHttpInfo(username); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, null, null); - return apiClient.execute(call); - } - - /** - * Delete user (asynchronously) - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getUserByName */ - private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call getUserByNameValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); - } - - - com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public User getUserByName(String username) throws ApiException { - ApiResponse resp = getUserByNameWithHttpInfo(username); - return resp.getData(); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return ApiResponse<User> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Get user by user name (asynchronously) - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for loginUser */ - private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (username != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - if (password != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call loginUserValidateBeforeCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); - } - - - com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public String loginUser(String username, String password) throws ApiException { - ApiResponse resp = loginUserWithHttpInfo(username, password); - return resp.getData(); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return ApiResponse<String> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { - com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Logs user into the system (asynchronously) - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for logoutUser */ - private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call logoutUserValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - - com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Logs out current logged in user session - * - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void logoutUser() throws ApiException { - logoutUserWithHttpInfo(); - } - - /** - * Logs out current logged in user session - * - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse logoutUserWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(null, null); - return apiClient.execute(call); - } - - /** - * Logs out current logged in user session (asynchronously) - * - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updateUser */ - private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call updateUserValidateBeforeCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); - } - - - com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updateUser(String username, User body) throws ApiException { - updateUserWithHttpInfo(username, body); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { - com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, null, null); - return apiClient.execute(call); - } - - /** - * Updated user (asynchronously) - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import io.swagger.client.model.User; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call createUserValidateBeforeCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + } + + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call createUsersWithArrayInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); + } + + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call createUsersWithListInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); + } + + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call deleteUserValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getUserByNameValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call loginUserValidateBeforeCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call logoutUserValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(null, null); + return apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call updateUserValidateBeforeCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java index 9086efc686c..df1255ab2ae 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/Animal.java @@ -24,6 +24,7 @@ import android.os.Parcel; * Animal */ + public class Animal implements Parcelable { @SerializedName("className") private String className = null; diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java index 41c55957eed..84fd6e64938 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/io/swagger/client/model/EnumTest.java @@ -34,7 +34,10 @@ public class EnumTest implements Parcelable { UPPER("UPPER"), @SerializedName("lower") - LOWER("lower"); + LOWER("lower"), + + @SerializedName("") + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/okhttp-gson/docs/Capitalization.md b/samples/client/petstore/java/okhttp-gson/docs/Capitalization.md new file mode 100644 index 00000000000..0f3064c1996 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/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] + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md b/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md +++ b/samples/client/petstore/java/okhttp-gson/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml index 1ba5649a770..1163f291fcb 100644 --- a/samples/client/petstore/java/okhttp-gson/pom.xml +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -6,8 +6,10 @@ jar swagger-petstore-okhttp-gson 1.0.0 + https://github.com/swagger-api/swagger-codegen + Swagger Java - scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git scm:git:git@github.com:swagger-api/swagger-codegen.git https://github.com/swagger-api/swagger-codegen @@ -22,7 +24,16 @@ repo - + + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + @@ -108,9 +119,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index fd71abbad68..70699c70e22 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -9,512 +9,512 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import java.math.BigDecimal; -import io.swagger.client.model.Client; -import org.threeten.bp.LocalDate; -import org.threeten.bp.OffsetDateTime; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class FakeApi { - private ApiClient apiClient; - - public FakeApi() { - this(Configuration.getDefaultApiClient()); - } - - public FakeApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testClientModel */ - private com.squareup.okhttp.Call testClientModelCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call testClientModelValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling testClientModel(Async)"); - } - - - com.squareup.okhttp.Call call = testClientModelCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * To test \"client\" model - * To test \"client\" model - * @param body client model (required) - * @return Client - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Client testClientModel(Client body) throws ApiException { - ApiResponse resp = testClientModelWithHttpInfo(body); - return resp.getData(); - } - - /** - * To test \"client\" model - * To test \"client\" model - * @param body client model (required) - * @return ApiResponse<Client> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testClientModelWithHttpInfo(Client body) throws ApiException { - com.squareup.okhttp.Call call = testClientModelValidateBeforeCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * To test \"client\" model (asynchronously) - * To test \"client\" model - * @param body client model (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testClientModelAsync(Client body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testClientModelValidateBeforeCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for testEndpointParameters */ - private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (integer != null) - localVarFormParams.put("integer", integer); - if (int32 != null) - localVarFormParams.put("int32", int32); - if (int64 != null) - localVarFormParams.put("int64", int64); - if (number != null) - localVarFormParams.put("number", number); - if (_float != null) - localVarFormParams.put("float", _float); - if (_double != null) - localVarFormParams.put("double", _double); - if (string != null) - localVarFormParams.put("string", string); - if (patternWithoutDelimiter != null) - localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); - if (_byte != null) - localVarFormParams.put("byte", _byte); - if (binary != null) - localVarFormParams.put("binary", binary); - if (date != null) - localVarFormParams.put("date", date); - if (dateTime != null) - localVarFormParams.put("dateTime", dateTime); - if (password != null) - localVarFormParams.put("password", password); - if (paramCallback != null) - localVarFormParams.put("callback", paramCallback); - - final String[] localVarAccepts = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/xml; charset=utf-8", "application/json; charset=utf-8" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "http_basic_test" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call testEndpointParametersValidateBeforeCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'number' is set - if (number == null) { - throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_double' is set - if (_double == null) { - throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter 'patternWithoutDelimiter' is set - if (patternWithoutDelimiter == null) { - throw new ApiException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters(Async)"); - } - - // verify the required parameter '_byte' is set - if (_byte == null) { - throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); - } - - - com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { - testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { - com.squareup.okhttp.Call call = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, null, null); - return apiClient.execute(call); - } - - /** - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for testEnumParameters */ - private com.squareup.okhttp.Call testEnumParametersCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/fake".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (enumQueryStringArray != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); - if (enumQueryString != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); - if (enumQueryInteger != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); - - Map localVarHeaderParams = new HashMap(); - if (enumHeaderStringArray != null) - localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); - if (enumHeaderString != null) - localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); - - Map localVarFormParams = new HashMap(); - if (enumFormStringArray != null) - localVarFormParams.put("enum_form_string_array", enumFormStringArray); - if (enumFormString != null) - localVarFormParams.put("enum_form_string", enumFormString); - if (enumQueryDouble != null) - localVarFormParams.put("enum_query_double", enumQueryDouble); - - final String[] localVarAccepts = { - "*/*" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "*/*" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call testEnumParametersValidateBeforeCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - - com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * To test enum parameters - * To test enum parameters - * @param enumFormStringArray Form parameter enum test (string array) (optional) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @param enumHeaderStringArray Header parameter enum test (string array) (optional) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { - testEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); - } - - /** - * To test enum parameters - * To test enum parameters - * @param enumFormStringArray Form parameter enum test (string array) (optional) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @param enumHeaderStringArray Header parameter enum test (string array) (optional) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testEnumParametersWithHttpInfo(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { - com.squareup.okhttp.Call call = testEnumParametersValidateBeforeCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, null, null); - return apiClient.execute(call); - } - - /** - * To test enum parameters (asynchronously) - * To test enum parameters - * @param enumFormStringArray Form parameter enum test (string array) (optional) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @param enumHeaderStringArray Header parameter enum test (string array) (optional) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testEnumParametersAsync(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testEnumParametersValidateBeforeCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import java.math.BigDecimal; +import io.swagger.client.model.Client; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient apiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for testClientModel */ + private com.squareup.okhttp.Call testClientModelCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testClientModelValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling testClientModel(Async)"); + } + + + com.squareup.okhttp.Call call = testClientModelCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * To test \"client\" model + * To test \"client\" model + * @param body client model (required) + * @return Client + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Client testClientModel(Client body) throws ApiException { + ApiResponse resp = testClientModelWithHttpInfo(body); + return resp.getData(); + } + + /** + * To test \"client\" model + * To test \"client\" model + * @param body client model (required) + * @return ApiResponse<Client> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testClientModelWithHttpInfo(Client body) throws ApiException { + com.squareup.okhttp.Call call = testClientModelValidateBeforeCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * To test \"client\" model (asynchronously) + * To test \"client\" model + * @param body client model (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testClientModelAsync(Client body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testClientModelValidateBeforeCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for testEndpointParameters */ + private com.squareup.okhttp.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (integer != null) + localVarFormParams.put("integer", integer); + if (int32 != null) + localVarFormParams.put("int32", int32); + if (int64 != null) + localVarFormParams.put("int64", int64); + if (number != null) + localVarFormParams.put("number", number); + if (_float != null) + localVarFormParams.put("float", _float); + if (_double != null) + localVarFormParams.put("double", _double); + if (string != null) + localVarFormParams.put("string", string); + if (patternWithoutDelimiter != null) + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); + if (_byte != null) + localVarFormParams.put("byte", _byte); + if (binary != null) + localVarFormParams.put("binary", binary); + if (date != null) + localVarFormParams.put("date", date); + if (dateTime != null) + localVarFormParams.put("dateTime", dateTime); + if (password != null) + localVarFormParams.put("password", password); + if (paramCallback != null) + localVarFormParams.put("callback", paramCallback); + + final String[] localVarAccepts = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/xml; charset=utf-8", "application/json; charset=utf-8" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "http_basic_test" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testEndpointParametersValidateBeforeCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + com.squareup.okhttp.Call call = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { + com.squareup.okhttp.Call call = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, null, null); + return apiClient.execute(call); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional) + * @param password None (optional) + * @param paramCallback None (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEndpointParametersAsync(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for testEnumParameters */ + private com.squareup.okhttp.Call testEnumParametersCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (enumQueryStringArray != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "enum_query_string_array", enumQueryStringArray)); + if (enumQueryString != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_string", enumQueryString)); + if (enumQueryInteger != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_query_integer", enumQueryInteger)); + + Map localVarHeaderParams = new HashMap(); + if (enumHeaderStringArray != null) + localVarHeaderParams.put("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); + if (enumHeaderString != null) + localVarHeaderParams.put("enum_header_string", apiClient.parameterToString(enumHeaderString)); + + Map localVarFormParams = new HashMap(); + if (enumFormStringArray != null) + localVarFormParams.put("enum_form_string_array", enumFormStringArray); + if (enumFormString != null) + localVarFormParams.put("enum_form_string", enumFormString); + if (enumQueryDouble != null) + localVarFormParams.put("enum_query_double", enumQueryDouble); + + final String[] localVarAccepts = { + "*/*" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "*/*" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call testEnumParametersValidateBeforeCall(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + + com.squareup.okhttp.Call call = testEnumParametersCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * To test enum parameters + * To test enum parameters + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { + testEnumParametersWithHttpInfo(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + + /** + * To test enum parameters + * To test enum parameters + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse testEnumParametersWithHttpInfo(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) throws ApiException { + com.squareup.okhttp.Call call = testEnumParametersValidateBeforeCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, null, null); + return apiClient.execute(call); + } + + /** + * To test enum parameters (asynchronously) + * To test enum parameters + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call testEnumParametersAsync(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = testEnumParametersValidateBeforeCall(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java deleted file mode 100644 index 76f7b7924a2..00000000000 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import io.swagger.client.model.Client; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class Fake_classname_tags123Api { - private ApiClient apiClient; - - public Fake_classname_tags123Api() { - this(Configuration.getDefaultApiClient()); - } - - public Fake_classname_tags123Api(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for testClassname */ - private com.squareup.okhttp.Call testClassnameCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/fake_classname_test".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call testClassnameValidateBeforeCall(Client body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling testClassname(Async)"); - } - - - com.squareup.okhttp.Call call = testClassnameCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * To test class name in snake case - * - * @param body client model (required) - * @return Client - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Client testClassname(Client body) throws ApiException { - ApiResponse resp = testClassnameWithHttpInfo(body); - return resp.getData(); - } - - /** - * To test class name in snake case - * - * @param body client model (required) - * @return ApiResponse<Client> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse testClassnameWithHttpInfo(Client body) throws ApiException { - com.squareup.okhttp.Call call = testClassnameValidateBeforeCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * To test class name in snake case (asynchronously) - * - * @param body client model (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call testClassnameAsync(Client body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = testClassnameValidateBeforeCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } -} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index d86cc92060b..b7119add7d1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -9,1012 +9,1012 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import java.io.File; -import io.swagger.client.model.ModelApiResponse; -import io.swagger.client.model.Pet; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class PetApi { - private ApiClient apiClient; - - public PetApi() { - this(Configuration.getDefaultApiClient()); - } - - public PetApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for addPet */ - private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call addPetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); - } - - - com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void addPet(Pet body) throws ApiException { - addPetWithHttpInfo(body); - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Add a new pet to the store (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deletePet */ - private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - if (apiKey != null) - localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call deletePetValidateBeforeCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); - } - - - com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deletePet(Long petId, String apiKey) throws ApiException { - deletePetWithHttpInfo(petId, apiKey); - } - - /** - * Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { - com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, null, null); - return apiClient.execute(call); - } - - /** - * Deletes a pet (asynchronously) - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for findPetsByStatus */ - private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (status != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call findPetsByStatusValidateBeforeCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); - } - - - com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByStatus(List status) throws ApiException { - ApiResponse> resp = findPetsByStatusWithHttpInfo(status); - return resp.getData(); - } - - /** - * 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) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { - com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * 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 (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for findPetsByTags */ - private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (tags != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call findPetsByTagsValidateBeforeCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); - } - - - com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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) - * @return List<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public List findPetsByTags(List tags) throws ApiException { - ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); - return resp.getData(); - } - - /** - * 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) - * @return ApiResponse<List<Pet>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { - com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * 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 (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getPetById */ - private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call getPetByIdValidateBeforeCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); - } - - - com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return Pet - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Pet getPetById(Long petId) throws ApiException { - ApiResponse resp = getPetByIdWithHttpInfo(petId); - return resp.getData(); - } - - /** - * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return (required) - * @return ApiResponse<Pet> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { - com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Find pet by ID (asynchronously) - * Returns a single pet - * @param petId ID of pet to return (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for updatePet */ - private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/pet".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/json", "application/xml" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call updatePetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); - } - - - com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePet(Pet body) throws ApiException { - updatePetWithHttpInfo(body); - } - - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { - com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Update an existing pet (asynchronously) - * - * @param body Pet object that needs to be added to the store (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updatePetWithForm */ - private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (name != null) - localVarFormParams.put("name", name); - if (status != null) - localVarFormParams.put("status", status); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "application/x-www-form-urlencoded" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call updatePetWithFormValidateBeforeCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); - } - - - com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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 (optional) - * @param status Updated status of the pet (optional) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updatePetWithForm(Long petId, String name, String status) throws ApiException { - updatePetWithFormWithHttpInfo(petId, name, status); - } - - /** - * 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 (optional) - * @param status Updated status of the pet (optional) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { - com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, null, null); - return apiClient.execute(call); - } - - /** - * Updates a pet in the store with form data (asynchronously) - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for uploadFile */ - private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - if (additionalMetadata != null) - localVarFormParams.put("additionalMetadata", additionalMetadata); - if (file != null) - localVarFormParams.put("file", file); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - "multipart/form-data" - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "petstore_auth" }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call uploadFileValidateBeforeCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); - } - - - com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ModelApiResponse - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { - ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); - return resp.getData(); - } - - /** - * uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return ApiResponse<ModelApiResponse> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { - com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * uploads an image (asynchronously) - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import java.io.File; +import io.swagger.client.model.ModelApiResponse; +import io.swagger.client.model.Pet; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for addPet */ + private com.squareup.okhttp.Call addPetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call addPetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling addPet(Async)"); + } + + + com.squareup.okhttp.Call call = addPetCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void addPet(Pet body) throws ApiException { + addPetWithHttpInfo(body); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse addPetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call addPetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = addPetValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deletePet */ + private com.squareup.okhttp.Call deletePetCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + if (apiKey != null) + localVarHeaderParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call deletePetValidateBeforeCall(Long petId, String apiKey, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + com.squareup.okhttp.Call call = deletePetCall(petId, apiKey, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, null, null); + return apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deletePetAsync(Long petId, String apiKey, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deletePetValidateBeforeCall(petId, apiKey, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for findPetsByStatus */ + private com.squareup.okhttp.Call findPetsByStatusCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (status != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "status", status)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call findPetsByStatusValidateBeforeCall(List status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + com.squareup.okhttp.Call call = findPetsByStatusCall(status, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> resp = findPetsByStatusWithHttpInfo(status); + return resp.getData(); + } + + /** + * 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) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * 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 (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByStatusAsync(List status, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByStatusValidateBeforeCall(status, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for findPetsByTags */ + private com.squareup.okhttp.Call findPetsByTagsCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (tags != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("csv", "tags", tags)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call findPetsByTagsValidateBeforeCall(List tags, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + + com.squareup.okhttp.Call call = findPetsByTagsCall(tags, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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) + * @return List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> resp = findPetsByTagsWithHttpInfo(tags); + return resp.getData(); + } + + /** + * 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) + * @return ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * 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 (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call findPetsByTagsAsync(List tags, final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = findPetsByTagsValidateBeforeCall(tags, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getPetById */ + private com.squareup.okhttp.Call getPetByIdCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getPetByIdValidateBeforeCall(Long petId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + com.squareup.okhttp.Call call = getPetByIdCall(petId, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse resp = getPetByIdWithHttpInfo(petId); + return resp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getPetByIdAsync(Long petId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getPetByIdValidateBeforeCall(petId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for updatePet */ + private com.squareup.okhttp.Call updatePetCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/pet".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call updatePetValidateBeforeCall(Pet body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updatePet(Async)"); + } + + + com.squareup.okhttp.Call call = updatePetCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePet(Pet body) throws ApiException { + updatePetWithHttpInfo(body); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithHttpInfo(Pet body) throws ApiException { + com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetAsync(Pet body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updatePetWithForm */ + private com.squareup.okhttp.Call updatePetWithFormCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (name != null) + localVarFormParams.put("name", name); + if (status != null) + localVarFormParams.put("status", status); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call updatePetWithFormValidateBeforeCall(Long petId, String name, String status, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + com.squareup.okhttp.Call call = updatePetWithFormCall(petId, name, status, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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 (optional) + * @param status Updated status of the pet (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * 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 (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, null, null); + return apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updatePetWithFormValidateBeforeCall(petId, name, status, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for uploadFile */ + private com.squareup.okhttp.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + if (additionalMetadata != null) + localVarFormParams.put("additionalMetadata", additionalMetadata); + if (file != null) + localVarFormParams.put("file", file); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call uploadFileValidateBeforeCall(Long petId, String additionalMetadata, File file, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + com.squareup.okhttp.Call call = uploadFileCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse resp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return resp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = uploadFileValidateBeforeCall(petId, additionalMetadata, file, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java index e2c41fa1aa5..199f2c7b109 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java @@ -9,511 +9,511 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import io.swagger.client.model.Order; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class StoreApi { - private ApiClient apiClient; - - public StoreApi() { - this(Configuration.getDefaultApiClient()); - } - - public StoreApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for deleteOrder */ - private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call deleteOrderValidateBeforeCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); - } - - - com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteOrder(String orderId) throws ApiException { - 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 - * @param orderId ID of the order that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { - com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, null, null); - return apiClient.execute(call); - } - - /** - * 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 (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getInventory */ - private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { "api_key" }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call getInventoryValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - - com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return Map<String, Integer> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Map getInventory() throws ApiException { - ApiResponse> resp = getInventoryWithHttpInfo(); - return resp.getData(); - } - - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - * @return ApiResponse<Map<String, Integer>> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse> getInventoryWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(null, null); - Type localVarReturnType = new TypeToken>(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Returns pet inventories by status (asynchronously) - * Returns a map of status codes to quantities - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken>(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for getOrderById */ - private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call getOrderByIdValidateBeforeCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); - } - - - com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * 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) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order getOrderById(Long orderId) throws ApiException { - ApiResponse resp = getOrderByIdWithHttpInfo(orderId); - return resp.getData(); - } - - /** - * 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) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { - com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * 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 (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for placeOrder */ - private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call placeOrderValidateBeforeCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); - } - - - com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return Order - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public Order placeOrder(Order body) throws ApiException { - ApiResponse resp = placeOrderWithHttpInfo(body); - return resp.getData(); - } - - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return ApiResponse<Order> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { - com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Place an order for a pet (asynchronously) - * - * @param body order placed for purchasing the pet (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import io.swagger.client.model.Order; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for deleteOrder */ + private com.squareup.okhttp.Call deleteOrderCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call deleteOrderValidateBeforeCall(String orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + com.squareup.okhttp.Call call = deleteOrderCall(orderId, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteOrder(String orderId) throws ApiException { + 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 + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, null, null); + return apiClient.execute(call); + } + + /** + * 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 (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteOrderAsync(String orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteOrderValidateBeforeCall(orderId, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getInventory */ + private com.squareup.okhttp.Call getInventoryCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/inventory".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getInventoryValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + + com.squareup.okhttp.Call call = getInventoryCall(progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Map getInventory() throws ApiException { + ApiResponse> resp = getInventoryWithHttpInfo(); + return resp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(null, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getInventoryAsync(final ApiCallback> callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getInventoryValidateBeforeCall(progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for getOrderById */ + private com.squareup.okhttp.Call getOrderByIdCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getOrderByIdValidateBeforeCall(Long orderId, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + com.squareup.okhttp.Call call = getOrderByIdCall(orderId, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * 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) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse resp = getOrderByIdWithHttpInfo(orderId); + return resp.getData(); + } + + /** + * 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) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * 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 (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getOrderByIdAsync(Long orderId, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getOrderByIdValidateBeforeCall(orderId, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for placeOrder */ + private com.squareup.okhttp.Call placeOrderCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/store/order".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call placeOrderValidateBeforeCall(Order body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling placeOrder(Async)"); + } + + + com.squareup.okhttp.Call call = placeOrderCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public Order placeOrder(Order body) throws ApiException { + ApiResponse resp = placeOrderWithHttpInfo(body); + return resp.getData(); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse placeOrderWithHttpInfo(Order body) throws ApiException { + com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call placeOrderAsync(Order body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = placeOrderValidateBeforeCall(body, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java index d79a19a65ca..ea719996a6b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -9,984 +9,984 @@ * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ - - -package io.swagger.client.api; - -import io.swagger.client.ApiCallback; -import io.swagger.client.ApiClient; -import io.swagger.client.ApiException; -import io.swagger.client.ApiResponse; -import io.swagger.client.Configuration; -import io.swagger.client.Pair; -import io.swagger.client.ProgressRequestBody; -import io.swagger.client.ProgressResponseBody; - -import com.google.gson.reflect.TypeToken; - -import java.io.IOException; - - -import io.swagger.client.model.User; - -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class UserApi { - private ApiClient apiClient; - - public UserApi() { - this(Configuration.getDefaultApiClient()); - } - - public UserApi(ApiClient apiClient) { - this.apiClient = apiClient; - } - - public ApiClient getApiClient() { - return apiClient; - } - - public void setApiClient(ApiClient apiClient) { - this.apiClient = apiClient; - } - - /* Build call for createUser */ - private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call createUserValidateBeforeCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); - } - - - com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUser(User body) throws ApiException { - createUserWithHttpInfo(body); - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUserWithHttpInfo(User body) throws ApiException { - com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Create user (asynchronously) - * This can only be done by the logged in user. - * @param body Created user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithArrayInput */ - private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call createUsersWithArrayInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); - } - - - com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithArrayInput(List body) throws ApiException { - createUsersWithArrayInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for createUsersWithListInput */ - private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call createUsersWithListInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); - } - - - com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void createUsersWithListInput(List body) throws ApiException { - createUsersWithListInputWithHttpInfo(body); - } - - /** - * Creates list of users with given input array - * - * @param body List of user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { - com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, null, null); - return apiClient.execute(call); - } - - /** - * Creates list of users with given input array (asynchronously) - * - * @param body List of user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for deleteUser */ - private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call deleteUserValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); - } - - - com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void deleteUser(String username) throws ApiException { - deleteUserWithHttpInfo(username); - } - - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, null, null); - return apiClient.execute(call); - } - - /** - * Delete user (asynchronously) - * This can only be done by the logged in user. - * @param username The name that needs to be deleted (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for getUserByName */ - private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call getUserByNameValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); - } - - - com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public User getUserByName(String username) throws ApiException { - ApiResponse resp = getUserByNameWithHttpInfo(username); - return resp.getData(); - } - - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return ApiResponse<User> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { - com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Get user by user name (asynchronously) - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for loginUser */ - private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - if (username != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); - if (password != null) - localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call loginUserValidateBeforeCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); - } - - - com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return String - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public String loginUser(String username, String password) throws ApiException { - ApiResponse resp = loginUserWithHttpInfo(username, password); - return resp.getData(); - } - - /** - * Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return ApiResponse<String> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { - com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, null, null); - Type localVarReturnType = new TypeToken(){}.getType(); - return apiClient.execute(call, localVarReturnType); - } - - /** - * Logs user into the system (asynchronously) - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, progressListener, progressRequestListener); - Type localVarReturnType = new TypeToken(){}.getType(); - apiClient.executeAsync(call, localVarReturnType, callback); - return call; - } - /* Build call for logoutUser */ - private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = null; - - // create path and map variables - String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call logoutUserValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - - com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Logs out current logged in user session - * - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void logoutUser() throws ApiException { - logoutUserWithHttpInfo(); - } - - /** - * Logs out current logged in user session - * - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse logoutUserWithHttpInfo() throws ApiException { - com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(null, null); - return apiClient.execute(call); - } - - /** - * Logs out current logged in user session (asynchronously) - * - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } - /* Build call for updateUser */ - private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - Object localVarPostBody = body; - - // create path and map variables - String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - - List localVarQueryParams = new ArrayList(); - - Map localVarHeaderParams = new HashMap(); - - Map localVarFormParams = new HashMap(); - - final String[] localVarAccepts = { - "application/xml", "application/json" - }; - final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); - if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); - - final String[] localVarContentTypes = { - - }; - final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); - localVarHeaderParams.put("Content-Type", localVarContentType); - - if(progressListener != null) { - apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { - @Override - public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { - com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); - return originalResponse.newBuilder() - .body(new ProgressResponseBody(originalResponse.body(), progressListener)) - .build(); - } - }); - } - - String[] localVarAuthNames = new String[] { }; - return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); - } - - @SuppressWarnings("rawtypes") - private com.squareup.okhttp.Call updateUserValidateBeforeCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { - - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); - } - - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); - } - - - com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); - return call; - - - - - - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public void updateUser(String username, User body) throws ApiException { - updateUserWithHttpInfo(username, body); - } - - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return ApiResponse<Void> - * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body - */ - public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { - com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, null, null); - return apiClient.execute(call); - } - - /** - * Updated user (asynchronously) - * This can only be done by the logged in user. - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @param callback The callback to be executed when the API call finishes - * @return The request call - * @throws ApiException If fail to process the API call, e.g. serializing the request body object - */ - public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { - - ProgressResponseBody.ProgressListener progressListener = null; - ProgressRequestBody.ProgressRequestListener progressRequestListener = null; - - if (callback != null) { - progressListener = new ProgressResponseBody.ProgressListener() { - @Override - public void update(long bytesRead, long contentLength, boolean done) { - callback.onDownloadProgress(bytesRead, contentLength, done); - } - }; - - progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { - @Override - public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { - callback.onUploadProgress(bytesWritten, contentLength, done); - } - }; - } - - com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, progressListener, progressRequestListener); - apiClient.executeAsync(call, callback); - return call; - } -} + + +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.ApiResponse; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; +import io.swagger.client.ProgressRequestBody; +import io.swagger.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import io.swagger.client.model.User; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /* Build call for createUser */ + private com.squareup.okhttp.Call createUserCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call createUserValidateBeforeCall(User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUser(Async)"); + } + + + com.squareup.okhttp.Call call = createUserCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUser(User body) throws ApiException { + createUserWithHttpInfo(body); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUserWithHttpInfo(User body) throws ApiException { + com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUserAsync(User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUserValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithArrayInput */ + private com.squareup.okhttp.Call createUsersWithArrayInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call createUsersWithArrayInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithArrayInput(Async)"); + } + + + com.squareup.okhttp.Call call = createUsersWithArrayInputCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithArrayInput(List body) throws ApiException { + createUsersWithArrayInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithArrayInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithArrayInputValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for createUsersWithListInput */ + private com.squareup.okhttp.Call createUsersWithListInputCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call createUsersWithListInputValidateBeforeCall(List body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling createUsersWithListInput(Async)"); + } + + + com.squareup.okhttp.Call call = createUsersWithListInputCall(body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void createUsersWithListInput(List body) throws ApiException { + createUsersWithListInputWithHttpInfo(body); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List body) throws ApiException { + com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, null, null); + return apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call createUsersWithListInputAsync(List body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = createUsersWithListInputValidateBeforeCall(body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for deleteUser */ + private com.squareup.okhttp.Call deleteUserCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call deleteUserValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + com.squareup.okhttp.Call call = deleteUserCall(username, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, null, null); + return apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call deleteUserAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = deleteUserValidateBeforeCall(username, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for getUserByName */ + private com.squareup.okhttp.Call getUserByNameCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call getUserByNameValidateBeforeCall(String username, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + com.squareup.okhttp.Call call = getUserByNameCall(username, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public User getUserByName(String username) throws ApiException { + ApiResponse resp = getUserByNameWithHttpInfo(username); + return resp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call getUserByNameAsync(String username, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = getUserByNameValidateBeforeCall(username, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for loginUser */ + private com.squareup.okhttp.Call loginUserCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/login".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + if (username != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + localVarQueryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call loginUserValidateBeforeCall(String username, String password, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + com.squareup.okhttp.Call call = loginUserCall(username, password, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse resp = loginUserWithHttpInfo(username, password); + return resp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, null, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return apiClient.execute(call, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call loginUserAsync(String username, String password, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = loginUserValidateBeforeCall(username, password, progressListener, progressRequestListener); + Type localVarReturnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, localVarReturnType, callback); + return call; + } + /* Build call for logoutUser */ + private com.squareup.okhttp.Call logoutUserCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/logout".replaceAll("\\{format\\}","json"); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call logoutUserValidateBeforeCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + + com.squareup.okhttp.Call call = logoutUserCall(progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(null, null); + return apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call logoutUserAsync(final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = logoutUserValidateBeforeCall(progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } + /* Build call for updateUser */ + private com.squareup.okhttp.Call updateUserCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + + Map localVarHeaderParams = new HashMap(); + + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + localVarHeaderParams.put("Content-Type", localVarContentType); + + if(progressListener != null) { + apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() { + @Override + public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException { + com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request()); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), progressListener)) + .build(); + } + }); + } + + String[] localVarAuthNames = new String[] { }; + return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener); + } + + @SuppressWarnings("rawtypes") + private com.squareup.okhttp.Call updateUserValidateBeforeCall(String username, User body, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException("Missing the required parameter 'body' when calling updateUser(Async)"); + } + + + com.squareup.okhttp.Call call = updateUserCall(username, body, progressListener, progressRequestListener); + return call; + + + + + + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public void updateUser(String username, User body) throws ApiException { + updateUserWithHttpInfo(username, body); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + */ + public ApiResponse updateUserWithHttpInfo(String username, User body) throws ApiException { + com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, null, null); + return apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param body Updated user object (required) + * @param callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + */ + public com.squareup.okhttp.Call updateUserAsync(String username, User body, final ApiCallback callback) throws ApiException { + + ProgressResponseBody.ProgressListener progressListener = null; + ProgressRequestBody.ProgressRequestListener progressRequestListener = null; + + if (callback != null) { + progressListener = new ProgressResponseBody.ProgressListener() { + @Override + public void update(long bytesRead, long contentLength, boolean done) { + callback.onDownloadProgress(bytesRead, contentLength, done); + } + }; + + progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { + @Override + public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { + callback.onUploadProgress(bytesWritten, contentLength, done); + } + }; + } + + com.squareup.okhttp.Call call = updateUserValidateBeforeCall(username, body, progressListener, progressRequestListener); + apiClient.executeAsync(call, callback); + return call; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java index b606da94d2f..31b4137edcf 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java @@ -22,6 +22,7 @@ import io.swagger.annotations.ApiModelProperty; * Animal */ + public class Animal { @SerializedName("className") private String className = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Capitalization.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Capitalization.java new file mode 100644 index 00000000000..0767353985f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Capitalization.java @@ -0,0 +1,203 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @SerializedName("smallCamel") + private String smallCamel = null; + + @SerializedName("CapitalCamel") + private String capitalCamel = null; + + @SerializedName("small_Snake") + private String smallSnake = null; + + @SerializedName("Capital_Snake") + private String capitalSnake = null; + + @SerializedName("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @SerializedName("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(example = "null", value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(example = "null", value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java index ec1873d9971..14116c3c445 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumTest.java @@ -32,7 +32,10 @@ public class EnumTest { UPPER("UPPER"), @SerializedName("lower") - LOWER("lower"); + LOWER("lower"), + + @SerializedName("") + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/retrofit/pom.xml b/samples/client/petstore/java/retrofit/pom.xml index 2f3bfa33af4..5d23171a297 100644 --- a/samples/client/petstore/java/retrofit/pom.xml +++ b/samples/client/petstore/java/retrofit/pom.xml @@ -6,8 +6,10 @@ jar swagger-petstore-retrofit 1.0.0 + https://github.com/swagger-api/swagger-codegen + Swagger Java - scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git scm:git:git@github.com:swagger-api/swagger-codegen.git https://github.com/swagger-api/swagger-codegen @@ -22,7 +24,16 @@ repo - + + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + @@ -116,9 +127,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java index 59094331de2..ed9821db8f7 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java @@ -54,11 +54,11 @@ public class ApiClient { this(); for(String authName : authNames) { Interceptor auth; - if (authName == "api_key") { + if ("api_key".equals(authName)) { auth = new ApiKeyAuth("header", "api_key"); - } else if (authName == "http_basic_test") { + } else if ("http_basic_test".equals(authName)) { auth = new HttpBasicAuth(); - } else if (authName == "petstore_auth") { + } else if ("petstore_auth".equals(authName)) { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); @@ -69,7 +69,7 @@ public class ApiClient { /** * Basic constructor for single auth name - * @param authName + * @param authName Authentication name */ public ApiClient(String authName) { this(new String[]{authName}); @@ -77,8 +77,8 @@ public class ApiClient { /** * Helper constructor for single api key - * @param authName - * @param apiKey + * @param authName Authentication name + * @param apiKey API key */ public ApiClient(String authName, String apiKey) { this(authName); @@ -87,9 +87,9 @@ public class ApiClient { /** * Helper constructor for single basic auth or password oauth2 - * @param authName - * @param username - * @param password + * @param authName Authentication name + * @param username Username + * @param password Password */ public ApiClient(String authName, String username, String password) { this(authName); @@ -98,11 +98,11 @@ public class ApiClient { /** * Helper constructor for single password oauth2 - * @param authName - * @param clientId - * @param secret - * @param username - * @param password + * @param authName Authentication name + * @param clientId Client ID + * @param secret Client secret + * @param username Username + * @param password Password */ public ApiClient(String authName, String clientId, String secret, String username, String password) { this(authName); @@ -136,7 +136,7 @@ public class ApiClient { /** * Helper method to configure the first api key found - * @param apiKey + * @param apiKey API key */ private void setApiKey(String apiKey) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -150,8 +150,8 @@ public class ApiClient { /** * Helper method to configure the username/password for basic auth or password oauth - * @param username - * @param password + * @param username Username + * @param password Password */ private void setCredentials(String username, String password) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -170,7 +170,7 @@ public class ApiClient { /** * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Token request builder */ public TokenRequestBuilder getTokenEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -184,7 +184,7 @@ public class ApiClient { /** * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return + * @return Authentication request builder */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -198,7 +198,7 @@ public class ApiClient { /** * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken + * @param accessToken Access token */ public void setAccessToken(String accessToken) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -212,9 +212,9 @@ public class ApiClient { /** * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId - * @param clientSecret - * @param redirectURI + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -234,7 +234,7 @@ public class ApiClient { /** * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener + * @param accessTokenListener Access token listener */ public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { @@ -248,8 +248,8 @@ public class ApiClient { /** * Adds an authorization to be used by the client - * @param authName - * @param authorization + * @param authName Authentication name + * @param authorization Authorization */ public void addAuthorization(String authName, Interceptor authorization) { if (apiAuthorizations.containsKey(authName)) { @@ -287,7 +287,7 @@ public class ApiClient { /** * Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the RestAdapter - * @param okClient + * @param okClient OkHttp client */ public void configureFromOkclient(OkHttpClient okClient) { OkHttpClient clone = okClient.clone(); @@ -355,14 +355,15 @@ class GsonConverterWrapper implements Converter { */ class DateTimeTypeAdapter extends TypeAdapter { - private final DateTimeFormatter formatter = ISODateTimeFormat.dateTime(); + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); @Override public void write(JsonWriter out, DateTime date) throws IOException { if (date == null) { out.nullValue(); } else { - out.value(formatter.print(date)); + out.value(printFormatter.print(date)); } } @@ -374,7 +375,7 @@ class DateTimeTypeAdapter extends TypeAdapter { return null; default: String date = in.nextString(); - return formatter.parseDateTime(date); + return parseFormatter.parseDateTime(date); } } } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java index 9f0ec47237b..67eb33f195e 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/FakeApi.java @@ -35,7 +35,6 @@ public interface FakeApi { * Async method * @param body client model (required) * @param cb callback method - * @return void */ @PATCH("/fake") @@ -87,7 +86,6 @@ public interface FakeApi { * @param password None (optional) * @param paramCallback None (optional) * @param cb callback method - * @return void */ @retrofit.http.FormUrlEncoded @@ -128,7 +126,6 @@ public interface FakeApi { * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) * @param cb callback method - * @return void */ @retrofit.http.FormUrlEncoded diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java deleted file mode 100644 index 3f4ad999a37..00000000000 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java +++ /dev/null @@ -1,42 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.client.CollectionFormats.*; - -import retrofit.Callback; -import retrofit.http.*; -import retrofit.mime.*; - -import io.swagger.client.model.Client; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public interface Fake_classname_tags123Api { - /** - * To test class name in snake case - * Sync method - * - * @param body client model (required) - * @return Client - */ - - @PATCH("/fake_classname_test") - Client testClassname( - @retrofit.http.Body Client body - ); - - /** - * To test class name in snake case - * Async method - * @param body client model (required) - * @param cb callback method - * @return void - */ - - @PATCH("/fake_classname_test") - void testClassname( - @retrofit.http.Body Client body, Callback cb - ); -} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index ce7eb9ed1d8..6f8b1d17830 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -34,7 +34,6 @@ public interface PetApi { * Async method * @param body Pet object that needs to be added to the store (required) * @param cb callback method - * @return void */ @POST("/pet") @@ -61,7 +60,6 @@ public interface PetApi { * @param petId Pet id to delete (required) * @param apiKey (optional) * @param cb callback method - * @return void */ @DELETE("/pet/{petId}") @@ -73,7 +71,7 @@ public interface PetApi { * Sync method * Multiple status values can be provided with comma separated strings * @param status Status values that need to be considered for filter (required) - * @return List + * @return List<Pet> */ @GET("/pet/findByStatus") @@ -86,7 +84,6 @@ public interface PetApi { * Async method * @param status Status values that need to be considered for filter (required) * @param cb callback method - * @return void */ @GET("/pet/findByStatus") @@ -98,7 +95,7 @@ public interface PetApi { * Sync method * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by (required) - * @return List + * @return List<Pet> */ @GET("/pet/findByTags") @@ -111,7 +108,6 @@ public interface PetApi { * Async method * @param tags Tags to filter by (required) * @param cb callback method - * @return void */ @GET("/pet/findByTags") @@ -136,7 +132,6 @@ public interface PetApi { * Async method * @param petId ID of pet to return (required) * @param cb callback method - * @return void */ @GET("/pet/{petId}") @@ -161,7 +156,6 @@ public interface PetApi { * Async method * @param body Pet object that needs to be added to the store (required) * @param cb callback method - * @return void */ @PUT("/pet") @@ -191,7 +185,6 @@ public interface PetApi { * @param name Updated name of the pet (optional) * @param status Updated status of the pet (optional) * @param cb callback method - * @return void */ @retrofit.http.FormUrlEncoded @@ -222,7 +215,6 @@ public interface PetApi { * @param additionalMetadata Additional data to pass to server (optional) * @param file file to upload (optional) * @param cb callback method - * @return void */ @retrofit.http.Multipart diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index c29f87ef9cc..7dba9b5d855 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -32,7 +32,6 @@ public interface StoreApi { * Async method * @param orderId ID of the order that needs to be deleted (required) * @param cb callback method - * @return void */ @DELETE("/store/order/{orderId}") @@ -43,7 +42,7 @@ public interface StoreApi { * Returns pet inventories by status * Sync method * Returns a map of status codes to quantities - * @return Map + * @return Map<String, Integer> */ @GET("/store/inventory") @@ -54,7 +53,6 @@ public interface StoreApi { * Returns pet inventories by status * Async method * @param cb callback method - * @return void */ @GET("/store/inventory") @@ -79,7 +77,6 @@ public interface StoreApi { * Async method * @param orderId ID of pet that needs to be fetched (required) * @param cb callback method - * @return void */ @GET("/store/order/{orderId}") @@ -104,7 +101,6 @@ public interface StoreApi { * Async method * @param body order placed for purchasing the pet (required) * @param cb callback method - * @return void */ @POST("/store/order") diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index 43876970c3f..4eb592928f8 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -32,7 +32,6 @@ public interface UserApi { * Async method * @param body Created user object (required) * @param cb callback method - * @return void */ @POST("/user") @@ -57,7 +56,6 @@ public interface UserApi { * Async method * @param body List of user object (required) * @param cb callback method - * @return void */ @POST("/user/createWithArray") @@ -82,7 +80,6 @@ public interface UserApi { * Async method * @param body List of user object (required) * @param cb callback method - * @return void */ @POST("/user/createWithList") @@ -107,7 +104,6 @@ public interface UserApi { * Async method * @param username The name that needs to be deleted (required) * @param cb callback method - * @return void */ @DELETE("/user/{username}") @@ -132,7 +128,6 @@ public interface UserApi { * Async method * @param username The name that needs to be fetched. Use user1 for testing. (required) * @param cb callback method - * @return void */ @GET("/user/{username}") @@ -159,7 +154,6 @@ public interface UserApi { * @param username The user name for login (required) * @param password The password for login in clear text (required) * @param cb callback method - * @return void */ @GET("/user/login") @@ -181,7 +175,6 @@ public interface UserApi { * Logs out current logged in user session * Async method * @param cb callback method - * @return void */ @GET("/user/logout") @@ -208,7 +201,6 @@ public interface UserApi { * @param username name that need to be deleted (required) * @param body Updated user object (required) * @param cb callback method - * @return void */ @PUT("/user/{username}") diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java index b606da94d2f..31b4137edcf 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Animal.java @@ -22,6 +22,7 @@ import io.swagger.annotations.ApiModelProperty; * Animal */ + public class Animal { @SerializedName("className") private String className = null; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Capitalization.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Capitalization.java new file mode 100644 index 00000000000..0767353985f --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Capitalization.java @@ -0,0 +1,203 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @SerializedName("smallCamel") + private String smallCamel = null; + + @SerializedName("CapitalCamel") + private String capitalCamel = null; + + @SerializedName("small_Snake") + private String smallSnake = null; + + @SerializedName("Capital_Snake") + private String capitalSnake = null; + + @SerializedName("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @SerializedName("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(example = "null", value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(example = "null", value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java index ec1873d9971..14116c3c445 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/EnumTest.java @@ -32,7 +32,10 @@ public class EnumTest { UPPER("UPPER"), @SerializedName("lower") - LOWER("lower"); + LOWER("lower"), + + @SerializedName("") + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/retrofit2-play24/docs/Capitalization.md b/samples/client/petstore/java/retrofit2-play24/docs/Capitalization.md new file mode 100644 index 00000000000..0f3064c1996 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/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] + + + diff --git a/samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md b/samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md +++ b/samples/client/petstore/java/retrofit2-play24/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/retrofit2-play24/pom.xml b/samples/client/petstore/java/retrofit2-play24/pom.xml index e6e546a3c01..db713a8877f 100644 --- a/samples/client/petstore/java/retrofit2-play24/pom.xml +++ b/samples/client/petstore/java/retrofit2-play24/pom.xml @@ -6,8 +6,10 @@ jar swagger-java-client 1.0.0 + https://github.com/swagger-api/swagger-codegen + Swagger Java - scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git scm:git:git@github.com:swagger-api/swagger-codegen.git https://github.com/swagger-api/swagger-codegen @@ -22,7 +24,16 @@ repo - + + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + @@ -108,9 +119,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger @@ -142,7 +199,7 @@ threetenbp ${threetenbp-version} - + com.squareup.retrofit2 @@ -163,7 +220,7 @@ com.fasterxml.jackson.core jackson-databind ${jackson-version} - + com.fasterxml.jackson.datatype jackson-datatype-joda diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/PetApi.java index 8ae3082d15e..ec44297e20e 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/PetApi.java @@ -53,7 +53,7 @@ public interface PetApi { * 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) - * @return Call<List> + * @return Call<List<Pet>> */ @GET("pet/findByStatus") @@ -65,7 +65,7 @@ public interface PetApi { * 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) - * @return Call<List> + * @return Call<List<Pet>> */ @GET("pet/findByTags") diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/StoreApi.java index 84b3f99f2c9..d2e38f90cbf 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/api/StoreApi.java @@ -34,7 +34,7 @@ public interface StoreApi { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Call<Map> + * @return Call<Map<String, Integer>> */ @GET("store/inventory") diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java index a1e8586074f..32cf42cdd74 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Animal.java @@ -25,10 +25,12 @@ import javax.validation.constraints.*; /** * Animal */ -@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "className" ) -@JsonSubTypes({ - @JsonSubTypes.Type(value = Dog.class, name = "Dog"),@JsonSubTypes.Type(value = Cat.class, name = "Cat"), +@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"), }) + public class Animal { @JsonProperty("className") private String className = null; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Capitalization.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Capitalization.java new file mode 100644 index 00000000000..6aa8eb59dc5 --- /dev/null +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/Capitalization.java @@ -0,0 +1,205 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(example = "null", value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(example = "null", value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java index f0da7fb482c..38fa33789f3 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/EnumTest.java @@ -32,7 +32,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java index 254be369cb8..1eacb85997d 100644 --- a/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2-play24/src/main/java/io/swagger/client/model/FormatTest.java @@ -142,6 +142,8 @@ public class FormatTest { * @return number **/ @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") @ApiModelProperty(example = "null", required = true, value = "") public BigDecimal getNumber() { return number; @@ -162,6 +164,8 @@ public class FormatTest { * maximum: 987.6 * @return _float **/ + @DecimalMin("54.3") + @DecimalMax("987.6") @ApiModelProperty(example = "null", value = "") public Float getFloat() { return _float; @@ -182,6 +186,8 @@ public class FormatTest { * maximum: 123.4 * @return _double **/ + @DecimalMin("67.8") + @DecimalMax("123.4") @ApiModelProperty(example = "null", value = "") public Double getDouble() { return _double; diff --git a/samples/client/petstore/java/retrofit2/docs/Capitalization.md b/samples/client/petstore/java/retrofit2/docs/Capitalization.md new file mode 100644 index 00000000000..0f3064c1996 --- /dev/null +++ b/samples/client/petstore/java/retrofit2/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] + + + diff --git a/samples/client/petstore/java/retrofit2/docs/EnumTest.md b/samples/client/petstore/java/retrofit2/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/retrofit2/docs/EnumTest.md +++ b/samples/client/petstore/java/retrofit2/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index 2aa68191b09..1ec90faab5f 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -6,8 +6,10 @@ jar swagger-petstore-retrofit2 1.0.0 + https://github.com/swagger-api/swagger-codegen + Swagger Java - scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git scm:git:git@github.com:swagger-api/swagger-codegen.git https://github.com/swagger-api/swagger-codegen @@ -22,7 +24,16 @@ repo - + + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + @@ -108,9 +119,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger @@ -142,7 +199,7 @@ threetenbp ${threetenbp-version} - + diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java index ba6bfe36e10..c6bd89ef1e6 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/ApiClient.java @@ -42,11 +42,11 @@ public class ApiClient { this(); for(String authName : authNames) { Interceptor auth; - if (authName.equals("api_key")) { + if ("api_key".equals(authName)) { auth = new ApiKeyAuth("header", "api_key"); - } else if (authName.equals("http_basic_test")) { + } else if ("http_basic_test".equals(authName)) { auth = new HttpBasicAuth(); - } else if (authName.equals("petstore_auth")) { + } else if ("petstore_auth".equals(authName)) { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); @@ -374,3 +374,61 @@ class GsonCustomConverterFactory extends Converter.Factory } } +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(printFormatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return parseFormatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java deleted file mode 100644 index 2fae2ba7d7f..00000000000 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.client.CollectionFormats.*; - - -import retrofit2.Call; -import retrofit2.http.*; - -import okhttp3.RequestBody; - -import io.swagger.client.model.Client; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public interface Fake_classname_tags123Api { - /** - * To test class name in snake case - * - * @param body client model (required) - * @return Call<Client> - */ - - @Headers({ - "Content-Type:application/json" - }) - @PATCH("fake_classname_test") - Call testClassname( - @retrofit2.http.Body Client body - ); - -} diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java index 21572a18938..0860d5354ed 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/PetApi.java @@ -51,7 +51,7 @@ public interface PetApi { * 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) - * @return Call<List> + * @return Call<List<Pet>> */ @GET("pet/findByStatus") @@ -63,7 +63,7 @@ public interface PetApi { * 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) - * @return Call<List> + * @return Call<List<Pet>> */ @GET("pet/findByTags") diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java index 643a7302b84..f2d3a26d0ed 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/api/StoreApi.java @@ -32,7 +32,7 @@ public interface StoreApi { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Call<Map> + * @return Call<Map<String, Integer>> */ @GET("store/inventory") diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java index b606da94d2f..31b4137edcf 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Animal.java @@ -22,6 +22,7 @@ import io.swagger.annotations.ApiModelProperty; * Animal */ + public class Animal { @SerializedName("className") private String className = null; diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Capitalization.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Capitalization.java new file mode 100644 index 00000000000..0767353985f --- /dev/null +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/Capitalization.java @@ -0,0 +1,203 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @SerializedName("smallCamel") + private String smallCamel = null; + + @SerializedName("CapitalCamel") + private String capitalCamel = null; + + @SerializedName("small_Snake") + private String smallSnake = null; + + @SerializedName("Capital_Snake") + private String capitalSnake = null; + + @SerializedName("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @SerializedName("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(example = "null", value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(example = "null", value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java index ec1873d9971..14116c3c445 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/io/swagger/client/model/EnumTest.java @@ -32,7 +32,10 @@ public class EnumTest { UPPER("UPPER"), @SerializedName("lower") - LOWER("lower"); + LOWER("lower"), + + @SerializedName("") + EMPTY(""); private String value; diff --git a/samples/client/petstore/java/retrofit2rx/docs/Capitalization.md b/samples/client/petstore/java/retrofit2rx/docs/Capitalization.md new file mode 100644 index 00000000000..0f3064c1996 --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/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] + + + diff --git a/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md b/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md index 1746ccb273e..08fee344882 100644 --- a/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md +++ b/samples/client/petstore/java/retrofit2rx/docs/EnumTest.md @@ -16,6 +16,7 @@ Name | Value ---- | ----- UPPER | "UPPER" LOWER | "lower" +EMPTY | "" diff --git a/samples/client/petstore/java/retrofit2rx/pom.xml b/samples/client/petstore/java/retrofit2rx/pom.xml index a74c7f309e0..d0877daf669 100644 --- a/samples/client/petstore/java/retrofit2rx/pom.xml +++ b/samples/client/petstore/java/retrofit2rx/pom.xml @@ -6,8 +6,10 @@ jar swagger-petstore-retrofit2-rx 1.0.0 + https://github.com/swagger-api/swagger-codegen + Swagger Java - scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git scm:git:git@github.com:swagger-api/swagger-codegen.git https://github.com/swagger-api/swagger-codegen @@ -22,7 +24,16 @@ repo - + + + + Swagger + apiteam@swagger.io + Swagger + http://swagger.io + + + @@ -108,9 +119,55 @@ org.apache.maven.plugins maven-javadoc-plugin 2.10.4 + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + io.swagger @@ -152,7 +209,7 @@ adapter-rxjava ${retrofit-version} - + diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java index 0ac7c8efeae..f03653fcd6d 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/ApiClient.java @@ -43,11 +43,11 @@ public class ApiClient { this(); for(String authName : authNames) { Interceptor auth; - if (authName.equals("api_key")) { + if ("api_key".equals(authName)) { auth = new ApiKeyAuth("header", "api_key"); - } else if (authName.equals("http_basic_test")) { + } else if ("http_basic_test".equals(authName)) { auth = new HttpBasicAuth(); - } else if (authName.equals("petstore_auth")) { + } else if ("petstore_auth".equals(authName)) { auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); @@ -376,3 +376,61 @@ class GsonCustomConverterFactory extends Converter.Factory } } +/** + * Gson TypeAdapter for Joda DateTime type + */ +class DateTimeTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); + private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(printFormatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return parseFormatter.parseDateTime(date); + } + } +} + +/** + * Gson TypeAdapter for Joda LocalDate type + */ +class LocalDateTypeAdapter extends TypeAdapter { + + private final DateTimeFormatter formatter = ISODateTimeFormat.date(); + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } +} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java deleted file mode 100644 index 68cc5b7f540..00000000000 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/Fake_classname_tags123Api.java +++ /dev/null @@ -1,35 +0,0 @@ -package io.swagger.client.api; - -import io.swagger.client.CollectionFormats.*; - -import rx.Observable; - -import retrofit2.http.*; - -import okhttp3.RequestBody; - -import io.swagger.client.model.Client; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public interface Fake_classname_tags123Api { - /** - * To test class name in snake case - * - * @param body client model (required) - * @return Call<Client> - */ - - @Headers({ - "Content-Type:application/json" - }) - @PATCH("fake_classname_test") - Observable testClassname( - @retrofit2.http.Body Client body - ); - -} diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java index e7ee14b2c0e..7d036572540 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/PetApi.java @@ -51,7 +51,7 @@ public interface PetApi { * 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) - * @return Call<List> + * @return Call<List<Pet>> */ @GET("pet/findByStatus") @@ -63,7 +63,7 @@ public interface PetApi { * 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) - * @return Call<List> + * @return Call<List<Pet>> */ @GET("pet/findByTags") diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java index eab5f872d0b..847c2721144 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/api/StoreApi.java @@ -32,7 +32,7 @@ public interface StoreApi { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Call<Map> + * @return Call<Map<String, Integer>> */ @GET("store/inventory") diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java index b606da94d2f..31b4137edcf 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Animal.java @@ -22,6 +22,7 @@ import io.swagger.annotations.ApiModelProperty; * Animal */ + public class Animal { @SerializedName("className") private String className = null; diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Capitalization.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Capitalization.java new file mode 100644 index 00000000000..0767353985f --- /dev/null +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/Capitalization.java @@ -0,0 +1,203 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.client.model; + +import java.util.Objects; +import com.google.gson.annotations.SerializedName; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +/** + * Capitalization + */ + +public class Capitalization { + @SerializedName("smallCamel") + private String smallCamel = null; + + @SerializedName("CapitalCamel") + private String capitalCamel = null; + + @SerializedName("small_Snake") + private String smallSnake = null; + + @SerializedName("Capital_Snake") + private String capitalSnake = null; + + @SerializedName("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @SerializedName("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(example = "null", value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(example = "null", value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(example = "null", value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java index ec1873d9971..14116c3c445 100644 --- a/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java +++ b/samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/EnumTest.java @@ -32,7 +32,10 @@ public class EnumTest { UPPER("UPPER"), @SerializedName("lower") - LOWER("lower"); + LOWER("lower"), + + @SerializedName("") + EMPTY(""); private String value; diff --git a/samples/client/petstore/javascript-promise/README.md b/samples/client/petstore/javascript-promise/README.md index dbb130add78..93ceb195c01 100644 --- a/samples/client/petstore/javascript-promise/README.md +++ b/samples/client/petstore/javascript-promise/README.md @@ -106,6 +106,7 @@ Class | Method | HTTP request | Description - [SwaggerPetstore.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [SwaggerPetstore.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [SwaggerPetstore.ArrayTest](docs/ArrayTest.md) + - [SwaggerPetstore.Capitalization](docs/Capitalization.md) - [SwaggerPetstore.Cat](docs/Cat.md) - [SwaggerPetstore.Category](docs/Category.md) - [SwaggerPetstore.ClassModel](docs/ClassModel.md) diff --git a/samples/client/petstore/javascript-promise/docs/Capitalization.md b/samples/client/petstore/javascript-promise/docs/Capitalization.md new file mode 100644 index 00000000000..c223a4ee982 --- /dev/null +++ b/samples/client/petstore/javascript-promise/docs/Capitalization.md @@ -0,0 +1,13 @@ +# SwaggerPetstore.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] + + diff --git a/samples/client/petstore/javascript-promise/docs/EnumTest.md b/samples/client/petstore/javascript-promise/docs/EnumTest.md index c907dac4951..9d85a20016d 100644 --- a/samples/client/petstore/javascript-promise/docs/EnumTest.md +++ b/samples/client/petstore/javascript-promise/docs/EnumTest.md @@ -17,6 +17,8 @@ Name | Type | Description | Notes * `lower` (value: `"lower"`) +* `empty` (value: `""`) + diff --git a/samples/client/petstore/javascript-promise/src/ApiClient.js b/samples/client/petstore/javascript-promise/src/ApiClient.js index 3d087d1cc2d..6556dba1fbb 100644 --- a/samples/client/petstore/javascript-promise/src/ApiClient.js +++ b/samples/client/petstore/javascript-promise/src/ApiClient.js @@ -314,13 +314,13 @@ * @returns A value of the specified type. */ exports.prototype.deserialize = function deserialize(response, returnType) { - if (response == null || returnType == null) { + if (response == null || returnType == null || response.status == 204) { return null; } // Rely on SuperAgent for parsing response body. // See http://visionmedia.github.io/superagent/#parsing-response-bodies var data = response.body; - if (data == null || !Object.keys(data).length) { + if (data == null || (typeof data === 'object' && typeof data.length === 'undefined' && !Object.keys(data).length)) { // SuperAgent does not always produce a body; use the unparsed response as a fallback data = response.text; } @@ -424,8 +424,12 @@ if (error) { reject(error); } else { - var data = _this.deserialize(response, returnType); - resolve(data); + try { + var data = _this.deserialize(response, returnType); + resolve(data); + } catch (err) { + reject(err); + } } }); }); diff --git a/samples/client/petstore/javascript-promise/src/index.js b/samples/client/petstore/javascript-promise/src/index.js index 9d68a7397c5..6447d8e8f4e 100644 --- a/samples/client/petstore/javascript-promise/src/index.js +++ b/samples/client/petstore/javascript-promise/src/index.js @@ -14,12 +14,12 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/ClassModel', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/OuterEnum', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/Fake_classname_tags123Api', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); + define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Capitalization', 'model/Cat', 'model/Category', 'model/ClassModel', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/OuterEnum', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/Fake_classname_tags123Api', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/ClassModel'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/OuterEnum'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/Fake_classname_tags123Api'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); + module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Capitalization'), require('./model/Cat'), require('./model/Category'), require('./model/ClassModel'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/OuterEnum'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/Fake_classname_tags123Api'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, ClassModel, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, OuterEnum, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, Fake_classname_tags123Api, PetApi, StoreApi, UserApi) { +}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Capitalization, Cat, Category, ClassModel, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, OuterEnum, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, Fake_classname_tags123Api, PetApi, StoreApi, UserApi) { 'use strict'; /** @@ -94,6 +94,11 @@ * @property {module:model/ArrayTest} */ ArrayTest: ArrayTest, + /** + * The Capitalization model constructor. + * @property {module:model/Capitalization} + */ + Capitalization: Capitalization, /** * The Cat model constructor. * @property {module:model/Cat} diff --git a/samples/client/petstore/javascript-promise/src/model/AnimalFarm.js b/samples/client/petstore/javascript-promise/src/model/AnimalFarm.js index b21d83a66dc..4cd8b41cf51 100644 --- a/samples/client/petstore/javascript-promise/src/model/AnimalFarm.js +++ b/samples/client/petstore/javascript-promise/src/model/AnimalFarm.js @@ -61,7 +61,7 @@ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); - ApiClient.constructFromObject(data, obj, Animal); + ApiClient.constructFromObject(data, obj, 'Animal'); } return obj; diff --git a/samples/client/petstore/javascript-promise/src/model/Capitalization.js b/samples/client/petstore/javascript-promise/src/model/Capitalization.js new file mode 100644 index 00000000000..84480fa0d40 --- /dev/null +++ b/samples/client/petstore/javascript-promise/src/model/Capitalization.js @@ -0,0 +1,120 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Capitalization = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The Capitalization model module. + * @module model/Capitalization + * @version 1.0.0 + */ + + /** + * Constructs a new Capitalization. + * @alias module:model/Capitalization + * @class + */ + var exports = function() { + var _this = this; + + + + + + + + }; + + /** + * Constructs a Capitalization from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Capitalization} obj Optional instance to populate. + * @return {module:model/Capitalization} The populated Capitalization instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('smallCamel')) { + obj['smallCamel'] = ApiClient.convertToType(data['smallCamel'], 'String'); + } + if (data.hasOwnProperty('CapitalCamel')) { + obj['CapitalCamel'] = ApiClient.convertToType(data['CapitalCamel'], 'String'); + } + if (data.hasOwnProperty('small_Snake')) { + obj['small_Snake'] = ApiClient.convertToType(data['small_Snake'], 'String'); + } + if (data.hasOwnProperty('Capital_Snake')) { + obj['Capital_Snake'] = ApiClient.convertToType(data['Capital_Snake'], 'String'); + } + if (data.hasOwnProperty('SCA_ETH_Flow_Points')) { + obj['SCA_ETH_Flow_Points'] = ApiClient.convertToType(data['SCA_ETH_Flow_Points'], 'String'); + } + if (data.hasOwnProperty('ATT_NAME')) { + obj['ATT_NAME'] = ApiClient.convertToType(data['ATT_NAME'], 'String'); + } + } + return obj; + } + + /** + * @member {String} smallCamel + */ + exports.prototype['smallCamel'] = undefined; + /** + * @member {String} CapitalCamel + */ + exports.prototype['CapitalCamel'] = undefined; + /** + * @member {String} small_Snake + */ + exports.prototype['small_Snake'] = undefined; + /** + * @member {String} Capital_Snake + */ + exports.prototype['Capital_Snake'] = undefined; + /** + * @member {String} SCA_ETH_Flow_Points + */ + exports.prototype['SCA_ETH_Flow_Points'] = undefined; + /** + * Name of the pet + * @member {String} ATT_NAME + */ + exports.prototype['ATT_NAME'] = undefined; + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript-promise/src/model/EnumClass.js b/samples/client/petstore/javascript-promise/src/model/EnumClass.js index 1ad4876ebe0..20ab7dad1f7 100644 --- a/samples/client/petstore/javascript-promise/src/model/EnumClass.js +++ b/samples/client/petstore/javascript-promise/src/model/EnumClass.js @@ -57,7 +57,7 @@ * @return {module:model/EnumClass} The enum EnumClass value. */ exports.constructFromObject = function(object) { - return exports[object]; + return object; } return exports; diff --git a/samples/client/petstore/javascript-promise/src/model/EnumTest.js b/samples/client/petstore/javascript-promise/src/model/EnumTest.js index 077ebcd470b..e33dd2c1186 100644 --- a/samples/client/petstore/javascript-promise/src/model/EnumTest.js +++ b/samples/client/petstore/javascript-promise/src/model/EnumTest.js @@ -111,7 +111,12 @@ * value: "lower" * @const */ - "lower": "lower" }; + "lower": "lower", + /** + * value: "" + * @const + */ + "empty": "" }; /** * Allowed values for the enum_integer property. diff --git a/samples/client/petstore/javascript-promise/src/model/OuterEnum.js b/samples/client/petstore/javascript-promise/src/model/OuterEnum.js index 8a31a9d87be..21da6b555e2 100644 --- a/samples/client/petstore/javascript-promise/src/model/OuterEnum.js +++ b/samples/client/petstore/javascript-promise/src/model/OuterEnum.js @@ -57,7 +57,7 @@ * @return {module:model/OuterEnum} The enum OuterEnum value. */ exports.constructFromObject = function(object) { - return exports[object]; + return object; } return exports; diff --git a/samples/client/petstore/javascript-promise/test/model/Capitalization.spec.js b/samples/client/petstore/javascript-promise/test/model/Capitalization.spec.js new file mode 100644 index 00000000000..f1aa695c3fd --- /dev/null +++ b/samples/client/petstore/javascript-promise/test/model/Capitalization.spec.js @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.Capitalization(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Capitalization', function() { + it('should create an instance of Capitalization', function() { + // uncomment below and update the code to test Capitalization + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be.a(SwaggerPetstore.Capitalization); + }); + + it('should have the property smallCamel (base name: "smallCamel")', function() { + // uncomment below and update the code to test the property smallCamel + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property capitalCamel (base name: "CapitalCamel")', function() { + // uncomment below and update the code to test the property capitalCamel + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property smallSnake (base name: "small_Snake")', function() { + // uncomment below and update the code to test the property smallSnake + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property capitalSnake (base name: "Capital_Snake")', function() { + // uncomment below and update the code to test the property capitalSnake + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property sCAETHFlowPoints (base name: "SCA_ETH_Flow_Points")', function() { + // uncomment below and update the code to test the property sCAETHFlowPoints + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property ATT_NAME (base name: "ATT_NAME")', function() { + // uncomment below and update the code to test the property ATT_NAME + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/javascript/README.md b/samples/client/petstore/javascript/README.md index a7de35bf225..c3b2548c749 100644 --- a/samples/client/petstore/javascript/README.md +++ b/samples/client/petstore/javascript/README.md @@ -109,6 +109,7 @@ Class | Method | HTTP request | Description - [SwaggerPetstore.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [SwaggerPetstore.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [SwaggerPetstore.ArrayTest](docs/ArrayTest.md) + - [SwaggerPetstore.Capitalization](docs/Capitalization.md) - [SwaggerPetstore.Cat](docs/Cat.md) - [SwaggerPetstore.Category](docs/Category.md) - [SwaggerPetstore.ClassModel](docs/ClassModel.md) diff --git a/samples/client/petstore/javascript/docs/Capitalization.md b/samples/client/petstore/javascript/docs/Capitalization.md new file mode 100644 index 00000000000..c223a4ee982 --- /dev/null +++ b/samples/client/petstore/javascript/docs/Capitalization.md @@ -0,0 +1,13 @@ +# SwaggerPetstore.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] + + diff --git a/samples/client/petstore/javascript/docs/EnumTest.md b/samples/client/petstore/javascript/docs/EnumTest.md index c907dac4951..9d85a20016d 100644 --- a/samples/client/petstore/javascript/docs/EnumTest.md +++ b/samples/client/petstore/javascript/docs/EnumTest.md @@ -17,6 +17,8 @@ Name | Type | Description | Notes * `lower` (value: `"lower"`) +* `empty` (value: `""`) + diff --git a/samples/client/petstore/javascript/src/ApiClient.js b/samples/client/petstore/javascript/src/ApiClient.js index 878c50dba34..10e54f6911a 100644 --- a/samples/client/petstore/javascript/src/ApiClient.js +++ b/samples/client/petstore/javascript/src/ApiClient.js @@ -314,13 +314,13 @@ * @returns A value of the specified type. */ exports.prototype.deserialize = function deserialize(response, returnType) { - if (response == null || returnType == null) { + if (response == null || returnType == null || response.status == 204) { return null; } // Rely on SuperAgent for parsing response body. // See http://visionmedia.github.io/superagent/#parsing-response-bodies var data = response.body; - if (data == null || !Object.keys(data).length) { + if (data == null || (typeof data === 'object' && typeof data.length === 'undefined' && !Object.keys(data).length)) { // SuperAgent does not always produce a body; use the unparsed response as a fallback data = response.text; } @@ -433,7 +433,11 @@ if (callback) { var data = null; if (!error) { - data = _this.deserialize(response, returnType); + try { + data = _this.deserialize(response, returnType); + } catch (err) { + error = err; + } } callback(error, data, response); } diff --git a/samples/client/petstore/javascript/src/index.js b/samples/client/petstore/javascript/src/index.js index 9d68a7397c5..6447d8e8f4e 100644 --- a/samples/client/petstore/javascript/src/index.js +++ b/samples/client/petstore/javascript/src/index.js @@ -14,12 +14,12 @@ (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Cat', 'model/Category', 'model/ClassModel', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/OuterEnum', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/Fake_classname_tags123Api', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); + define(['ApiClient', 'model/AdditionalPropertiesClass', 'model/Animal', 'model/AnimalFarm', 'model/ApiResponse', 'model/ArrayOfArrayOfNumberOnly', 'model/ArrayOfNumberOnly', 'model/ArrayTest', 'model/Capitalization', 'model/Cat', 'model/Category', 'model/ClassModel', 'model/Client', 'model/Dog', 'model/EnumArrays', 'model/EnumClass', 'model/EnumTest', 'model/FormatTest', 'model/HasOnlyReadOnly', 'model/List', 'model/MapTest', 'model/MixedPropertiesAndAdditionalPropertiesClass', 'model/Model200Response', 'model/ModelReturn', 'model/Name', 'model/NumberOnly', 'model/Order', 'model/OuterEnum', 'model/Pet', 'model/ReadOnlyFirst', 'model/SpecialModelName', 'model/Tag', 'model/User', 'api/FakeApi', 'api/Fake_classname_tags123Api', 'api/PetApi', 'api/StoreApi', 'api/UserApi'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Cat'), require('./model/Category'), require('./model/ClassModel'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/OuterEnum'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/Fake_classname_tags123Api'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); + module.exports = factory(require('./ApiClient'), require('./model/AdditionalPropertiesClass'), require('./model/Animal'), require('./model/AnimalFarm'), require('./model/ApiResponse'), require('./model/ArrayOfArrayOfNumberOnly'), require('./model/ArrayOfNumberOnly'), require('./model/ArrayTest'), require('./model/Capitalization'), require('./model/Cat'), require('./model/Category'), require('./model/ClassModel'), require('./model/Client'), require('./model/Dog'), require('./model/EnumArrays'), require('./model/EnumClass'), require('./model/EnumTest'), require('./model/FormatTest'), require('./model/HasOnlyReadOnly'), require('./model/List'), require('./model/MapTest'), require('./model/MixedPropertiesAndAdditionalPropertiesClass'), require('./model/Model200Response'), require('./model/ModelReturn'), require('./model/Name'), require('./model/NumberOnly'), require('./model/Order'), require('./model/OuterEnum'), require('./model/Pet'), require('./model/ReadOnlyFirst'), require('./model/SpecialModelName'), require('./model/Tag'), require('./model/User'), require('./api/FakeApi'), require('./api/Fake_classname_tags123Api'), require('./api/PetApi'), require('./api/StoreApi'), require('./api/UserApi')); } -}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Cat, Category, ClassModel, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, OuterEnum, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, Fake_classname_tags123Api, PetApi, StoreApi, UserApi) { +}(function(ApiClient, AdditionalPropertiesClass, Animal, AnimalFarm, ApiResponse, ArrayOfArrayOfNumberOnly, ArrayOfNumberOnly, ArrayTest, Capitalization, Cat, Category, ClassModel, Client, Dog, EnumArrays, EnumClass, EnumTest, FormatTest, HasOnlyReadOnly, List, MapTest, MixedPropertiesAndAdditionalPropertiesClass, Model200Response, ModelReturn, Name, NumberOnly, Order, OuterEnum, Pet, ReadOnlyFirst, SpecialModelName, Tag, User, FakeApi, Fake_classname_tags123Api, PetApi, StoreApi, UserApi) { 'use strict'; /** @@ -94,6 +94,11 @@ * @property {module:model/ArrayTest} */ ArrayTest: ArrayTest, + /** + * The Capitalization model constructor. + * @property {module:model/Capitalization} + */ + Capitalization: Capitalization, /** * The Cat model constructor. * @property {module:model/Cat} diff --git a/samples/client/petstore/javascript/src/model/AnimalFarm.js b/samples/client/petstore/javascript/src/model/AnimalFarm.js index b21d83a66dc..4cd8b41cf51 100644 --- a/samples/client/petstore/javascript/src/model/AnimalFarm.js +++ b/samples/client/petstore/javascript/src/model/AnimalFarm.js @@ -61,7 +61,7 @@ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); - ApiClient.constructFromObject(data, obj, Animal); + ApiClient.constructFromObject(data, obj, 'Animal'); } return obj; diff --git a/samples/client/petstore/javascript/src/model/Capitalization.js b/samples/client/petstore/javascript/src/model/Capitalization.js new file mode 100644 index 00000000000..84480fa0d40 --- /dev/null +++ b/samples/client/petstore/javascript/src/model/Capitalization.js @@ -0,0 +1,120 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.SwaggerPetstore) { + root.SwaggerPetstore = {}; + } + root.SwaggerPetstore.Capitalization = factory(root.SwaggerPetstore.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + + + + /** + * The Capitalization model module. + * @module model/Capitalization + * @version 1.0.0 + */ + + /** + * Constructs a new Capitalization. + * @alias module:model/Capitalization + * @class + */ + var exports = function() { + var _this = this; + + + + + + + + }; + + /** + * Constructs a Capitalization from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Capitalization} obj Optional instance to populate. + * @return {module:model/Capitalization} The populated Capitalization instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + + if (data.hasOwnProperty('smallCamel')) { + obj['smallCamel'] = ApiClient.convertToType(data['smallCamel'], 'String'); + } + if (data.hasOwnProperty('CapitalCamel')) { + obj['CapitalCamel'] = ApiClient.convertToType(data['CapitalCamel'], 'String'); + } + if (data.hasOwnProperty('small_Snake')) { + obj['small_Snake'] = ApiClient.convertToType(data['small_Snake'], 'String'); + } + if (data.hasOwnProperty('Capital_Snake')) { + obj['Capital_Snake'] = ApiClient.convertToType(data['Capital_Snake'], 'String'); + } + if (data.hasOwnProperty('SCA_ETH_Flow_Points')) { + obj['SCA_ETH_Flow_Points'] = ApiClient.convertToType(data['SCA_ETH_Flow_Points'], 'String'); + } + if (data.hasOwnProperty('ATT_NAME')) { + obj['ATT_NAME'] = ApiClient.convertToType(data['ATT_NAME'], 'String'); + } + } + return obj; + } + + /** + * @member {String} smallCamel + */ + exports.prototype['smallCamel'] = undefined; + /** + * @member {String} CapitalCamel + */ + exports.prototype['CapitalCamel'] = undefined; + /** + * @member {String} small_Snake + */ + exports.prototype['small_Snake'] = undefined; + /** + * @member {String} Capital_Snake + */ + exports.prototype['Capital_Snake'] = undefined; + /** + * @member {String} SCA_ETH_Flow_Points + */ + exports.prototype['SCA_ETH_Flow_Points'] = undefined; + /** + * Name of the pet + * @member {String} ATT_NAME + */ + exports.prototype['ATT_NAME'] = undefined; + + + + return exports; +})); + + diff --git a/samples/client/petstore/javascript/src/model/EnumClass.js b/samples/client/petstore/javascript/src/model/EnumClass.js index 1ad4876ebe0..20ab7dad1f7 100644 --- a/samples/client/petstore/javascript/src/model/EnumClass.js +++ b/samples/client/petstore/javascript/src/model/EnumClass.js @@ -57,7 +57,7 @@ * @return {module:model/EnumClass} The enum EnumClass value. */ exports.constructFromObject = function(object) { - return exports[object]; + return object; } return exports; diff --git a/samples/client/petstore/javascript/src/model/EnumTest.js b/samples/client/petstore/javascript/src/model/EnumTest.js index 077ebcd470b..e33dd2c1186 100644 --- a/samples/client/petstore/javascript/src/model/EnumTest.js +++ b/samples/client/petstore/javascript/src/model/EnumTest.js @@ -111,7 +111,12 @@ * value: "lower" * @const */ - "lower": "lower" }; + "lower": "lower", + /** + * value: "" + * @const + */ + "empty": "" }; /** * Allowed values for the enum_integer property. diff --git a/samples/client/petstore/javascript/src/model/OuterEnum.js b/samples/client/petstore/javascript/src/model/OuterEnum.js index 8a31a9d87be..21da6b555e2 100644 --- a/samples/client/petstore/javascript/src/model/OuterEnum.js +++ b/samples/client/petstore/javascript/src/model/OuterEnum.js @@ -57,7 +57,7 @@ * @return {module:model/OuterEnum} The enum OuterEnum value. */ exports.constructFromObject = function(object) { - return exports[object]; + return object; } return exports; diff --git a/samples/client/petstore/javascript/test/model/Capitalization.spec.js b/samples/client/petstore/javascript/test/model/Capitalization.spec.js new file mode 100644 index 00000000000..f1aa695c3fd --- /dev/null +++ b/samples/client/petstore/javascript/test/model/Capitalization.spec.js @@ -0,0 +1,95 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. + define(['expect.js', '../../src/index'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + factory(require('expect.js'), require('../../src/index')); + } else { + // Browser globals (root is window) + factory(root.expect, root.SwaggerPetstore); + } +}(this, function(expect, SwaggerPetstore) { + 'use strict'; + + var instance; + + beforeEach(function() { + instance = new SwaggerPetstore.Capitalization(); + }); + + var getProperty = function(object, getter, property) { + // Use getter method if present; otherwise, get the property directly. + if (typeof object[getter] === 'function') + return object[getter](); + else + return object[property]; + } + + var setProperty = function(object, setter, property, value) { + // Use setter method if present; otherwise, set the property directly. + if (typeof object[setter] === 'function') + object[setter](value); + else + object[property] = value; + } + + describe('Capitalization', function() { + it('should create an instance of Capitalization', function() { + // uncomment below and update the code to test Capitalization + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be.a(SwaggerPetstore.Capitalization); + }); + + it('should have the property smallCamel (base name: "smallCamel")', function() { + // uncomment below and update the code to test the property smallCamel + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property capitalCamel (base name: "CapitalCamel")', function() { + // uncomment below and update the code to test the property capitalCamel + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property smallSnake (base name: "small_Snake")', function() { + // uncomment below and update the code to test the property smallSnake + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property capitalSnake (base name: "Capital_Snake")', function() { + // uncomment below and update the code to test the property capitalSnake + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property sCAETHFlowPoints (base name: "SCA_ETH_Flow_Points")', function() { + // uncomment below and update the code to test the property sCAETHFlowPoints + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + it('should have the property ATT_NAME (base name: "ATT_NAME")', function() { + // uncomment below and update the code to test the property ATT_NAME + //var instane = new SwaggerPetstore.Capitalization(); + //expect(instance).to.be(); + }); + + }); + +})); diff --git a/samples/client/petstore/objc/core-data/SwaggerClient.podspec b/samples/client/petstore/objc/core-data/SwaggerClient.podspec index 1a31e2e9a15..d00714358b1 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient.podspec +++ b/samples/client/petstore/objc/core-data/SwaggerClient.podspec @@ -30,8 +30,8 @@ Pod::Spec.new do |s| s.public_header_files = 'SwaggerClient/**/*.h' s.resources = 'SwaggerClient/**/*.{xcdatamodeld,xcdatamodel}' - s.dependency 'AFNetworking', '~> 3.1' - s.dependency 'JSONModel', '~> 1.4' + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' s.dependency 'ISO8601', '~> 0.6' end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h index 1c89bd5c5a3..74ba6e6b482 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h @@ -27,84 +27,113 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// /// /// @param body Pet object that needs to be added to the store (optional) +/// /// code:405 message:"Invalid input" --(NSNumber*) addPetWithBody: (SWGPet*) body +/// +/// @return +-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; + /// Deletes a pet /// /// /// @param petId Pet id to delete /// @param apiKey (optional) +/// /// code:400 message:"Invalid pet value" --(NSNumber*) deletePetWithPetId: (NSNumber*) petId +/// +/// @return +-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler; + /// 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 (optional) (default to available) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid status value" +/// /// @return NSArray* --(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status +-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; + /// 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 (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid tag value" +/// /// @return NSArray* --(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags +-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; + /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// @param petId ID of pet that needs to be fetched +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found" +/// /// @return SWGPet* --(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId +-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler; + /// Update an existing pet /// /// /// @param body Pet object that needs to be added to the store (optional) +/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found", /// code:405 message:"Validation exception" --(NSNumber*) updatePetWithBody: (SWGPet*) body +/// +/// @return +-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; + /// 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) +/// /// code:405 message:"Invalid input" --(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId +/// +/// @return +-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler; + /// 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) +/// /// code:0 message:"successful operation" --(NSNumber*) uploadFileWithPetId: (NSNumber*) petId +/// +/// @return +-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m index 0d0a55f2688..c0ca97c3480 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m @@ -52,10 +52,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Add a new pet to the store /// -/// @param body Pet object that needs to be added to the store (optional) +/// @param body Pet object that needs to be added to the store (optional) /// -/// code:405 message:"Invalid input" --(NSNumber*) addPetWithBody: (SWGPet*) body +/// @returns void +/// +-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -109,12 +110,13 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Deletes a pet /// -/// @param petId Pet id to delete +/// @param petId Pet id to delete /// -/// @param apiKey (optional) +/// @param apiKey (optional) /// -/// code:400 message:"Invalid pet value" --(NSNumber*) deletePetWithPetId: (NSNumber*) petId +/// @returns void +/// +-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'petId' is set @@ -185,12 +187,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// 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 (optional, default to available) +/// @param status Status values that need to be considered for filter (optional, default to available) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid status value" -/// @return NSArray* --(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status +/// @returns NSArray* +/// +-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; @@ -247,12 +248,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// 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 (optional) +/// @param tags Tags to filter by (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid tag value" -/// @return NSArray* --(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags +/// @returns NSArray* +/// +-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; @@ -309,13 +309,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions -/// @param petId ID of pet that needs to be fetched +/// @param petId ID of pet that needs to be fetched /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Pet not found" -/// @return SWGPet* --(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId +/// @returns SWGPet* +/// +-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler { // verify the required parameter 'petId' is set if (petId == nil) { @@ -382,12 +380,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Update an existing pet /// -/// @param body Pet object that needs to be added to the store (optional) +/// @param body Pet object that needs to be added to the store (optional) /// -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Pet not found", -/// code:405 message:"Validation exception" --(NSNumber*) updatePetWithBody: (SWGPet*) body +/// @returns void +/// +-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -441,14 +438,15 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Updates a pet in the store with form data /// -/// @param petId ID of pet that needs to be updated +/// @param petId ID of pet that needs to be updated /// -/// @param name Updated name of the pet (optional) +/// @param name Updated name of the pet (optional) /// -/// @param status Updated status of the pet (optional) +/// @param status Updated status of the pet (optional) /// -/// code:405 message:"Invalid input" --(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId +/// @returns void +/// +-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler { @@ -523,14 +521,15 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// uploads an image /// -/// @param petId ID of pet to update +/// @param petId ID of pet to update /// -/// @param additionalMetadata Additional data to pass to server (optional) +/// @param additionalMetadata Additional data to pass to server (optional) /// -/// @param file file to upload (optional) +/// @param file file to upload (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) uploadFileWithPetId: (NSNumber*) petId +/// @returns void +/// +-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler { @@ -601,4 +600,5 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; } + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h index c2cbc721198..6cfc765cd0b 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h @@ -27,39 +27,52 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode; /// 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 +/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId +/// +/// @return +-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler; + /// Returns pet inventories by status /// Returns a map of status codes to quantities /// +/// /// code:200 message:"successful operation" +/// /// @return NSDictionary* --(NSNumber*) getInventoryWithCompletionHandler: +-(NSURLSessionTask*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler; + /// 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 +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" +/// /// @return SWGOrder* --(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId +-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; + /// Place an order for a pet /// /// /// @param body order placed for purchasing the pet (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid Order" +/// /// @return SWGOrder* --(NSNumber*) placeOrderWithBody: (SWGOrder*) body +-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m index 09d04cc2f69..2a17173f83a 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m @@ -52,11 +52,11 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// 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 +/// @param orderId ID of the order that needs to be deleted /// -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Order not found" --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId +/// @returns void +/// +-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'orderId' is set if (orderId == nil) { @@ -123,9 +123,9 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// Returns pet inventories by status /// Returns a map of status codes to quantities -/// code:200 message:"successful operation" -/// @return NSDictionary* --(NSNumber*) getInventoryWithCompletionHandler: +/// @returns NSDictionary* +/// +-(NSURLSessionTask*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; @@ -178,13 +178,11 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// 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 +/// @param orderId ID of pet that needs to be fetched /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Order not found" -/// @return SWGOrder* --(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId +/// @returns SWGOrder* +/// +-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { // verify the required parameter 'orderId' is set if (orderId == nil) { @@ -251,12 +249,11 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// Place an order for a pet /// -/// @param body order placed for purchasing the pet (optional) +/// @param body order placed for purchasing the pet (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid Order" -/// @return SWGOrder* --(NSNumber*) placeOrderWithBody: (SWGOrder*) body +/// @returns SWGOrder* +/// +-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; @@ -308,4 +305,5 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; } + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h index 9d51cfc3d9a..9695c16918b 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h @@ -27,75 +27,105 @@ extern NSInteger kSWGUserApiMissingParamErrorCode; /// This can only be done by the logged in user. /// /// @param body Created user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUserWithBody: (SWGUser*) body +/// +/// @return +-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; + /// Creates list of users with given input array /// /// /// @param body List of user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body +/// +/// @return +-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; + /// Creates list of users with given input array /// /// /// @param body List of user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body +/// +/// @return +-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; + /// Delete user /// This can only be done by the logged in user. /// /// @param username The name that needs to be deleted +/// /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" --(NSNumber*) deleteUserWithUsername: (NSString*) username +/// +/// @return +-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler; + /// Get user by user name /// /// /// @param username The name that needs to be fetched. Use user1 for testing. +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" +/// /// @return SWGUser* --(NSNumber*) getUserByNameWithUsername: (NSString*) username +-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; + /// Logs user into the system /// /// /// @param username The user name for login (optional) /// @param password The password for login in clear text (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username/password supplied" +/// /// @return NSString* --(NSNumber*) loginUserWithUsername: (NSString*) username +-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler; + /// Logs out current logged in user session /// /// +/// /// code:0 message:"successful operation" --(NSNumber*) logoutUserWithCompletionHandler: +/// +/// @return +-(NSURLSessionTask*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler; + /// Updated user /// This can only be done by the logged in user. /// /// @param username name that need to be deleted /// @param body Updated user object (optional) +/// /// code:400 message:"Invalid user supplied", /// code:404 message:"User not found" --(NSNumber*) updateUserWithUsername: (NSString*) username +/// +/// @return +-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m index ddf4fbbbbd7..e1acf3af007 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m @@ -52,10 +52,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Create user /// This can only be done by the logged in user. -/// @param body Created user object (optional) +/// @param body Created user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUserWithBody: (SWGUser*) body +/// @returns void +/// +-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"]; @@ -109,10 +110,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) +/// @param body List of user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body +/// @returns void +/// +-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"]; @@ -166,10 +168,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) +/// @param body List of user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body +/// @returns void +/// +-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"]; @@ -223,11 +226,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Delete user /// This can only be done by the logged in user. -/// @param username The name that needs to be deleted +/// @param username The name that needs to be deleted /// -/// code:400 message:"Invalid username supplied", -/// code:404 message:"User not found" --(NSNumber*) deleteUserWithUsername: (NSString*) username +/// @returns void +/// +-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set if (username == nil) { @@ -294,13 +297,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Get user by user name /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid username supplied", -/// code:404 message:"User not found" -/// @return SWGUser* --(NSNumber*) getUserByNameWithUsername: (NSString*) username +/// @returns SWGUser* +/// +-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler { // verify the required parameter 'username' is set if (username == nil) { @@ -367,14 +368,13 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Logs user into the system /// -/// @param username The user name for login (optional) +/// @param username The user name for login (optional) /// -/// @param password The password for login in clear text (optional) +/// @param password The password for login in clear text (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid username/password supplied" -/// @return NSString* --(NSNumber*) loginUserWithUsername: (NSString*) username +/// @returns NSString* +/// +-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"]; @@ -434,8 +434,9 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Logs out current logged in user session /// -/// code:0 message:"successful operation" --(NSNumber*) logoutUserWithCompletionHandler: +/// @returns void +/// +-(NSURLSessionTask*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"]; @@ -488,13 +489,13 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Updated user /// This can only be done by the logged in user. -/// @param username name that need to be deleted +/// @param username name that need to be deleted /// -/// @param body Updated user object (optional) +/// @param body Updated user object (optional) /// -/// code:400 message:"Invalid user supplied", -/// code:404 message:"User not found" --(NSNumber*) updateUserWithUsername: (NSString*) username +/// @returns void +/// +-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set @@ -561,4 +562,5 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; } + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h index 417344d77f8..099fb88c335 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h @@ -34,14 +34,6 @@ extern NSString *const SWGResponseObjectErrorKey; @property(nonatomic, strong) id sanitizer; -@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer *>* requestSerializerForContentType; - -/** - * Gets client singleton instance - */ -+ (instancetype) sharedClient; - - /** * Gets if the client is unreachable * @@ -63,29 +55,16 @@ extern NSString *const SWGResponseObjectErrorKey; */ +(AFNetworkReachabilityStatus) getReachabilityStatus; -/** - * Gets the next request id - * - * @return The next executed request id. - */ -+(NSNumber*) nextRequestId; +@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer *>* requestSerializerForContentType; /** - * Generates request id and add it to the queue - * - * @return The next executed request id. + * Gets client singleton instance */ -+(NSNumber*) queueRequest; ++ (instancetype) sharedClient; + /** - * Removes request id from the queue - * - * @param requestId The request which will be removed. - */ -+(void) cancelRequest:(NSNumber*)requestId; - -/** - * Customizes the behavior when the reachability changed + * Updates header parameters and query parameters for authentication * * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. @@ -100,7 +79,15 @@ extern NSString *const SWGResponseObjectErrorKey; * @param configuration The configuration implementation */ - (instancetype)initWithConfiguration:(id)configuration; - + +/** +* Initializes the session manager with a configuration and url +* +* @param url The base url +* @param configuration The configuration implementation +*/ +- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id)configuration; + /** * Performs request * diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.m index 16fabe93089..f757e139d0e 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.m @@ -80,6 +80,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { @"application/x-www-form-urlencoded": afhttpRequestSerializer, @"multipart/form-data": afhttpRequestSerializer }; + self.securityPolicy = [self createSecurityPolicy]; self.responseSerializer = [AFHTTPResponseSerializer serializer]; } return self; @@ -351,4 +352,25 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } +- (AFSecurityPolicy *) createSecurityPolicy { + AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + + id config = self.configuration; + + if (config.sslCaCert) { + NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; + [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]]; + } + + if (config.verifySSL) { + [securityPolicy setAllowInvalidCertificates:NO]; + } + else { + [securityPolicy setAllowInvalidCertificates:YES]; + [securityPolicy setValidatesDomainName:NO]; + } + + return securityPolicy; +} + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.h b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.h index 24a5cfdf59f..195b8192494 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.h @@ -64,6 +64,18 @@ static NSString * const kSWGAPIVersion = @"1.0.0"; */ @property (readonly, nonatomic) BOOL debug; +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (readonly, nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (readonly, nonatomic) NSString *sslCaCert; + /** * Authentication Settings */ @@ -74,4 +86,4 @@ static NSString * const kSWGAPIVersion = @"1.0.0"; */ @property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; -@end \ No newline at end of file +@end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGDefaultConfiguration.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGDefaultConfiguration.m index 6c274bce81a..4afe43359aa 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGDefaultConfiguration.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGDefaultConfiguration.m @@ -32,6 +32,7 @@ _username = @""; _password = @""; _accessToken= @""; + _verifySSL = YES; _mutableApiKey = [NSMutableDictionary dictionary]; _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; _mutableDefaultHeaders = [NSMutableDictionary dictionary]; diff --git a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 2c63354b73d..6a4b5ec1f8d 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -391,7 +391,7 @@ ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -436,7 +436,7 @@ ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -466,7 +466,22 @@ ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + E337D7E459CCFFDF27046FFC /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; diff --git a/samples/client/petstore/objc/default/SwaggerClient.podspec b/samples/client/petstore/objc/default/SwaggerClient.podspec index 2587bd3375a..e43cdfd5a09 100644 --- a/samples/client/petstore/objc/default/SwaggerClient.podspec +++ b/samples/client/petstore/objc/default/SwaggerClient.podspec @@ -30,8 +30,8 @@ Pod::Spec.new do |s| s.public_header_files = 'SwaggerClient/**/*.h' - s.dependency 'AFNetworking', '~> 3.1' - s.dependency 'JSONModel', '~> 1.4' + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' s.dependency 'ISO8601', '~> 0.6' end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h index 1c89bd5c5a3..74ba6e6b482 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h @@ -27,84 +27,113 @@ extern NSInteger kSWGPetApiMissingParamErrorCode; /// /// /// @param body Pet object that needs to be added to the store (optional) +/// /// code:405 message:"Invalid input" --(NSNumber*) addPetWithBody: (SWGPet*) body +/// +/// @return +-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; + /// Deletes a pet /// /// /// @param petId Pet id to delete /// @param apiKey (optional) +/// /// code:400 message:"Invalid pet value" --(NSNumber*) deletePetWithPetId: (NSNumber*) petId +/// +/// @return +-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler; + /// 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 (optional) (default to available) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid status value" +/// /// @return NSArray* --(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status +-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; + /// 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 (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid tag value" +/// /// @return NSArray* --(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags +-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; + /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// @param petId ID of pet that needs to be fetched +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found" +/// /// @return SWGPet* --(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId +-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler; + /// Update an existing pet /// /// /// @param body Pet object that needs to be added to the store (optional) +/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found", /// code:405 message:"Validation exception" --(NSNumber*) updatePetWithBody: (SWGPet*) body +/// +/// @return +-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; + /// 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) +/// /// code:405 message:"Invalid input" --(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId +/// +/// @return +-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler; + /// 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) +/// /// code:0 message:"successful operation" --(NSNumber*) uploadFileWithPetId: (NSNumber*) petId +/// +/// @return +-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m index 0d0a55f2688..c0ca97c3480 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m @@ -52,10 +52,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Add a new pet to the store /// -/// @param body Pet object that needs to be added to the store (optional) +/// @param body Pet object that needs to be added to the store (optional) /// -/// code:405 message:"Invalid input" --(NSNumber*) addPetWithBody: (SWGPet*) body +/// @returns void +/// +-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -109,12 +110,13 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Deletes a pet /// -/// @param petId Pet id to delete +/// @param petId Pet id to delete /// -/// @param apiKey (optional) +/// @param apiKey (optional) /// -/// code:400 message:"Invalid pet value" --(NSNumber*) deletePetWithPetId: (NSNumber*) petId +/// @returns void +/// +-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'petId' is set @@ -185,12 +187,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// 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 (optional, default to available) +/// @param status Status values that need to be considered for filter (optional, default to available) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid status value" -/// @return NSArray* --(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status +/// @returns NSArray* +/// +-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; @@ -247,12 +248,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// 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 (optional) +/// @param tags Tags to filter by (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid tag value" -/// @return NSArray* --(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags +/// @returns NSArray* +/// +-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; @@ -309,13 +309,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions -/// @param petId ID of pet that needs to be fetched +/// @param petId ID of pet that needs to be fetched /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Pet not found" -/// @return SWGPet* --(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId +/// @returns SWGPet* +/// +-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler { // verify the required parameter 'petId' is set if (petId == nil) { @@ -382,12 +380,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Update an existing pet /// -/// @param body Pet object that needs to be added to the store (optional) +/// @param body Pet object that needs to be added to the store (optional) /// -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Pet not found", -/// code:405 message:"Validation exception" --(NSNumber*) updatePetWithBody: (SWGPet*) body +/// @returns void +/// +-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -441,14 +438,15 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Updates a pet in the store with form data /// -/// @param petId ID of pet that needs to be updated +/// @param petId ID of pet that needs to be updated /// -/// @param name Updated name of the pet (optional) +/// @param name Updated name of the pet (optional) /// -/// @param status Updated status of the pet (optional) +/// @param status Updated status of the pet (optional) /// -/// code:405 message:"Invalid input" --(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId +/// @returns void +/// +-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler { @@ -523,14 +521,15 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// uploads an image /// -/// @param petId ID of pet to update +/// @param petId ID of pet to update /// -/// @param additionalMetadata Additional data to pass to server (optional) +/// @param additionalMetadata Additional data to pass to server (optional) /// -/// @param file file to upload (optional) +/// @param file file to upload (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) uploadFileWithPetId: (NSNumber*) petId +/// @returns void +/// +-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler { @@ -601,4 +600,5 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; } + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h index c2cbc721198..6cfc765cd0b 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h @@ -27,39 +27,52 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode; /// 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 +/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId +/// +/// @return +-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler; + /// Returns pet inventories by status /// Returns a map of status codes to quantities /// +/// /// code:200 message:"successful operation" +/// /// @return NSDictionary* --(NSNumber*) getInventoryWithCompletionHandler: +-(NSURLSessionTask*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler; + /// 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 +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" +/// /// @return SWGOrder* --(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId +-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; + /// Place an order for a pet /// /// /// @param body order placed for purchasing the pet (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid Order" +/// /// @return SWGOrder* --(NSNumber*) placeOrderWithBody: (SWGOrder*) body +-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m index 09d04cc2f69..2a17173f83a 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m @@ -52,11 +52,11 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// 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 +/// @param orderId ID of the order that needs to be deleted /// -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Order not found" --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId +/// @returns void +/// +-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'orderId' is set if (orderId == nil) { @@ -123,9 +123,9 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// Returns pet inventories by status /// Returns a map of status codes to quantities -/// code:200 message:"successful operation" -/// @return NSDictionary* --(NSNumber*) getInventoryWithCompletionHandler: +/// @returns NSDictionary* +/// +-(NSURLSessionTask*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; @@ -178,13 +178,11 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// 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 +/// @param orderId ID of pet that needs to be fetched /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Order not found" -/// @return SWGOrder* --(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId +/// @returns SWGOrder* +/// +-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { // verify the required parameter 'orderId' is set if (orderId == nil) { @@ -251,12 +249,11 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// Place an order for a pet /// -/// @param body order placed for purchasing the pet (optional) +/// @param body order placed for purchasing the pet (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid Order" -/// @return SWGOrder* --(NSNumber*) placeOrderWithBody: (SWGOrder*) body +/// @returns SWGOrder* +/// +-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; @@ -308,4 +305,5 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; } + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h index 9d51cfc3d9a..9695c16918b 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h @@ -27,75 +27,105 @@ extern NSInteger kSWGUserApiMissingParamErrorCode; /// This can only be done by the logged in user. /// /// @param body Created user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUserWithBody: (SWGUser*) body +/// +/// @return +-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; + /// Creates list of users with given input array /// /// /// @param body List of user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body +/// +/// @return +-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; + /// Creates list of users with given input array /// /// /// @param body List of user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body +/// +/// @return +-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; + /// Delete user /// This can only be done by the logged in user. /// /// @param username The name that needs to be deleted +/// /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" --(NSNumber*) deleteUserWithUsername: (NSString*) username +/// +/// @return +-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler; + /// Get user by user name /// /// /// @param username The name that needs to be fetched. Use user1 for testing. +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" +/// /// @return SWGUser* --(NSNumber*) getUserByNameWithUsername: (NSString*) username +-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; + /// Logs user into the system /// /// /// @param username The user name for login (optional) /// @param password The password for login in clear text (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username/password supplied" +/// /// @return NSString* --(NSNumber*) loginUserWithUsername: (NSString*) username +-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler; + /// Logs out current logged in user session /// /// +/// /// code:0 message:"successful operation" --(NSNumber*) logoutUserWithCompletionHandler: +/// +/// @return +-(NSURLSessionTask*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler; + /// Updated user /// This can only be done by the logged in user. /// /// @param username name that need to be deleted /// @param body Updated user object (optional) +/// /// code:400 message:"Invalid user supplied", /// code:404 message:"User not found" --(NSNumber*) updateUserWithUsername: (NSString*) username +/// +/// @return +-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m index ddf4fbbbbd7..e1acf3af007 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m @@ -52,10 +52,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Create user /// This can only be done by the logged in user. -/// @param body Created user object (optional) +/// @param body Created user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUserWithBody: (SWGUser*) body +/// @returns void +/// +-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"]; @@ -109,10 +110,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) +/// @param body List of user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body +/// @returns void +/// +-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"]; @@ -166,10 +168,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) +/// @param body List of user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body +/// @returns void +/// +-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"]; @@ -223,11 +226,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Delete user /// This can only be done by the logged in user. -/// @param username The name that needs to be deleted +/// @param username The name that needs to be deleted /// -/// code:400 message:"Invalid username supplied", -/// code:404 message:"User not found" --(NSNumber*) deleteUserWithUsername: (NSString*) username +/// @returns void +/// +-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set if (username == nil) { @@ -294,13 +297,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Get user by user name /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid username supplied", -/// code:404 message:"User not found" -/// @return SWGUser* --(NSNumber*) getUserByNameWithUsername: (NSString*) username +/// @returns SWGUser* +/// +-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler { // verify the required parameter 'username' is set if (username == nil) { @@ -367,14 +368,13 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Logs user into the system /// -/// @param username The user name for login (optional) +/// @param username The user name for login (optional) /// -/// @param password The password for login in clear text (optional) +/// @param password The password for login in clear text (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid username/password supplied" -/// @return NSString* --(NSNumber*) loginUserWithUsername: (NSString*) username +/// @returns NSString* +/// +-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"]; @@ -434,8 +434,9 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Logs out current logged in user session /// -/// code:0 message:"successful operation" --(NSNumber*) logoutUserWithCompletionHandler: +/// @returns void +/// +-(NSURLSessionTask*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"]; @@ -488,13 +489,13 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Updated user /// This can only be done by the logged in user. -/// @param username name that need to be deleted +/// @param username name that need to be deleted /// -/// @param body Updated user object (optional) +/// @param body Updated user object (optional) /// -/// code:400 message:"Invalid user supplied", -/// code:404 message:"User not found" --(NSNumber*) updateUserWithUsername: (NSString*) username +/// @returns void +/// +-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set @@ -561,4 +562,5 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; } + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h index 417344d77f8..099fb88c335 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h @@ -34,14 +34,6 @@ extern NSString *const SWGResponseObjectErrorKey; @property(nonatomic, strong) id sanitizer; -@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer *>* requestSerializerForContentType; - -/** - * Gets client singleton instance - */ -+ (instancetype) sharedClient; - - /** * Gets if the client is unreachable * @@ -63,29 +55,16 @@ extern NSString *const SWGResponseObjectErrorKey; */ +(AFNetworkReachabilityStatus) getReachabilityStatus; -/** - * Gets the next request id - * - * @return The next executed request id. - */ -+(NSNumber*) nextRequestId; +@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer *>* requestSerializerForContentType; /** - * Generates request id and add it to the queue - * - * @return The next executed request id. + * Gets client singleton instance */ -+(NSNumber*) queueRequest; ++ (instancetype) sharedClient; + /** - * Removes request id from the queue - * - * @param requestId The request which will be removed. - */ -+(void) cancelRequest:(NSNumber*)requestId; - -/** - * Customizes the behavior when the reachability changed + * Updates header parameters and query parameters for authentication * * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. @@ -100,7 +79,15 @@ extern NSString *const SWGResponseObjectErrorKey; * @param configuration The configuration implementation */ - (instancetype)initWithConfiguration:(id)configuration; - + +/** +* Initializes the session manager with a configuration and url +* +* @param url The base url +* @param configuration The configuration implementation +*/ +- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id)configuration; + /** * Performs request * diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m index 16fabe93089..f757e139d0e 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m @@ -80,6 +80,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { @"application/x-www-form-urlencoded": afhttpRequestSerializer, @"multipart/form-data": afhttpRequestSerializer }; + self.securityPolicy = [self createSecurityPolicy]; self.responseSerializer = [AFHTTPResponseSerializer serializer]; } return self; @@ -351,4 +352,25 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } +- (AFSecurityPolicy *) createSecurityPolicy { + AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + + id config = self.configuration; + + if (config.sslCaCert) { + NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; + [securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]]; + } + + if (config.verifySSL) { + [securityPolicy setAllowInvalidCertificates:NO]; + } + else { + [securityPolicy setAllowInvalidCertificates:YES]; + [securityPolicy setValidatesDomainName:NO]; + } + + return securityPolicy; +} + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h index 24a5cfdf59f..195b8192494 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h @@ -64,6 +64,18 @@ static NSString * const kSWGAPIVersion = @"1.0.0"; */ @property (readonly, nonatomic) BOOL debug; +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (readonly, nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (readonly, nonatomic) NSString *sslCaCert; + /** * Authentication Settings */ @@ -74,4 +86,4 @@ static NSString * const kSWGAPIVersion = @"1.0.0"; */ @property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; -@end \ No newline at end of file +@end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGDefaultConfiguration.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGDefaultConfiguration.m index 6c274bce81a..4afe43359aa 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGDefaultConfiguration.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGDefaultConfiguration.m @@ -32,6 +32,7 @@ _username = @""; _password = @""; _accessToken= @""; + _verifySSL = YES; _mutableApiKey = [NSMutableDictionary dictionary]; _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; _mutableDefaultHeaders = [NSMutableDictionary dictionary]; diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index 8fff4f574d8..1fd5b85a80b 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -10,48 +10,47 @@ Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/ - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-11-16T17:12:17.554+08:00 -- Build package: class io.swagger.codegen.languages.PerlClientCodegen +- Build package: io.swagger.codegen.languages.PerlClientCodegen ## A note on Moose -This role is the only component of the library that uses Moose. See -WWW::SwaggerClient::ApiFactory for non-Moosey usage. +This role is the only component of the library that uses Moose. See +WWW::SwaggerClient::ApiFactory for non-Moosey usage. # SYNOPSIS -The Perl Swagger Codegen project builds a library of Perl modules to interact with -a web service defined by a OpenAPI Specification. See below for how to build the +The Perl Swagger Codegen project builds a library of Perl modules to interact with +a web service defined by a OpenAPI Specification. See below for how to build the library. -This module provides an interface to the generated library. All the classes, -objects, and methods (well, not quite \*all\*, see below) are flattened into this -role. +This module provides an interface to the generated library. All the classes, +objects, and methods (well, not quite \*all\*, see below) are flattened into this +role. package MyApp; use Moose; with 'WWW::SwaggerClient::Role'; - + package main; - + my $api = MyApp->new({ tokens => $tokens }); - + my $pet = $api->get_pet_by_id(pet_id => $pet_id); - + ## Structure of the library The library consists of a set of API classes, one for each endpoint. These APIs -implement the method calls available on each endpoint. +implement the method calls available on each endpoint. -Additionally, there is a set of "object" classes, which represent the objects -returned by and sent to the methods on the endpoints. +Additionally, there is a set of "object" classes, which represent the objects +returned by and sent to the methods on the endpoints. -An API factory class is provided, which builds instances of each endpoint API. +An API factory class is provided, which builds instances of each endpoint API. -This Moose role flattens all the methods from the endpoint APIs onto the consuming -class. It also provides methods to retrieve the endpoint API objects, and the API -factory object, should you need it. +This Moose role flattens all the methods from the endpoint APIs onto the consuming +class. It also provides methods to retrieve the endpoint API objects, and the API +factory object, should you need it. For documentation of all these methods, see AUTOMATIC DOCUMENTATION below. @@ -64,33 +63,33 @@ required and where to put them. You just need to supply the tokens. # basic username => $username, password => $password, - + # oauth access_token => $oauth_token, - + # keys $some_key => { token => $token, - prefix => $prefix, - in => $in, # 'head||query', + prefix => $prefix, + in => $in, # 'head||query', }, - + $another => { token => $token, - prefix => $prefix, - in => $in, # 'head||query', - }, + prefix => $prefix, + in => $in, # 'head||query', + }, ..., - + }; - + my $api = MyApp->new({ tokens => $tokens }); Note these are all optional, as are `prefix` and `in`, and depend on the API you are accessing. Usually `prefix` and `in` will be determined by the code generator from the spec and you will not need to set them at run time. If not, `in` will -default to 'head' and `prefix` to the empty string. +default to 'head' and `prefix` to the empty string. The tokens will be placed in the `WWW::SwaggerClient::Configuration` namespace -as follows, but you don't need to know about this. +as follows, but you don't need to know about this. - `$WWW::SwaggerClient::Configuration::username` @@ -121,22 +120,22 @@ as follows, but you don't need to know about this. - `$WWW::SwaggerClient::Configuration::access_token` - String. The OAuth access token. + String. The OAuth access token. # METHODS ## `base_url` -The generated code has the `base_url` already set as a default value. This method -returns (and optionally sets, but only if the API client has not been +The generated code has the `base_url` already set as a default value. This method +returns (and optionally sets, but only if the API client has not been created yet) the current value of `base_url`. ## `api_factory` -Returns an API factory object. You probably won't need to call this directly. +Returns an API factory object. You probably won't need to call this directly. $self->api_factory('Pet'); # returns a WWW::SwaggerClient::PetApi instance - + $self->pet_api; # the same # MISSING METHODS @@ -146,9 +145,9 @@ Most of the methods on the API are delegated to individual endpoint API objects same method name (e.g. `new()`), these methods can't be delegated. So you need to call `$api->pet_api->new()`. -In principle, every API is susceptible to the presence of a few, random, undelegatable -method names. In practice, because of the way method names are constructed, it's -unlikely in general that any methods will be undelegatable, except for: +In principle, every API is susceptible to the presence of a few, random, undelegatable +method names. In practice, because of the way method names are constructed, it's +unlikely in general that any methods will be undelegatable, except for: new() class_documentation() @@ -161,12 +160,12 @@ you could also call them on class names. # BUILDING YOUR LIBRARY -See the homepage `https://github.com/swagger-api/swagger-codegen` for full details. -But briefly, clone the git repository, build the codegen codebase, set up your build +See the homepage `https://github.com/swagger-api/swagger-codegen` for full details. +But briefly, clone the git repository, build the codegen codebase, set up your build config file, then run the API build script. You will need git, Java 7 or 8 and Apache maven 3.0.3 or better already installed. -The config file should specify the project name for the generated library: +The config file should specify the project name for the generated library: {"moduleName":"WWW::MyProjectName"} @@ -181,8 +180,8 @@ Your library files will be built under `WWW::MyProjectName`. -c /path/to/config/file.json \ -o /path/to/output/folder -Bang, all done. Run the `autodoc` script in the `bin` directory to see the API -you just built. +Bang, all done. Run the `autodoc` script in the `bin` directory to see the API +you just built. # AUTOMATIC DOCUMENTATION @@ -194,28 +193,28 @@ output formats are supported: -w wide format (default) -n narrow format - -p POD format - -H HTML format + -p POD format + -H HTML format -m Markdown format -h print this help message -c your application class - + The `-c` option allows you to load and inspect your own application. A dummy namespace is used if you don't supply your own class. # DOCUMENTATION FROM THE OpenAPI Spec -Additional documentation for each class and method may be provided by the Swagger -spec. If so, this is available via the `class_documentation()` and -`method_documentation()` methods on each generated object class, and the -`method_documentation()` method on the endpoint API classes: +Additional documentation for each class and method may be provided by the Swagger +spec. If so, this is available via the `class_documentation()` and +`method_documentation()` methods on each generated object class, and the +`method_documentation()` method on the endpoint API classes: + + my $cmdoc = $api->pet_api->method_documentation->{$method_name}; + + my $odoc = $api->get_pet_by_id->(pet_id => $pet_id)->class_documentation; + my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; - my $cmdoc = $api->pet_api->method_documentation->{$method_name}; - - my $odoc = $api->get_pet_by_id->(pet_id => $pet_id)->class_documentation; - my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; - Each of these calls returns a hashref with various useful pieces of information. @@ -239,8 +238,10 @@ use WWW::SwaggerClient::Object::ApiResponse; use WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayTest; +use WWW::SwaggerClient::Object::Capitalization; use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; +use WWW::SwaggerClient::Object::ClassModel; use WWW::SwaggerClient::Object::Client; use WWW::SwaggerClient::Object::Dog; use WWW::SwaggerClient::Object::EnumArrays; @@ -256,6 +257,7 @@ use WWW::SwaggerClient::Object::ModelReturn; use WWW::SwaggerClient::Object::Name; use WWW::SwaggerClient::Object::NumberOnly; use WWW::SwaggerClient::Object::Order; +use WWW::SwaggerClient::Object::OuterEnum; use WWW::SwaggerClient::Object::Pet; use WWW::SwaggerClient::Object::ReadOnlyFirst; use WWW::SwaggerClient::Object::SpecialModelName; @@ -285,8 +287,10 @@ use WWW::SwaggerClient::Object::ApiResponse; use WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayOfNumberOnly; use WWW::SwaggerClient::Object::ArrayTest; +use WWW::SwaggerClient::Object::Capitalization; use WWW::SwaggerClient::Object::Cat; use WWW::SwaggerClient::Object::Category; +use WWW::SwaggerClient::Object::ClassModel; use WWW::SwaggerClient::Object::Client; use WWW::SwaggerClient::Object::Dog; use WWW::SwaggerClient::Object::EnumArrays; @@ -302,6 +306,7 @@ use WWW::SwaggerClient::Object::ModelReturn; use WWW::SwaggerClient::Object::Name; use WWW::SwaggerClient::Object::NumberOnly; use WWW::SwaggerClient::Object::Order; +use WWW::SwaggerClient::Object::OuterEnum; use WWW::SwaggerClient::Object::Pet; use WWW::SwaggerClient::Object::ReadOnlyFirst; use WWW::SwaggerClient::Object::SpecialModelName; @@ -365,8 +370,10 @@ Class | Method | HTTP request | Description - [WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [WWW::SwaggerClient::Object::ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [WWW::SwaggerClient::Object::ArrayTest](docs/ArrayTest.md) + - [WWW::SwaggerClient::Object::Capitalization](docs/Capitalization.md) - [WWW::SwaggerClient::Object::Cat](docs/Cat.md) - [WWW::SwaggerClient::Object::Category](docs/Category.md) + - [WWW::SwaggerClient::Object::ClassModel](docs/ClassModel.md) - [WWW::SwaggerClient::Object::Client](docs/Client.md) - [WWW::SwaggerClient::Object::Dog](docs/Dog.md) - [WWW::SwaggerClient::Object::EnumArrays](docs/EnumArrays.md) @@ -382,6 +389,7 @@ Class | Method | HTTP request | Description - [WWW::SwaggerClient::Object::Name](docs/Name.md) - [WWW::SwaggerClient::Object::NumberOnly](docs/NumberOnly.md) - [WWW::SwaggerClient::Object::Order](docs/Order.md) + - [WWW::SwaggerClient::Object::OuterEnum](docs/OuterEnum.md) - [WWW::SwaggerClient::Object::Pet](docs/Pet.md) - [WWW::SwaggerClient::Object::ReadOnlyFirst](docs/ReadOnlyFirst.md) - [WWW::SwaggerClient::Object::SpecialModelName](docs/SpecialModelName.md) @@ -393,7 +401,7 @@ Class | Method | HTTP request | Description ## api_key -- **Type**: API key +- **Type**: API key - **API key parameter name**: api_key - **Location**: HTTP header @@ -410,5 +418,3 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets - - diff --git a/samples/client/petstore/perl/docs/Capitalization.md b/samples/client/petstore/perl/docs/Capitalization.md new file mode 100644 index 00000000000..c63257baa52 --- /dev/null +++ b/samples/client/petstore/perl/docs/Capitalization.md @@ -0,0 +1,20 @@ +# WWW::SwaggerClient::Object::Capitalization + +## Load the model package +```perl +use WWW::SwaggerClient::Object::Capitalization; +``` + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**small_camel** | **string** | | [optional] +**capital_camel** | **string** | | [optional] +**small_snake** | **string** | | [optional] +**capital_snake** | **string** | | [optional] +**sca_eth_flow_points** | **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/perl/docs/ClassModel.md b/samples/client/petstore/perl/docs/ClassModel.md new file mode 100644 index 00000000000..95d325176df --- /dev/null +++ b/samples/client/petstore/perl/docs/ClassModel.md @@ -0,0 +1,15 @@ +# WWW::SwaggerClient::Object::ClassModel + +## Load the model package +```perl +use WWW::SwaggerClient::Object::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/perl/docs/EnumTest.md b/samples/client/petstore/perl/docs/EnumTest.md index 0c3416150e1..07cc4d9ebce 100644 --- a/samples/client/petstore/perl/docs/EnumTest.md +++ b/samples/client/petstore/perl/docs/EnumTest.md @@ -11,6 +11,7 @@ Name | Type | Description | Notes **enum_string** | **string** | | [optional] **enum_integer** | **int** | | [optional] **enum_number** | **double** | | [optional] +**outer_enum** | [**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/perl/docs/FakeApi.md b/samples/client/petstore/perl/docs/FakeApi.md index c070d1a2059..642f8fd1fe8 100644 --- a/samples/client/petstore/perl/docs/FakeApi.md +++ b/samples/client/petstore/perl/docs/FakeApi.md @@ -19,6 +19,8 @@ Method | HTTP request | Description To test \"client\" model +To test \"client\" model + ### Example ```perl use Data::Dumper; @@ -138,6 +140,8 @@ void (empty response body) To test enum parameters +To test enum parameters + ### Example ```perl use Data::Dumper; @@ -151,7 +155,7 @@ my $enum_header_string_array = []; # ARRAY[string] | Header parameter enum test my $enum_header_string = 'enum_header_string_example'; # string | Header parameter enum test (string) my $enum_query_string_array = []; # ARRAY[string] | Query parameter enum test (string array) my $enum_query_string = 'enum_query_string_example'; # string | Query parameter enum test (string) -my $enum_query_integer = 3.4; # Number | Query parameter enum test (double) +my $enum_query_integer = 56; # int | Query parameter enum test (double) my $enum_query_double = 1.2; # double | Query parameter enum test (double) eval { @@ -172,7 +176,7 @@ Name | Type | Description | Notes **enum_header_string** | **string**| Header parameter enum test (string) | [optional] [default to -efg] **enum_query_string_array** | [**ARRAY[string]**](string.md)| Query parameter enum test (string array) | [optional] **enum_query_string** | **string**| Query parameter enum test (string) | [optional] [default to -efg] - **enum_query_integer** | **Number**| Query parameter enum test (double) | [optional] + **enum_query_integer** | **int**| Query parameter enum test (double) | [optional] **enum_query_double** | **double**| Query parameter enum test (double) | [optional] ### Return type diff --git a/samples/client/petstore/perl/docs/OuterEnum.md b/samples/client/petstore/perl/docs/OuterEnum.md new file mode 100644 index 00000000000..7d0056d6522 --- /dev/null +++ b/samples/client/petstore/perl/docs/OuterEnum.md @@ -0,0 +1,14 @@ +# WWW::SwaggerClient::Object::OuterEnum + +## Load the model package +```perl +use WWW::SwaggerClient::Object::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/perl/lib/WWW/SwaggerClient/FakeApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm index 32267333ba4..ebb8bb5b86e 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/FakeApi.pm @@ -348,7 +348,7 @@ sub test_endpoint_parameters { # @param string $enum_header_string Header parameter enum test (string) (optional, default to -efg) # @param ARRAY[string] $enum_query_string_array Query parameter enum test (string array) (optional) # @param string $enum_query_string Query parameter enum test (string) (optional, default to -efg) -# @param Number $enum_query_integer Query parameter enum test (double) (optional) +# @param int $enum_query_integer Query parameter enum test (double) (optional) # @param double $enum_query_double Query parameter enum test (double) (optional) { my $params = { @@ -383,7 +383,7 @@ sub test_endpoint_parameters { required => '0', }, 'enum_query_integer' => { - data_type => 'Number', + data_type => 'int', description => 'Query parameter enum test (double)', required => '0', }, diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Capitalization.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Capitalization.pm new file mode 100644 index 00000000000..a1eb4353d3d --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Capitalization.pm @@ -0,0 +1,210 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::Capitalization; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'Capitalization', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + 'small_camel' => { + datatype => 'string', + base_name => 'smallCamel', + description => '', + format => '', + read_only => '', + }, + 'capital_camel' => { + datatype => 'string', + base_name => 'CapitalCamel', + description => '', + format => '', + read_only => '', + }, + 'small_snake' => { + datatype => 'string', + base_name => 'small_Snake', + description => '', + format => '', + read_only => '', + }, + 'capital_snake' => { + datatype => 'string', + base_name => 'Capital_Snake', + description => '', + format => '', + read_only => '', + }, + 'sca_eth_flow_points' => { + datatype => 'string', + base_name => 'SCA_ETH_Flow_Points', + description => '', + format => '', + read_only => '', + }, + 'att_name' => { + datatype => 'string', + base_name => 'ATT_NAME', + description => 'Name of the pet ', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + 'small_camel' => 'string', + 'capital_camel' => 'string', + 'small_snake' => 'string', + 'capital_snake' => 'string', + 'sca_eth_flow_points' => 'string', + 'att_name' => 'string' +} ); + +__PACKAGE__->attribute_map( { + 'small_camel' => 'smallCamel', + 'capital_camel' => 'CapitalCamel', + 'small_snake' => 'small_Snake', + 'capital_snake' => 'Capital_Snake', + 'sca_eth_flow_points' => 'SCA_ETH_Flow_Points', + 'att_name' => 'ATT_NAME' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ClassModel.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ClassModel.pm new file mode 100644 index 00000000000..90634705247 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/ClassModel.pm @@ -0,0 +1,165 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::ClassModel; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +#Model for testing model with \"_class\" property +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => 'Model for testing model with \"_class\" property', + class => 'ClassModel', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ + '_class' => { + datatype => 'string', + base_name => '_class', + description => '', + format => '', + read_only => '', + }, +}); + +__PACKAGE__->swagger_types( { + '_class' => 'string' +} ); + +__PACKAGE__->attribute_map( { + '_class' => '_class' +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm index b5d7d2f7798..6b5f9317c4d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/EnumTest.pm @@ -163,18 +163,27 @@ __PACKAGE__->method_documentation({ format => '', read_only => '', }, + 'outer_enum' => { + datatype => 'OuterEnum', + base_name => 'outerEnum', + description => '', + format => '', + read_only => '', + }, }); __PACKAGE__->swagger_types( { 'enum_string' => 'string', 'enum_integer' => 'int', - 'enum_number' => 'double' + 'enum_number' => 'double', + 'outer_enum' => 'OuterEnum' } ); __PACKAGE__->attribute_map( { 'enum_string' => 'enum_string', 'enum_integer' => 'enum_integer', - 'enum_number' => 'enum_number' + 'enum_number' => 'enum_number', + 'outer_enum' => 'outerEnum' } ); __PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/OuterEnum.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/OuterEnum.pm new file mode 100644 index 00000000000..344b4624d82 --- /dev/null +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/OuterEnum.pm @@ -0,0 +1,158 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +package WWW::SwaggerClient::Object::OuterEnum; + +require 5.6.0; +use strict; +use warnings; +use utf8; +use JSON qw(decode_json); +use Data::Dumper; +use Module::Runtime qw(use_module); +use Log::Any qw($log); +use Date::Parse; +use DateTime; + +use base ("Class::Accessor", "Class::Data::Inheritable"); + + +# +# +# +# NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +# REF: https://github.com/swagger-api/swagger-codegen +# + +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the swagger code generator program. +# Do not edit the class manually. +# Ref: https://github.com/swagger-api/swagger-codegen +# +__PACKAGE__->mk_classdata('attribute_map' => {}); +__PACKAGE__->mk_classdata('swagger_types' => {}); +__PACKAGE__->mk_classdata('method_documentation' => {}); +__PACKAGE__->mk_classdata('class_documentation' => {}); + +# new object +sub new { + my ($class, %args) = @_; + + my $self = bless {}, $class; + + foreach my $attribute (keys %{$class->attribute_map}) { + my $args_key = $class->attribute_map->{$attribute}; + $self->$attribute( $args{ $args_key } ); + } + + return $self; +} + +# return perl hash +sub to_hash { + return decode_json(JSON->new->convert_blessed->encode( shift )); +} + +# used by JSON for serialization +sub TO_JSON { + my $self = shift; + my $_data = {}; + foreach my $_key (keys %{$self->attribute_map}) { + if (defined $self->{$_key}) { + $_data->{$self->attribute_map->{$_key}} = $self->{$_key}; + } + } + return $_data; +} + +# from Perl hashref +sub from_hash { + my ($self, $hash) = @_; + + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each %{$self->swagger_types} ) { + my $_json_attribute = $self->attribute_map->{$_key}; + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$_json_attribute}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (exists $hash->{$_json_attribute}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_json_attribute}); + } else { + $log->debugf("Warning: %s (%s) does not exist in input hash\n", $_key, $_json_attribute); + } + } + + return $self; +} + +# deserialize non-array data +sub _deserialize { + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } +} + + + +__PACKAGE__->class_documentation({description => '', + class => 'OuterEnum', + required => [], # TODO +} ); + +__PACKAGE__->method_documentation({ +}); + +__PACKAGE__->swagger_types( { + +} ); + +__PACKAGE__->attribute_map( { + +} ); + +__PACKAGE__->mk_accessors(keys %{__PACKAGE__->attribute_map}); + + +1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm index f77724eee88..c1d15a27176 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm @@ -13,7 +13,7 @@ Generated by: https://github.com/swagger-api/swagger-codegen.git =cut # -# NOTE: This class is auto generated by the swagger code generator program. +# NOTE: This class is auto generated by the swagger code generator program. # Do not edit the class manually. # Ref: https://github.com/swagger-api/swagger-codegen # @@ -34,7 +34,7 @@ has base_url => ( is => 'ro', has api_factory => ( is => 'ro', isa => 'WWW::SwaggerClient::ApiFactory', - builder => '_build_af', + builder => '_build_af', lazy => 1, documentation => 'Builds an instance of the endpoint API class', ); @@ -51,49 +51,48 @@ has _cfg => ( is => 'ro', default => 'WWW::SwaggerClient::Configuration', ); -has version_info => ( is => 'ro', - isa => 'HashRef', +has version_info => ( is => 'ro', + isa => 'HashRef', default => sub { { app_name => 'Swagger Petstore', app_version => '1.0.0', - generated_date => '2016-11-16T17:12:17.554+08:00', - generator_class => 'class io.swagger.codegen.languages.PerlClientCodegen', + generator_class => 'io.swagger.codegen.languages.PerlClientCodegen', } }, documentation => 'Information about the application version and the codegen codebase version' ); sub BUILD { my $self = shift; - + $self->_cfg->accept_tokens( $self->tokens ) if keys %{$self->tokens}; - + # ignore these symbols imported into API namespaces my %outsiders = map {$_ => 1} qw( croak ); - + my %delegates; - + # collect the methods callable on each API foreach my $api_name ($self->api_factory->apis_available) { my $api_class = $self->api_factory->classname_for($api_name); my $methods = Class::Inspector->methods($api_class, 'expanded'); # not Moose, so use CI instead my @local_methods = grep {! /^_/} grep {! $outsiders{$_}} map {$_->[2]} grep {$_->[1] eq $api_class} @$methods; - push( @{$delegates{$_}}, {api_name => $api_name, api_class => $api_class} ) for @local_methods; + push( @{$delegates{$_}}, {api_name => $api_name, api_class => $api_class} ) for @local_methods; } - + # remove clashes foreach my $method (keys %delegates) { if ( @{$delegates{$method}} > 1 ) { my ($apis) = delete $delegates{$method}; } } - + # build the flattened API foreach my $api_name ($self->api_factory->apis_available) { my $att_name = sprintf "%s_api", lc($api_name); my $api_class = $self->api_factory->classname_for($api_name); my @delegated = grep { $delegates{$_}->[0]->{api_name} eq $api_name } keys %delegates; $log->debugf("Adding API: '%s' handles %s", $att_name, join ', ', @delegated); - $self->meta->add_attribute( $att_name => ( + $self->meta->add_attribute( $att_name => ( is => 'ro', isa => $api_class, default => sub {$self->api_factory->get_api($api_name)}, @@ -112,62 +111,59 @@ sub _build_af { =head1 NAME -WWW::SwaggerClient::Role - a Moose role for the Swagger Petstore +WWW::SwaggerClient::Role - a Moose role for the Swagger Petstore =head2 Swagger Petstore version: 1.0.0 =head1 VERSION -Automatically generated by the Perl Swagger Codegen project: +Automatically generated by the Perl Swagger Codegen project: -=over 4 +=over 4 +=item Build package: io.swagger.codegen.languages.PerlClientCodegen -=item Build date: 2016-11-16T17:12:17.554+08:00 - -=item Build package: class io.swagger.codegen.languages.PerlClientCodegen - -=item Codegen version: +=item Codegen version: =back =head2 A note on Moose -This role is the only component of the library that uses Moose. See -WWW::SwaggerClient::ApiFactory for non-Moosey usage. +This role is the only component of the library that uses Moose. See +WWW::SwaggerClient::ApiFactory for non-Moosey usage. =head1 SYNOPSIS -The Perl Swagger Codegen project builds a library of Perl modules to interact with -a web service defined by a OpenAPI Specification. See below for how to build the +The Perl Swagger Codegen project builds a library of Perl modules to interact with +a web service defined by a OpenAPI Specification. See below for how to build the library. -This module provides an interface to the generated library. All the classes, -objects, and methods (well, not quite *all*, see below) are flattened into this -role. +This module provides an interface to the generated library. All the classes, +objects, and methods (well, not quite *all*, see below) are flattened into this +role. package MyApp; use Moose; with 'WWW::SwaggerClient::Role'; - + package main; - + my $api = MyApp->new({ tokens => $tokens }); - + my $pet = $api->get_pet_by_id(pet_id => $pet_id); - + =head2 Structure of the library The library consists of a set of API classes, one for each endpoint. These APIs -implement the method calls available on each endpoint. +implement the method calls available on each endpoint. -Additionally, there is a set of "object" classes, which represent the objects -returned by and sent to the methods on the endpoints. +Additionally, there is a set of "object" classes, which represent the objects +returned by and sent to the methods on the endpoints. -An API factory class is provided, which builds instances of each endpoint API. +An API factory class is provided, which builds instances of each endpoint API. -This Moose role flattens all the methods from the endpoint APIs onto the consuming -class. It also provides methods to retrieve the endpoint API objects, and the API -factory object, should you need it. +This Moose role flattens all the methods from the endpoint APIs onto the consuming +class. It also provides methods to retrieve the endpoint API objects, and the API +factory object, should you need it. For documentation of all these methods, see AUTOMATIC DOCUMENTATION below. @@ -180,33 +176,33 @@ required and where to put them. You just need to supply the tokens. # basic username => $username, password => $password, - + # oauth access_token => $oauth_token, - + # keys $some_key => { token => $token, - prefix => $prefix, - in => $in, # 'head||query', + prefix => $prefix, + in => $in, # 'head||query', }, - + $another => { token => $token, - prefix => $prefix, - in => $in, # 'head||query', - }, + prefix => $prefix, + in => $in, # 'head||query', + }, ..., - + }; - + my $api = MyApp->new({ tokens => $tokens }); Note these are all optional, as are C and C, and depend on the API you are accessing. Usually C and C will be determined by the code generator from the spec and you will not need to set them at run time. If not, C will -default to 'head' and C to the empty string. +default to 'head' and C to the empty string. The tokens will be placed in the C namespace -as follows, but you don't need to know about this. +as follows, but you don't need to know about this. =over 4 @@ -239,7 +235,7 @@ all api keys require a prefix. =item C<$WWW::SwaggerClient::Configuration::access_token> -String. The OAuth access token. +String. The OAuth access token. =back @@ -247,16 +243,16 @@ String. The OAuth access token. =head2 C -The generated code has the C already set as a default value. This method -returns (and optionally sets, but only if the API client has not been +The generated code has the C already set as a default value. This method +returns (and optionally sets, but only if the API client has not been created yet) the current value of C. =head2 C -Returns an API factory object. You probably won't need to call this directly. - +Returns an API factory object. You probably won't need to call this directly. + $self->api_factory('Pet'); # returns a WWW::SwaggerClient::PetApi instance - + $self->pet_api; # the same =head1 MISSING METHODS @@ -266,9 +262,9 @@ Most of the methods on the API are delegated to individual endpoint API objects same method name (e.g. C), these methods can't be delegated. So you need to call C<$api-Epet_api-Enew()>. -In principle, every API is susceptible to the presence of a few, random, undelegatable -method names. In practice, because of the way method names are constructed, it's -unlikely in general that any methods will be undelegatable, except for: +In principle, every API is susceptible to the presence of a few, random, undelegatable +method names. In practice, because of the way method names are constructed, it's +unlikely in general that any methods will be undelegatable, except for: new() class_documentation() @@ -281,12 +277,12 @@ you could also call them on class names. =head1 BUILDING YOUR LIBRARY -See the homepage C for full details. -But briefly, clone the git repository, build the codegen codebase, set up your build +See the homepage C for full details. +But briefly, clone the git repository, build the codegen codebase, set up your build config file, then run the API build script. You will need git, Java 7 or 8 and Apache maven 3.0.3 or better already installed. -The config file should specify the project name for the generated library: +The config file should specify the project name for the generated library: {"moduleName":"WWW::MyProjectName"} @@ -301,8 +297,8 @@ Your library files will be built under C. -c /path/to/config/file.json \ -o /path/to/output/folder -Bang, all done. Run the C script in the C directory to see the API -you just built. +Bang, all done. Run the C script in the C directory to see the API +you just built. =head1 AUTOMATIC DOCUMENTATION @@ -314,28 +310,28 @@ output formats are supported: -w wide format (default) -n narrow format - -p POD format - -H HTML format + -p POD format + -H HTML format -m Markdown format -h print this help message -c your application class - + The C<-c> option allows you to load and inspect your own application. A dummy namespace is used if you don't supply your own class. =head1 DOCUMENTATION FROM THE OpenAPI Spec -Additional documentation for each class and method may be provided by the Swagger -spec. If so, this is available via the C and -C methods on each generated object class, and the -C method on the endpoint API classes: +Additional documentation for each class and method may be provided by the Swagger +spec. If so, this is available via the C and +C methods on each generated object class, and the +C method on the endpoint API classes: - my $cmdoc = $api->pet_api->method_documentation->{$method_name}; - - my $odoc = $api->get_pet_by_id->(pet_id => $pet_id)->class_documentation; - my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; - -Each of these calls returns a hashref with various useful pieces of information. + my $cmdoc = $api->pet_api->method_documentation->{$method_name}; + + my $odoc = $api->get_pet_by_id->(pet_id => $pet_id)->class_documentation; + my $omdoc = $api->get_pet_by_id->(pet_id => $pet_id)->method_documentation->{method_name}; + +Each of these calls returns a hashref with various useful pieces of information. =cut diff --git a/samples/client/petstore/perl/t/ArrayOfArrayOfNumberOnlyTest.t b/samples/client/petstore/perl/t/ArrayOfArrayOfNumberOnlyTest.t new file mode 100644 index 00000000000..55f3388253b --- /dev/null +++ b/samples/client/petstore/perl/t/ArrayOfArrayOfNumberOnlyTest.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly'); + +my $instance = WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ArrayOfArrayOfNumberOnly'); + diff --git a/samples/client/petstore/perl/t/ArrayOfNumberOnlyTest.t b/samples/client/petstore/perl/t/ArrayOfNumberOnlyTest.t new file mode 100644 index 00000000000..278324d0124 --- /dev/null +++ b/samples/client/petstore/perl/t/ArrayOfNumberOnlyTest.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ArrayOfNumberOnly'); + +my $instance = WWW::SwaggerClient::Object::ArrayOfNumberOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ArrayOfNumberOnly'); + diff --git a/samples/client/petstore/perl/t/CapitalizationTest.t b/samples/client/petstore/perl/t/CapitalizationTest.t new file mode 100644 index 00000000000..f55d16c468c --- /dev/null +++ b/samples/client/petstore/perl/t/CapitalizationTest.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::Capitalization'); + +my $instance = WWW::SwaggerClient::Object::Capitalization->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::Capitalization'); + diff --git a/samples/client/petstore/perl/t/ClassModelTest.t b/samples/client/petstore/perl/t/ClassModelTest.t new file mode 100644 index 00000000000..b0175148496 --- /dev/null +++ b/samples/client/petstore/perl/t/ClassModelTest.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::ClassModel'); + +my $instance = WWW::SwaggerClient::Object::ClassModel->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::ClassModel'); + diff --git a/samples/client/petstore/perl/t/ClientTest.t b/samples/client/petstore/perl/t/ClientTest.t new file mode 100644 index 00000000000..e5763def392 --- /dev/null +++ b/samples/client/petstore/perl/t/ClientTest.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::Client'); + +my $instance = WWW::SwaggerClient::Object::Client->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::Client'); + diff --git a/samples/client/petstore/perl/t/EnumArraysTest.t b/samples/client/petstore/perl/t/EnumArraysTest.t new file mode 100644 index 00000000000..2a8edae5870 --- /dev/null +++ b/samples/client/petstore/perl/t/EnumArraysTest.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::EnumArrays'); + +my $instance = WWW::SwaggerClient::Object::EnumArrays->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::EnumArrays'); + diff --git a/samples/client/petstore/perl/t/FakeApiTest.t b/samples/client/petstore/perl/t/FakeApiTest.t new file mode 100644 index 00000000000..4855c9f7057 --- /dev/null +++ b/samples/client/petstore/perl/t/FakeApiTest.t @@ -0,0 +1,77 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by Swagger Codegen +# Please update the test cases below to test the API endpoints. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 1; #TODO update number of test cases +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + +use_ok('WWW::SwaggerClient::FakeApi'); + +my $api = WWW::SwaggerClient::FakeApi->new(); +isa_ok($api, 'WWW::SwaggerClient::FakeApi'); + +# +# test_client_model test +# +{ + my $body = undef; # replace NULL with a proper value + my $result = $api->test_client_model(body => $body); +} + +# +# test_endpoint_parameters test +# +{ + my $number = undef; # replace NULL with a proper value + my $double = undef; # replace NULL with a proper value + my $pattern_without_delimiter = undef; # replace NULL with a proper value + my $byte = undef; # replace NULL with a proper value + my $integer = undef; # replace NULL with a proper value + my $int32 = undef; # replace NULL with a proper value + my $int64 = undef; # replace NULL with a proper value + my $float = undef; # replace NULL with a proper value + my $string = undef; # replace NULL with a proper value + my $binary = undef; # replace NULL with a proper value + my $date = undef; # replace NULL with a proper value + my $date_time = undef; # replace NULL with a proper value + my $password = undef; # replace NULL with a proper value + my $callback = undef; # replace NULL with a proper value + my $result = $api->test_endpoint_parameters(number => $number, double => $double, pattern_without_delimiter => $pattern_without_delimiter, byte => $byte, integer => $integer, int32 => $int32, int64 => $int64, float => $float, string => $string, binary => $binary, date => $date, date_time => $date_time, password => $password, callback => $callback); +} + +# +# test_enum_parameters test +# +{ + my $enum_form_string_array = undef; # replace NULL with a proper value + my $enum_form_string = undef; # replace NULL with a proper value + my $enum_header_string_array = undef; # replace NULL with a proper value + my $enum_header_string = undef; # replace NULL with a proper value + my $enum_query_string_array = undef; # replace NULL with a proper value + my $enum_query_string = undef; # replace NULL with a proper value + my $enum_query_integer = undef; # replace NULL with a proper value + my $enum_query_double = undef; # replace NULL with a proper value + my $result = $api->test_enum_parameters(enum_form_string_array => $enum_form_string_array, enum_form_string => $enum_form_string, enum_header_string_array => $enum_header_string_array, enum_header_string => $enum_header_string, enum_query_string_array => $enum_query_string_array, enum_query_string => $enum_query_string, enum_query_integer => $enum_query_integer, enum_query_double => $enum_query_double); +} + + +1; diff --git a/samples/client/petstore/perl/t/HasOnlyReadOnlyTest.t b/samples/client/petstore/perl/t/HasOnlyReadOnlyTest.t new file mode 100644 index 00000000000..ba598e0f2c4 --- /dev/null +++ b/samples/client/petstore/perl/t/HasOnlyReadOnlyTest.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::HasOnlyReadOnly'); + +my $instance = WWW::SwaggerClient::Object::HasOnlyReadOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::HasOnlyReadOnly'); + diff --git a/samples/client/petstore/perl/t/ListTest.t b/samples/client/petstore/perl/t/ListTest.t new file mode 100644 index 00000000000..9cf167906a9 --- /dev/null +++ b/samples/client/petstore/perl/t/ListTest.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::List'); + +my $instance = WWW::SwaggerClient::Object::List->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::List'); + diff --git a/samples/client/petstore/perl/t/MapTestTest.t b/samples/client/petstore/perl/t/MapTestTest.t new file mode 100644 index 00000000000..acb1be0ccbd --- /dev/null +++ b/samples/client/petstore/perl/t/MapTestTest.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::MapTest'); + +my $instance = WWW::SwaggerClient::Object::MapTest->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::MapTest'); + diff --git a/samples/client/petstore/perl/t/NumberOnlyTest.t b/samples/client/petstore/perl/t/NumberOnlyTest.t new file mode 100644 index 00000000000..4daf60b5dfb --- /dev/null +++ b/samples/client/petstore/perl/t/NumberOnlyTest.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::NumberOnly'); + +my $instance = WWW::SwaggerClient::Object::NumberOnly->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::NumberOnly'); + diff --git a/samples/client/petstore/perl/t/OuterEnumTest.t b/samples/client/petstore/perl/t/OuterEnumTest.t new file mode 100644 index 00000000000..77c1962bb3f --- /dev/null +++ b/samples/client/petstore/perl/t/OuterEnumTest.t @@ -0,0 +1,33 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by the Swagger Codegen +# Please update the test cases below to test the model. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 2; +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + + +use_ok('WWW::SwaggerClient::Object::OuterEnum'); + +my $instance = WWW::SwaggerClient::Object::OuterEnum->new(); + +isa_ok($instance, 'WWW::SwaggerClient::Object::OuterEnum'); + diff --git a/samples/client/petstore/perl/t/PetApiTest.t b/samples/client/petstore/perl/t/PetApiTest.t new file mode 100644 index 00000000000..cf0041edd12 --- /dev/null +++ b/samples/client/petstore/perl/t/PetApiTest.t @@ -0,0 +1,102 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by Swagger Codegen +# Please update the test cases below to test the API endpoints. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 1; #TODO update number of test cases +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + +use_ok('WWW::SwaggerClient::PetApi'); + +my $api = WWW::SwaggerClient::PetApi->new(); +isa_ok($api, 'WWW::SwaggerClient::PetApi'); + +# +# add_pet test +# +{ + my $body = undef; # replace NULL with a proper value + my $result = $api->add_pet(body => $body); +} + +# +# delete_pet test +# +{ + my $pet_id = undef; # replace NULL with a proper value + my $api_key = undef; # replace NULL with a proper value + my $result = $api->delete_pet(pet_id => $pet_id, api_key => $api_key); +} + +# +# find_pets_by_status test +# +{ + my $status = undef; # replace NULL with a proper value + my $result = $api->find_pets_by_status(status => $status); +} + +# +# find_pets_by_tags test +# +{ + my $tags = undef; # replace NULL with a proper value + my $result = $api->find_pets_by_tags(tags => $tags); +} + +# +# get_pet_by_id test +# +{ + my $pet_id = undef; # replace NULL with a proper value + my $result = $api->get_pet_by_id(pet_id => $pet_id); +} + +# +# update_pet test +# +{ + my $body = undef; # replace NULL with a proper value + my $result = $api->update_pet(body => $body); +} + +# +# update_pet_with_form test +# +{ + my $pet_id = undef; # replace NULL with a proper value + my $name = undef; # replace NULL with a proper value + my $status = undef; # replace NULL with a proper value + my $result = $api->update_pet_with_form(pet_id => $pet_id, name => $name, status => $status); +} + +# +# upload_file test +# +{ + my $pet_id = undef; # replace NULL with a proper value + my $additional_metadata = undef; # replace NULL with a proper value + my $file = undef; # replace NULL with a proper value + my $result = $api->upload_file(pet_id => $pet_id, additional_metadata => $additional_metadata, file => $file); +} + + +1; diff --git a/samples/client/petstore/perl/t/StoreApiTest.t b/samples/client/petstore/perl/t/StoreApiTest.t new file mode 100644 index 00000000000..98c11bb5839 --- /dev/null +++ b/samples/client/petstore/perl/t/StoreApiTest.t @@ -0,0 +1,64 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by Swagger Codegen +# Please update the test cases below to test the API endpoints. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 1; #TODO update number of test cases +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + +use_ok('WWW::SwaggerClient::StoreApi'); + +my $api = WWW::SwaggerClient::StoreApi->new(); +isa_ok($api, 'WWW::SwaggerClient::StoreApi'); + +# +# delete_order test +# +{ + my $order_id = undef; # replace NULL with a proper value + my $result = $api->delete_order(order_id => $order_id); +} + +# +# get_inventory test +# +{ + my $result = $api->get_inventory(); +} + +# +# get_order_by_id test +# +{ + my $order_id = undef; # replace NULL with a proper value + my $result = $api->get_order_by_id(order_id => $order_id); +} + +# +# place_order test +# +{ + my $body = undef; # replace NULL with a proper value + my $result = $api->place_order(body => $body); +} + + +1; diff --git a/samples/client/petstore/perl/t/UserApiTest.t b/samples/client/petstore/perl/t/UserApiTest.t new file mode 100644 index 00000000000..57a830412c0 --- /dev/null +++ b/samples/client/petstore/perl/t/UserApiTest.t @@ -0,0 +1,98 @@ +=begin comment + +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end comment + +=cut + +# +# NOTE: This class is auto generated by Swagger Codegen +# Please update the test cases below to test the API endpoints. +# Ref: https://github.com/swagger-api/swagger-codegen +# +use Test::More tests => 1; #TODO update number of test cases +use Test::Exception; + +use lib 'lib'; +use strict; +use warnings; + +use_ok('WWW::SwaggerClient::UserApi'); + +my $api = WWW::SwaggerClient::UserApi->new(); +isa_ok($api, 'WWW::SwaggerClient::UserApi'); + +# +# create_user test +# +{ + my $body = undef; # replace NULL with a proper value + my $result = $api->create_user(body => $body); +} + +# +# create_users_with_array_input test +# +{ + my $body = undef; # replace NULL with a proper value + my $result = $api->create_users_with_array_input(body => $body); +} + +# +# create_users_with_list_input test +# +{ + my $body = undef; # replace NULL with a proper value + my $result = $api->create_users_with_list_input(body => $body); +} + +# +# delete_user test +# +{ + my $username = undef; # replace NULL with a proper value + my $result = $api->delete_user(username => $username); +} + +# +# get_user_by_name test +# +{ + my $username = undef; # replace NULL with a proper value + my $result = $api->get_user_by_name(username => $username); +} + +# +# login_user test +# +{ + my $username = undef; # replace NULL with a proper value + my $password = undef; # replace NULL with a proper value + my $result = $api->login_user(username => $username, password => $password); +} + +# +# logout_user test +# +{ + my $result = $api->logout_user(); +} + +# +# update_user test +# +{ + my $username = undef; # replace NULL with a proper value + my $body = undef; # replace NULL with a proper value + my $result = $api->update_user(username => $username, body => $body); +} + + +1; diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index a8d469f5c02..7de4bd350d5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -109,6 +109,7 @@ Class | Method | HTTP request | Description - [ArrayOfArrayOfNumberOnly](docs/Model/ArrayOfArrayOfNumberOnly.md) - [ArrayOfNumberOnly](docs/Model/ArrayOfNumberOnly.md) - [ArrayTest](docs/Model/ArrayTest.md) + - [Capitalization](docs/Model/Capitalization.md) - [Cat](docs/Model/Cat.md) - [Category](docs/Model/Category.md) - [ClassModel](docs/Model/ClassModel.md) diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md index b589c11a32a..d99eea4c925 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Api/PetApi.md @@ -389,7 +389,7 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| ID of pet to update | **additional_metadata** | **string**| Additional data to pass to server | [optional] - **file** | **\SplFileObject****\SplFileObject**| file to upload | [optional] + **file** | **\SplFileObject**| file to upload | [optional] ### Return type diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/Model/Capitalization.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Capitalization.md new file mode 100644 index 00000000000..0fcc9e873d7 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/Capitalization.md @@ -0,0 +1,15 @@ +# Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**small_camel** | **string** | | [optional] +**capital_camel** | **string** | | [optional] +**small_snake** | **string** | | [optional] +**capital_snake** | **string** | | [optional] +**sca_eth_flow_points** | **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/php/SwaggerClient-php/docs/Model/ClassModel.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/ClassModel.md new file mode 100644 index 00000000000..3ad025b6ed3 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/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/php/SwaggerClient-php/docs/Model/OuterEnum.md b/samples/client/petstore/php/SwaggerClient-php/docs/Model/OuterEnum.md new file mode 100644 index 00000000000..06d413b0168 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/Model/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/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 9d13660091f..54522e7a792 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -59,7 +59,6 @@ class FakeApi { if ($apiClient === null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } $this->apiClient = $apiClient; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index efee25ca687..cb902068dd4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -59,7 +59,6 @@ class PetApi { if ($apiClient === null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } $this->apiClient = $apiClient; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 7070313661d..655fb65737a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -59,7 +59,6 @@ class StoreApi { if ($apiClient === null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } $this->apiClient = $apiClient; @@ -118,10 +117,6 @@ class StoreApi if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); } - if (($order_id < 1.0)) { - throw new \InvalidArgumentException('invalid value for "$order_id" when calling StoreApi.deleteOrder, must be bigger than or equal to 1.0.'); - } - // parse inputs $resourcePath = "/store/order/{orderId}"; $httpBody = ''; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index db404dd8818..31580e1b3c1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -59,7 +59,6 @@ class UserApi { if ($apiClient === null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); } $this->apiClient = $apiClient; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 8bda07de03f..b8add9f133c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -163,6 +163,11 @@ class ApiClient if ($this->config->getCurlTimeout() !== 0) { curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); } + // set connect timeout, if needed + if ($this->config->getCurlConnectTimeout() != 0) { + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $this->config->getCurlConnectTimeout()); + } + // return the result on success, rather than just true curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); @@ -174,6 +179,22 @@ class ApiClient curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); } + if ($this->config->getCurlProxyHost()) { + curl_setopt($curl, CURLOPT_PROXY, $this->config->getCurlProxyHost()); + } + + if ($this->config->getCurlProxyPort()) { + curl_setopt($curl, CURLOPT_PROXYPORT, $this->config->getCurlProxyPort()); + } + + if ($this->config->getCurlProxyType()) { + curl_setopt($curl, CURLOPT_PROXYTYPE, $this->config->getCurlProxyType()); + } + + if ($this->config->getCurlProxyUser()) { + curl_setopt($curl, CURLOPT_PROXYUSERPWD, $this->config->getCurlProxyUser() . ':' .$this->config->getCurlProxyPassword()); + } + if (!empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index ca4e62be7ee..cc6875156cf 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -97,6 +97,13 @@ class Configuration */ protected $curlTimeout = 0; + /** + * Timeout (second) of the HTTP connection, by default set to 0, no timeout + * + * @var string + */ + protected $curlConnectTimeout = 0; + /** * User agent of the HTTP request, set to "PHP-Swagger" by default * @@ -134,6 +141,42 @@ class Configuration */ protected $sslVerification = true; + /** + * Curl proxy host + * + * @var string + */ + protected $proxyHost; + + /** + * Curl proxy port + * + * @var integer + */ + protected $proxyPort; + + /** + * Curl proxy type, e.g. CURLPROXY_HTTP or CURLPROXY_SOCKS5 + * + * @see https://secure.php.net/manual/en/function.curl-setopt.php + * @var integer + */ + protected $proxyType; + + /** + * Curl proxy username + * + * @var string + */ + protected $proxyUser; + + /** + * Curl proxy password + * + * @var string + */ + protected $proxyPassword; + /** * Constructor */ @@ -380,6 +423,149 @@ class Configuration return $this->curlTimeout; } + /** + * Sets the HTTP connect timeout value + * + * @param integer $seconds Number of seconds before connection times out [set to 0 for no timeout] + * + * @return Configuration + */ + public function setCurlConnectTimeout($seconds) + { + if (!is_numeric($seconds) || $seconds < 0) { + throw new \InvalidArgumentException('Connect timeout value must be numeric and a non-negative number.'); + } + + $this->curlConnectTimeout = $seconds; + return $this; + } + + /** + * Gets the HTTP connect timeout value + * + * @return string HTTP connect timeout value + */ + public function getCurlConnectTimeout() + { + return $this->curlConnectTimeout; + } + + + /** + * Sets the HTTP Proxy Host + * + * @param string $proxyHost HTTP Proxy URL + * + * @return ApiClient + */ + public function setCurlProxyHost($proxyHost) + { + $this->proxyHost = $proxyHost; + return $this; + } + + /** + * Gets the HTTP Proxy Host + * + * @return string + */ + public function getCurlProxyHost() + { + return $this->proxyHost; + } + + /** + * Sets the HTTP Proxy Port + * + * @param integer $proxyPort HTTP Proxy Port + * + * @return ApiClient + */ + public function setCurlProxyPort($proxyPort) + { + $this->proxyPort = $proxyPort; + return $this; + } + + /** + * Gets the HTTP Proxy Port + * + * @return integer + */ + public function getCurlProxyPort() + { + return $this->proxyPort; + } + + /** + * Sets the HTTP Proxy Type + * + * @param integer $proxyType HTTP Proxy Type + * + * @return ApiClient + */ + public function setCurlProxyType($proxyType) + { + $this->proxyType = $proxyType; + return $this; + } + + /** + * Gets the HTTP Proxy Type + * + * @return integer + */ + public function getCurlProxyType() + { + return $this->proxyType; + } + + /** + * Sets the HTTP Proxy User + * + * @param string $proxyUser HTTP Proxy User + * + * @return ApiClient + */ + public function setCurlProxyUser($proxyUser) + { + $this->proxyUser = $proxyUser; + return $this; + } + + /** + * Gets the HTTP Proxy User + * + * @return string + */ + public function getCurlProxyUser() + { + return $this->proxyUser; + } + + /** + * Sets the HTTP Proxy Password + * + * @param string $proxyPassword HTTP Proxy Password + * + * @return ApiClient + */ + public function setCurlProxyPassword($proxyPassword) + { + $this->proxyPassword = $proxyPassword; + return $this; + } + + /** + * Gets the HTTP Proxy Password + * + * @return string + */ + public function getCurlProxyPassword() + { + return $this->proxyPassword; + } + /** * Sets debug flag * diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php index 5be00bdb3dc..8f901b731a2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AdditionalPropertiesClass.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * AdditionalPropertiesClass Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -136,6 +135,7 @@ class AdditionalPropertiesClass implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -143,10 +143,11 @@ class AdditionalPropertiesClass implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php index dff108c3214..a0f1de3c08c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Animal.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * Animal Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -140,6 +139,7 @@ class Animal implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + if ($this->container['class_name'] === null) { $invalid_properties[] = "'class_name' can't be null"; } @@ -150,10 +150,11 @@ class Animal implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + if ($this->container['class_name'] === null) { return false; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php index b9244039c30..d1736598716 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/AnimalFarm.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * AnimalFarm Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -129,7 +128,8 @@ class AnimalFarm implements ArrayAccess */ public function listInvalidProperties() { - $invalid_properties = []; + $invalid_properties = parent::listInvalidProperties(); + return $invalid_properties; } @@ -137,10 +137,14 @@ class AnimalFarm implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + if (!parent::valid()) { + return false; + } + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php index 2d2732d89c8..95148c75e22 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ApiResponse.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * ApiResponse Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -141,6 +140,7 @@ class ApiResponse implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -148,10 +148,11 @@ class ApiResponse implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php index eb969b9c1be..48f3b369b77 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * ArrayOfArrayOfNumberOnly Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -131,6 +130,7 @@ class ArrayOfArrayOfNumberOnly implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -138,10 +138,11 @@ class ArrayOfArrayOfNumberOnly implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php index be0521157ff..103297a25e0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayOfNumberOnly.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * ArrayOfNumberOnly Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -131,6 +130,7 @@ class ArrayOfNumberOnly implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -138,10 +138,11 @@ class ArrayOfNumberOnly implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php index 5eda007acef..f95c8cf869b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ArrayTest.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * ArrayTest Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -141,6 +140,7 @@ class ArrayTest implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -148,10 +148,11 @@ class ArrayTest implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Capitalization.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Capitalization.php new file mode 100644 index 00000000000..9e124413199 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Capitalization.php @@ -0,0 +1,359 @@ + 'string', + 'capital_camel' => 'string', + 'small_snake' => 'string', + 'capital_snake' => 'string', + 'sca_eth_flow_points' => 'string', + 'att_name' => 'string' + ]; + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = [ + 'small_camel' => 'smallCamel', + 'capital_camel' => 'CapitalCamel', + 'small_snake' => 'small_Snake', + 'capital_snake' => 'Capital_Snake', + 'sca_eth_flow_points' => 'SCA_ETH_Flow_Points', + 'att_name' => 'ATT_NAME' + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + 'small_camel' => 'setSmallCamel', + 'capital_camel' => 'setCapitalCamel', + 'small_snake' => 'setSmallSnake', + 'capital_snake' => 'setCapitalSnake', + 'sca_eth_flow_points' => 'setScaEthFlowPoints', + 'att_name' => 'setAttName' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + 'small_camel' => 'getSmallCamel', + 'capital_camel' => 'getCapitalCamel', + 'small_snake' => 'getSmallSnake', + 'capital_snake' => 'getCapitalSnake', + 'sca_eth_flow_points' => 'getScaEthFlowPoints', + 'att_name' => 'getAttName' + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->container['small_camel'] = isset($data['small_camel']) ? $data['small_camel'] : null; + $this->container['capital_camel'] = isset($data['capital_camel']) ? $data['capital_camel'] : null; + $this->container['small_snake'] = isset($data['small_snake']) ? $data['small_snake'] : null; + $this->container['capital_snake'] = isset($data['capital_snake']) ? $data['capital_snake'] : null; + $this->container['sca_eth_flow_points'] = isset($data['sca_eth_flow_points']) ? $data['sca_eth_flow_points'] : null; + $this->container['att_name'] = isset($data['att_name']) ? $data['att_name'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = []; + + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets small_camel + * @return string + */ + public function getSmallCamel() + { + return $this->container['small_camel']; + } + + /** + * Sets small_camel + * @param string $small_camel + * @return $this + */ + public function setSmallCamel($small_camel) + { + $this->container['small_camel'] = $small_camel; + + return $this; + } + + /** + * Gets capital_camel + * @return string + */ + public function getCapitalCamel() + { + return $this->container['capital_camel']; + } + + /** + * Sets capital_camel + * @param string $capital_camel + * @return $this + */ + public function setCapitalCamel($capital_camel) + { + $this->container['capital_camel'] = $capital_camel; + + return $this; + } + + /** + * Gets small_snake + * @return string + */ + public function getSmallSnake() + { + return $this->container['small_snake']; + } + + /** + * Sets small_snake + * @param string $small_snake + * @return $this + */ + public function setSmallSnake($small_snake) + { + $this->container['small_snake'] = $small_snake; + + return $this; + } + + /** + * Gets capital_snake + * @return string + */ + public function getCapitalSnake() + { + return $this->container['capital_snake']; + } + + /** + * Sets capital_snake + * @param string $capital_snake + * @return $this + */ + public function setCapitalSnake($capital_snake) + { + $this->container['capital_snake'] = $capital_snake; + + return $this; + } + + /** + * Gets sca_eth_flow_points + * @return string + */ + public function getScaEthFlowPoints() + { + return $this->container['sca_eth_flow_points']; + } + + /** + * Sets sca_eth_flow_points + * @param string $sca_eth_flow_points + * @return $this + */ + public function setScaEthFlowPoints($sca_eth_flow_points) + { + $this->container['sca_eth_flow_points'] = $sca_eth_flow_points; + + return $this; + } + + /** + * Gets att_name + * @return string + */ + public function getAttName() + { + return $this->container['att_name']; + } + + /** + * Sets att_name + * @param string $att_name Name of the pet + * @return $this + */ + public function setAttName($att_name) + { + $this->container['att_name'] = $att_name; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php index 8450b99c1ea..611f01e36f4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Cat.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * Cat Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -132,7 +131,8 @@ class Cat extends Animal implements ArrayAccess */ public function listInvalidProperties() { - $invalid_properties = []; + $invalid_properties = parent::listInvalidProperties(); + return $invalid_properties; } @@ -140,10 +140,14 @@ class Cat extends Animal implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + if (!parent::valid()) { + return false; + } + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index c5b1e6c96ba..f8848cb956e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * Category Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -136,6 +135,7 @@ class Category implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -143,10 +143,11 @@ class Category implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ClassModel.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ClassModel.php new file mode 100644 index 00000000000..18aa0fcbd4b --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ClassModel.php @@ -0,0 +1,230 @@ + 'string' + ]; + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = [ + '_class' => '_class' + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + '_class' => 'setClass' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + '_class' => 'getClass' + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->container['_class'] = isset($data['_class']) ? $data['_class'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = []; + + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets _class + * @return string + */ + public function getClass() + { + return $this->container['_class']; + } + + /** + * Sets _class + * @param string $_class + * @return $this + */ + public function setClass($_class) + { + $this->container['_class'] = $_class; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php index e642f6f8da9..a6a09cfa3a7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Client.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * Client Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -131,6 +130,7 @@ class Client implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -138,10 +138,11 @@ class Client implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php index a6a17e6114a..ba325f2f8bc 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Dog.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * Dog Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -132,7 +131,8 @@ class Dog extends Animal implements ArrayAccess */ public function listInvalidProperties() { - $invalid_properties = []; + $invalid_properties = parent::listInvalidProperties(); + return $invalid_properties; } @@ -140,10 +140,14 @@ class Dog extends Animal implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + if (!parent::valid()) { + return false; + } + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php index e6dea8c2d18..09d496d1926 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumArrays.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * EnumArrays Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -164,9 +163,10 @@ class EnumArrays implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + $allowed_values = [">=", "$"]; if (!in_array($this->container['just_symbol'], $allowed_values)) { - $invalid_properties[] = "invalid value for 'just_symbol', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'just_symbol', must be one of '>=', '$'."; } return $invalid_properties; @@ -176,10 +176,11 @@ class EnumArrays implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + $allowed_values = [">=", "$"]; if (!in_array($this->container['just_symbol'], $allowed_values)) { return false; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php index 356be0577f6..223e012b084 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * EnumClass Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php index cfee4f5eaab..bb6d88b4b96 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * EnumTest Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -118,6 +117,7 @@ class EnumTest implements ArrayAccess const ENUM_STRING_UPPER = 'UPPER'; const ENUM_STRING_LOWER = 'lower'; + const ENUM_STRING_EMPTY = ''; const ENUM_INTEGER_1 = 1; const ENUM_INTEGER_MINUS_1 = -1; const ENUM_NUMBER_1_DOT_1 = 1.1; @@ -134,6 +134,7 @@ class EnumTest implements ArrayAccess return [ self::ENUM_STRING_UPPER, self::ENUM_STRING_LOWER, + self::ENUM_STRING_EMPTY, ]; } @@ -188,19 +189,20 @@ class EnumTest implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; - $allowed_values = ["UPPER", "lower"]; + + $allowed_values = ["UPPER", "lower", ""]; if (!in_array($this->container['enum_string'], $allowed_values)) { - $invalid_properties[] = "invalid value for 'enum_string', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_string', must be one of 'UPPER', 'lower', ''."; } $allowed_values = ["1", "-1"]; if (!in_array($this->container['enum_integer'], $allowed_values)) { - $invalid_properties[] = "invalid value for 'enum_integer', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_integer', must be one of '1', '-1'."; } $allowed_values = ["1.1", "-1.2"]; if (!in_array($this->container['enum_number'], $allowed_values)) { - $invalid_properties[] = "invalid value for 'enum_number', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'enum_number', must be one of '1.1', '-1.2'."; } return $invalid_properties; @@ -210,11 +212,12 @@ class EnumTest implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { - $allowed_values = ["UPPER", "lower"]; + + $allowed_values = ["UPPER", "lower", ""]; if (!in_array($this->container['enum_string'], $allowed_values)) { return false; } @@ -246,9 +249,9 @@ class EnumTest implements ArrayAccess */ public function setEnumString($enum_string) { - $allowed_values = array('UPPER', 'lower'); + $allowed_values = array('UPPER', 'lower', ''); if (!is_null($enum_string) && (!in_array($enum_string, $allowed_values))) { - throw new \InvalidArgumentException("Invalid value for 'enum_string', must be one of 'UPPER', 'lower'"); + throw new \InvalidArgumentException("Invalid value for 'enum_string', must be one of 'UPPER', 'lower', ''"); } $this->container['enum_string'] = $enum_string; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php index 29fc74a86eb..400d9adf3c3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/FormatTest.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * FormatTest Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -191,6 +190,7 @@ class FormatTest implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + if (!is_null($this->container['integer']) && ($this->container['integer'] > 100)) { $invalid_properties[] = "invalid value for 'integer', must be smaller than or equal to 100."; } @@ -262,10 +262,11 @@ class FormatTest implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + if ($this->container['integer'] > 100) { return false; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php index c88fa186ccb..953f1550bbc 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/HasOnlyReadOnly.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * HasOnlyReadOnly Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -136,6 +135,7 @@ class HasOnlyReadOnly implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -143,10 +143,11 @@ class HasOnlyReadOnly implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php index 67c6f2ef6ff..024ec0b45ee 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MapTest.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * MapTest Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -150,6 +149,7 @@ class MapTest implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -157,10 +157,11 @@ class MapTest implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php index 232f6f161cf..a7b8eb94812 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * MixedPropertiesAndAdditionalPropertiesClass Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -141,6 +140,7 @@ class MixedPropertiesAndAdditionalPropertiesClass implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -148,10 +148,11 @@ class MixedPropertiesAndAdditionalPropertiesClass implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php index 610ae374fd4..36473dc1dcc 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Model200Response.php @@ -34,9 +34,8 @@ use \ArrayAccess; /** * Model200Response Class Doc Comment * - * @category Class */ - // @description Model for testing model name starting with number -/** + * @category Class + * @description Model for testing model name starting with number * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -137,6 +136,7 @@ class Model200Response implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -144,10 +144,11 @@ class Model200Response implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php index 35789521a88..d2fae7b53f9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelList.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * ModelList Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -131,6 +130,7 @@ class ModelList implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -138,10 +138,11 @@ class ModelList implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php index 2d65176ee55..f959dbd5065 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -34,9 +34,8 @@ use \ArrayAccess; /** * ModelReturn Class Doc Comment * - * @category Class */ - // @description Model for testing reserved words -/** + * @category Class + * @description Model for testing reserved words * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -132,6 +131,7 @@ class ModelReturn implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -139,10 +139,11 @@ class ModelReturn implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php index eb45df9cacd..61a6838537b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Name.php @@ -34,9 +34,8 @@ use \ArrayAccess; /** * Name Class Doc Comment * - * @category Class */ - // @description Model for testing model name same as property name -/** + * @category Class + * @description Model for testing model name same as property name * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -147,6 +146,7 @@ class Name implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + if ($this->container['name'] === null) { $invalid_properties[] = "'name' can't be null"; } @@ -157,10 +157,11 @@ class Name implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + if ($this->container['name'] === null) { return false; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php index 2907e80bee9..eb5e7f10698 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/NumberOnly.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * NumberOnly Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -131,6 +130,7 @@ class NumberOnly implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -138,10 +138,11 @@ class NumberOnly implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 8a3e8b58ff4..1b70e5914b6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * Order Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -172,9 +171,10 @@ class Order implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + $allowed_values = ["placed", "approved", "delivered"]; if (!in_array($this->container['status'], $allowed_values)) { - $invalid_properties[] = "invalid value for 'status', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'status', must be one of 'placed', 'approved', 'delivered'."; } return $invalid_properties; @@ -184,10 +184,11 @@ class Order implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + $allowed_values = ["placed", "approved", "delivered"]; if (!in_array($this->container['status'], $allowed_values)) { return false; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/OuterEnum.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/OuterEnum.php new file mode 100644 index 00000000000..b077a3b7b74 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/OuterEnum.php @@ -0,0 +1,50 @@ +container['name'] === null) { $invalid_properties[] = "'name' can't be null"; } @@ -180,7 +180,7 @@ class Pet implements ArrayAccess } $allowed_values = ["available", "pending", "sold"]; if (!in_array($this->container['status'], $allowed_values)) { - $invalid_properties[] = "invalid value for 'status', must be one of #{allowed_values}."; + $invalid_properties[] = "invalid value for 'status', must be one of 'available', 'pending', 'sold'."; } return $invalid_properties; @@ -190,10 +190,11 @@ class Pet implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + if ($this->container['name'] === null) { return false; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php index 1f2ec1095ab..b53677fc495 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/ReadOnlyFirst.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * ReadOnlyFirst Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -136,6 +135,7 @@ class ReadOnlyFirst implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -143,10 +143,11 @@ class ReadOnlyFirst implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php index dc78d2ef6c5..ac73ff0a376 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/SpecialModelName.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * SpecialModelName Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -131,6 +130,7 @@ class SpecialModelName implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -138,10 +138,11 @@ class SpecialModelName implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index f72c54d58bd..1705129380b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * Tag Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -136,6 +135,7 @@ class Tag implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -143,10 +143,11 @@ class Tag implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 82564b9d658..583a94ca57c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -34,8 +34,7 @@ use \ArrayAccess; /** * User Class Doc Comment * - * @category Class */ -/** + * @category Class * @package Swagger\Client * @author Swagger Codegen team * @link https://github.com/swagger-api/swagger-codegen @@ -166,6 +165,7 @@ class User implements ArrayAccess public function listInvalidProperties() { $invalid_properties = []; + return $invalid_properties; } @@ -173,10 +173,11 @@ class User implements ArrayAccess * validate all the properties in the model * return true if all passed * - * @return bool True if all properteis are valid + * @return bool True if all properties are valid */ public function valid() { + return true; } diff --git a/samples/client/petstore/php/SwaggerClient-php/test/Model/CapitalizationTest.php b/samples/client/petstore/php/SwaggerClient-php/test/Model/CapitalizationTest.php new file mode 100644 index 00000000000..48e309b787f --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/test/Model/CapitalizationTest.php @@ -0,0 +1,133 @@ +assertSame('red', $dog->getColor()); $this->assertSame('red', $animal->getColor()); } + + // Ensure that API Classes pickup ApiClient defaults to prevent regressions of PR #4525 + public function testHostOverride() + { + $orig_default = Configuration::getDefaultConfiguration(); + $new_default = new Configuration(); + + $new_default->setHost("http://localhost/whatever"); + Configuration::setDefaultConfiguration($new_default); + + $pet_api = new Api\PetApi(); + $pet_host = $pet_api->getApiClient()->getConfig()->getHost(); + $this->assertSame($pet_host, $new_default->getHost()); + + Configuration::setDefaultConfiguration($orig_default); // Reset to original to prevent failure of other tests that rely on this state + } } diff --git a/samples/client/petstore/python/petstore_api/apis/fake_classname_tags_123_api.py b/samples/client/petstore/python/petstore_api/apis/fake_classname_tags_123_api.py index de8d248fb9e..1797c8c7a91 100644 --- a/samples/client/petstore/python/petstore_api/apis/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python/petstore_api/apis/fake_classname_tags_123_api.py @@ -8,20 +8,9 @@ OpenAPI spec version: 1.0.0 Contact: apiteam@swagger.io Generated by: https://github.com/swagger-api/swagger-codegen.git - - 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 - - http://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. """ + from __future__ import absolute_import import sys @@ -54,8 +43,6 @@ class FakeClassnameTags123Api(object): def test_classname(self, body, **kwargs): """ To test class name in snake case - - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -81,8 +68,6 @@ class FakeClassnameTags123Api(object): def test_classname_with_http_info(self, body, **kwargs): """ To test class name in snake case - - This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please define a `callback` function to be invoked when receiving the response. @@ -102,6 +87,8 @@ class FakeClassnameTags123Api(object): all_params = ['body'] all_params.append('callback') all_params.append('_return_http_data_only') + all_params.append('_preload_content') + all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): @@ -132,12 +119,9 @@ class FakeClassnameTags123Api(object): body_params = None if 'body' in params: body_params = params['body'] - # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) - if not header_params['Accept']: - del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ @@ -147,14 +131,16 @@ class FakeClassnameTags123Api(object): auth_settings = [] return self.api_client.call_api(resource_path, 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Client', - auth_settings=auth_settings, - callback=params.get('callback'), - _return_http_data_only=params.get('_return_http_data_only'), - collection_formats=collection_formats) + path_params, + query_params, + header_params, + body=body_params, + post_params=form_params, + files=local_var_files, + response_type='Client', + auth_settings=auth_settings, + callback=params.get('callback'), + _return_http_data_only=params.get('_return_http_data_only'), + _preload_content=params.get('_preload_content', True), + _request_timeout=params.get('_request_timeout'), + collection_formats=collection_formats) diff --git a/samples/client/petstore/python/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python/petstore_api/models/additional_properties_class.py index 4840f52a8e8..5873f70643f 100644 --- a/samples/client/petstore/python/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/models/additional_properties_class.py @@ -127,6 +127,9 @@ class AdditionalPropertiesClass(object): """ Returns true if both objects are equal """ + if not isinstance(other, AdditionalPropertiesClass): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/animal.py b/samples/client/petstore/python/petstore_api/models/animal.py index c12c9d22284..c46cfb28ddb 100644 --- a/samples/client/petstore/python/petstore_api/models/animal.py +++ b/samples/client/petstore/python/petstore_api/models/animal.py @@ -129,6 +129,9 @@ class Animal(object): """ Returns true if both objects are equal """ + if not isinstance(other, Animal): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/animal_farm.py b/samples/client/petstore/python/petstore_api/models/animal_farm.py index b3884fb4b3f..ff8a3794e90 100644 --- a/samples/client/petstore/python/petstore_api/models/animal_farm.py +++ b/samples/client/petstore/python/petstore_api/models/animal_farm.py @@ -81,6 +81,9 @@ class AnimalFarm(object): """ Returns true if both objects are equal """ + if not isinstance(other, AnimalFarm): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/api_response.py b/samples/client/petstore/python/petstore_api/models/api_response.py index 652c48b69b4..ba5c434abc7 100644 --- a/samples/client/petstore/python/petstore_api/models/api_response.py +++ b/samples/client/petstore/python/petstore_api/models/api_response.py @@ -151,6 +151,9 @@ class ApiResponse(object): """ Returns true if both objects are equal """ + if not isinstance(other, ApiResponse): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py index 64a9a2c0513..16c6345baad 100644 --- a/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py @@ -103,6 +103,9 @@ class ArrayOfArrayOfNumberOnly(object): """ Returns true if both objects are equal """ + if not isinstance(other, ArrayOfArrayOfNumberOnly): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python/petstore_api/models/array_of_number_only.py index 931ae9b1229..0db1d9591d5 100644 --- a/samples/client/petstore/python/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/models/array_of_number_only.py @@ -103,6 +103,9 @@ class ArrayOfNumberOnly(object): """ Returns true if both objects are equal """ + if not isinstance(other, ArrayOfNumberOnly): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/array_test.py b/samples/client/petstore/python/petstore_api/models/array_test.py index 36bceca687f..bd1858faa0d 100644 --- a/samples/client/petstore/python/petstore_api/models/array_test.py +++ b/samples/client/petstore/python/petstore_api/models/array_test.py @@ -151,6 +151,9 @@ class ArrayTest(object): """ Returns true if both objects are equal """ + if not isinstance(other, ArrayTest): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/capitalization.py b/samples/client/petstore/python/petstore_api/models/capitalization.py index e524d7604fd..b9030b5b76d 100644 --- a/samples/client/petstore/python/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python/petstore_api/models/capitalization.py @@ -225,6 +225,9 @@ class Capitalization(object): """ Returns true if both objects are equal """ + if not isinstance(other, Capitalization): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/cat.py b/samples/client/petstore/python/petstore_api/models/cat.py index c52594a9870..67cae27ae8a 100644 --- a/samples/client/petstore/python/petstore_api/models/cat.py +++ b/samples/client/petstore/python/petstore_api/models/cat.py @@ -153,6 +153,9 @@ class Cat(object): """ Returns true if both objects are equal """ + if not isinstance(other, Cat): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/category.py b/samples/client/petstore/python/petstore_api/models/category.py index 8a312c27094..2cdc9911d4e 100644 --- a/samples/client/petstore/python/petstore_api/models/category.py +++ b/samples/client/petstore/python/petstore_api/models/category.py @@ -127,6 +127,9 @@ class Category(object): """ Returns true if both objects are equal """ + if not isinstance(other, Category): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/class_model.py b/samples/client/petstore/python/petstore_api/models/class_model.py index dd08406c04b..cf93b27c760 100644 --- a/samples/client/petstore/python/petstore_api/models/class_model.py +++ b/samples/client/petstore/python/petstore_api/models/class_model.py @@ -103,6 +103,9 @@ class ClassModel(object): """ Returns true if both objects are equal """ + if not isinstance(other, ClassModel): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/client.py b/samples/client/petstore/python/petstore_api/models/client.py index 47a89b35729..2d572bfbeb2 100644 --- a/samples/client/petstore/python/petstore_api/models/client.py +++ b/samples/client/petstore/python/petstore_api/models/client.py @@ -103,6 +103,9 @@ class Client(object): """ Returns true if both objects are equal """ + if not isinstance(other, Client): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/dog.py b/samples/client/petstore/python/petstore_api/models/dog.py index 0a13575dfb8..fc1d1fbf30c 100644 --- a/samples/client/petstore/python/petstore_api/models/dog.py +++ b/samples/client/petstore/python/petstore_api/models/dog.py @@ -153,6 +153,9 @@ class Dog(object): """ Returns true if both objects are equal """ + if not isinstance(other, Dog): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/enum_arrays.py b/samples/client/petstore/python/petstore_api/models/enum_arrays.py index a9c96ef1bff..46b34bd41f7 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python/petstore_api/models/enum_arrays.py @@ -140,6 +140,9 @@ class EnumArrays(object): """ Returns true if both objects are equal """ + if not isinstance(other, EnumArrays): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/enum_class.py b/samples/client/petstore/python/petstore_api/models/enum_class.py index 792b6152a2b..45f6b0b4578 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python/petstore_api/models/enum_class.py @@ -81,6 +81,9 @@ class EnumClass(object): """ Returns true if both objects are equal """ + if not isinstance(other, EnumClass): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/enum_test.py b/samples/client/petstore/python/petstore_api/models/enum_test.py index 2769128794a..e3293425049 100644 --- a/samples/client/petstore/python/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python/petstore_api/models/enum_test.py @@ -67,7 +67,7 @@ class EnumTest(object): :param enum_string: The enum_string of this EnumTest. :type: str """ - allowed_values = ["UPPER", "lower"] + allowed_values = ["UPPER", "lower", ""] if enum_string not in allowed_values: raise ValueError( "Invalid value for `enum_string` ({0}), must be one of {1}" @@ -193,6 +193,9 @@ class EnumTest(object): """ Returns true if both objects are equal """ + if not isinstance(other, EnumTest): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/format_test.py b/samples/client/petstore/python/petstore_api/models/format_test.py index 1223bb1ea99..cde65b89a17 100644 --- a/samples/client/petstore/python/petstore_api/models/format_test.py +++ b/samples/client/petstore/python/petstore_api/models/format_test.py @@ -425,6 +425,9 @@ class FormatTest(object): """ Returns true if both objects are equal """ + if not isinstance(other, FormatTest): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python/petstore_api/models/has_only_read_only.py index fcad8f02d4b..c374793e617 100644 --- a/samples/client/petstore/python/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python/petstore_api/models/has_only_read_only.py @@ -127,6 +127,9 @@ class HasOnlyReadOnly(object): """ Returns true if both objects are equal """ + if not isinstance(other, HasOnlyReadOnly): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/list.py b/samples/client/petstore/python/petstore_api/models/list.py index 5e23577f213..f1393a4b6a3 100644 --- a/samples/client/petstore/python/petstore_api/models/list.py +++ b/samples/client/petstore/python/petstore_api/models/list.py @@ -103,6 +103,9 @@ class List(object): """ Returns true if both objects are equal """ + if not isinstance(other, List): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/map_test.py b/samples/client/petstore/python/petstore_api/models/map_test.py index 61f97136063..e6ece72af81 100644 --- a/samples/client/petstore/python/petstore_api/models/map_test.py +++ b/samples/client/petstore/python/petstore_api/models/map_test.py @@ -134,6 +134,9 @@ class MapTest(object): """ Returns true if both objects are equal """ + if not isinstance(other, MapTest): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py index bdfa6721fb7..ee9b1e641e4 100644 --- a/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -151,6 +151,9 @@ class MixedPropertiesAndAdditionalPropertiesClass(object): """ Returns true if both objects are equal """ + if not isinstance(other, MixedPropertiesAndAdditionalPropertiesClass): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/model_200_response.py b/samples/client/petstore/python/petstore_api/models/model_200_response.py index ea332d78a59..73b6dccc050 100644 --- a/samples/client/petstore/python/petstore_api/models/model_200_response.py +++ b/samples/client/petstore/python/petstore_api/models/model_200_response.py @@ -127,6 +127,9 @@ class Model200Response(object): """ Returns true if both objects are equal """ + if not isinstance(other, Model200Response): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/model_return.py b/samples/client/petstore/python/petstore_api/models/model_return.py index 472c733793a..d99df7402b0 100644 --- a/samples/client/petstore/python/petstore_api/models/model_return.py +++ b/samples/client/petstore/python/petstore_api/models/model_return.py @@ -103,6 +103,9 @@ class ModelReturn(object): """ Returns true if both objects are equal """ + if not isinstance(other, ModelReturn): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/name.py b/samples/client/petstore/python/petstore_api/models/name.py index f2ea96a04fe..af281208f7a 100644 --- a/samples/client/petstore/python/petstore_api/models/name.py +++ b/samples/client/petstore/python/petstore_api/models/name.py @@ -177,6 +177,9 @@ class Name(object): """ Returns true if both objects are equal """ + if not isinstance(other, Name): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/number_only.py b/samples/client/petstore/python/petstore_api/models/number_only.py index 7b471e980d2..48fea068509 100644 --- a/samples/client/petstore/python/petstore_api/models/number_only.py +++ b/samples/client/petstore/python/petstore_api/models/number_only.py @@ -103,6 +103,9 @@ class NumberOnly(object): """ Returns true if both objects are equal """ + if not isinstance(other, NumberOnly): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/order.py b/samples/client/petstore/python/petstore_api/models/order.py index fa8c7b8c750..d0ed63cd482 100644 --- a/samples/client/petstore/python/petstore_api/models/order.py +++ b/samples/client/petstore/python/petstore_api/models/order.py @@ -231,6 +231,9 @@ class Order(object): """ Returns true if both objects are equal """ + if not isinstance(other, Order): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/outer_enum.py b/samples/client/petstore/python/petstore_api/models/outer_enum.py index d86b2a3c03f..8c732caee81 100644 --- a/samples/client/petstore/python/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python/petstore_api/models/outer_enum.py @@ -81,6 +81,9 @@ class OuterEnum(object): """ Returns true if both objects are equal """ + if not isinstance(other, OuterEnum): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/pet.py b/samples/client/petstore/python/petstore_api/models/pet.py index 11f84a0f609..7dea8afd1b2 100644 --- a/samples/client/petstore/python/petstore_api/models/pet.py +++ b/samples/client/petstore/python/petstore_api/models/pet.py @@ -235,6 +235,9 @@ class Pet(object): """ Returns true if both objects are equal """ + if not isinstance(other, Pet): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/read_only_first.py b/samples/client/petstore/python/petstore_api/models/read_only_first.py index 4316ec0911f..2b1dfda420c 100644 --- a/samples/client/petstore/python/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python/petstore_api/models/read_only_first.py @@ -127,6 +127,9 @@ class ReadOnlyFirst(object): """ Returns true if both objects are equal """ + if not isinstance(other, ReadOnlyFirst): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/special_model_name.py b/samples/client/petstore/python/petstore_api/models/special_model_name.py index 3a133e2534b..651c51e8e56 100644 --- a/samples/client/petstore/python/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python/petstore_api/models/special_model_name.py @@ -103,6 +103,9 @@ class SpecialModelName(object): """ Returns true if both objects are equal """ + if not isinstance(other, SpecialModelName): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/tag.py b/samples/client/petstore/python/petstore_api/models/tag.py index e0067308f99..4bd6bfedfb6 100644 --- a/samples/client/petstore/python/petstore_api/models/tag.py +++ b/samples/client/petstore/python/petstore_api/models/tag.py @@ -127,6 +127,9 @@ class Tag(object): """ Returns true if both objects are equal """ + if not isinstance(other, Tag): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/python/petstore_api/models/user.py b/samples/client/petstore/python/petstore_api/models/user.py index 3d84d068d12..ed3af1ce20d 100644 --- a/samples/client/petstore/python/petstore_api/models/user.py +++ b/samples/client/petstore/python/petstore_api/models/user.py @@ -273,6 +273,9 @@ class User(object): """ Returns true if both objects are equal """ + if not isinstance(other, User): + return False + return self.__dict__ == other.__dict__ def __ne__(self, other): diff --git a/samples/client/petstore/qt5cpp/client/Order.cpp b/samples/client/petstore/qt5cpp/client/Order.cpp index aa396c44f60..e9eb3bc2430 100644 --- a/samples/client/petstore/qt5cpp/client/Order.cpp +++ b/samples/client/petstore/qt5cpp/client/Order.cpp @@ -74,9 +74,9 @@ Order::fromJson(QString &json) { void Order::fromJsonObject(QJsonObject &pJson) { ::Swagger::setValue(&id, pJson["id"], "qint64", ""); - ::Swagger::setValue(&pet_id, pJson["pet_id"], "qint64", ""); + ::Swagger::setValue(&pet_id, pJson["petId"], "qint64", ""); ::Swagger::setValue(&quantity, pJson["quantity"], "qint32", ""); - ::Swagger::setValue(&ship_date, pJson["ship_date"], "QDateTime", "QDateTime"); + ::Swagger::setValue(&ship_date, pJson["shipDate"], "QDateTime", "QDateTime"); ::Swagger::setValue(&status, pJson["status"], "QString", "QString"); ::Swagger::setValue(&complete, pJson["complete"], "bool", ""); } @@ -97,11 +97,11 @@ Order::asJsonObject() { obj->insert("id", QJsonValue(id)); - obj->insert("pet_id", QJsonValue(pet_id)); + obj->insert("petId", QJsonValue(pet_id)); obj->insert("quantity", QJsonValue(quantity)); - toJsonValue(QString("ship_date"), ship_date, obj, QString("QDateTime")); + toJsonValue(QString("shipDate"), ship_date, obj, QString("QDateTime")); toJsonValue(QString("status"), status, obj, QString("QString")); diff --git a/samples/client/petstore/qt5cpp/client/Pet.cpp b/samples/client/petstore/qt5cpp/client/Pet.cpp index a1f1090afae..f78cac3eb6c 100644 --- a/samples/client/petstore/qt5cpp/client/Pet.cpp +++ b/samples/client/petstore/qt5cpp/client/Pet.cpp @@ -94,7 +94,7 @@ Pet::fromJsonObject(QJsonObject &pJson) { ::Swagger::setValue(&category, pJson["category"], "Category", "Category"); ::Swagger::setValue(&name, pJson["name"], "QString", "QString"); - ::Swagger::setValue(&photo_urls, pJson["photo_urls"], "QList", "QString"); + ::Swagger::setValue(&photo_urls, pJson["photoUrls"], "QList", "QString"); ::Swagger::setValue(&tags, pJson["tags"], "QList", "Tag"); @@ -124,7 +124,7 @@ Pet::asJsonObject() { QJsonArray photo_urlsJsonArray; toJsonArray((QList*)photo_urls, &photo_urlsJsonArray, "photo_urls", "QString"); - obj->insert("photo_urls", photo_urlsJsonArray); + obj->insert("photoUrls", photo_urlsJsonArray); QJsonArray tagsJsonArray; toJsonArray((QList*)tags, &tagsJsonArray, "tags", "Tag"); diff --git a/samples/client/petstore/qt5cpp/client/User.cpp b/samples/client/petstore/qt5cpp/client/User.cpp index 89f149376a0..d988ab195b6 100644 --- a/samples/client/petstore/qt5cpp/client/User.cpp +++ b/samples/client/petstore/qt5cpp/client/User.cpp @@ -91,12 +91,12 @@ void User::fromJsonObject(QJsonObject &pJson) { ::Swagger::setValue(&id, pJson["id"], "qint64", ""); ::Swagger::setValue(&username, pJson["username"], "QString", "QString"); - ::Swagger::setValue(&first_name, pJson["first_name"], "QString", "QString"); - ::Swagger::setValue(&last_name, pJson["last_name"], "QString", "QString"); + ::Swagger::setValue(&first_name, pJson["firstName"], "QString", "QString"); + ::Swagger::setValue(&last_name, pJson["lastName"], "QString", "QString"); ::Swagger::setValue(&email, pJson["email"], "QString", "QString"); ::Swagger::setValue(&password, pJson["password"], "QString", "QString"); ::Swagger::setValue(&phone, pJson["phone"], "QString", "QString"); - ::Swagger::setValue(&user_status, pJson["user_status"], "qint32", ""); + ::Swagger::setValue(&user_status, pJson["userStatus"], "qint32", ""); } QString @@ -117,9 +117,9 @@ User::asJsonObject() { toJsonValue(QString("username"), username, obj, QString("QString")); - toJsonValue(QString("first_name"), first_name, obj, QString("QString")); + toJsonValue(QString("firstName"), first_name, obj, QString("QString")); - toJsonValue(QString("last_name"), last_name, obj, QString("QString")); + toJsonValue(QString("lastName"), last_name, obj, QString("QString")); toJsonValue(QString("email"), email, obj, QString("QString")); @@ -127,7 +127,7 @@ User::asJsonObject() { toJsonValue(QString("phone"), phone, obj, QString("QString")); - obj->insert("user_status", QJsonValue(user_status)); + obj->insert("userStatus", QJsonValue(user_status)); return obj; } diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 2789989c589..83eb4707284 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -109,6 +109,7 @@ Class | Method | HTTP request | Description - [Petstore::ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [Petstore::ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [Petstore::ArrayTest](docs/ArrayTest.md) + - [Petstore::Capitalization](docs/Capitalization.md) - [Petstore::Cat](docs/Cat.md) - [Petstore::Category](docs/Category.md) - [Petstore::ClassModel](docs/ClassModel.md) diff --git a/samples/client/petstore/ruby/docs/Capitalization.md b/samples/client/petstore/ruby/docs/Capitalization.md new file mode 100644 index 00000000000..d99c603f54a --- /dev/null +++ b/samples/client/petstore/ruby/docs/Capitalization.md @@ -0,0 +1,13 @@ +# Petstore::Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**small_camel** | **String** | | [optional] +**capital_camel** | **String** | | [optional] +**small_snake** | **String** | | [optional] +**capital_snake** | **String** | | [optional] +**sca_eth_flow_points** | **String** | | [optional] +**att_name** | **String** | Name of the pet | [optional] + + diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 6999fac514b..5644d820a27 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -23,6 +23,7 @@ require 'petstore/models/api_response' require 'petstore/models/array_of_array_of_number_only' require 'petstore/models/array_of_number_only' require 'petstore/models/array_test' +require 'petstore/models/capitalization' require 'petstore/models/cat' require 'petstore/models/category' require 'petstore/models/class_model' 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 403705d2746..481004db585 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -145,20 +145,20 @@ module Petstore # verify the required parameter 'byte' is set fail ArgumentError, "Missing the required parameter 'byte' when calling FakeApi.test_endpoint_parameters" if byte.nil? - if !opts[:'integer'].nil? && opts[:'integer'] > 100 - fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 100.' + if !opts[:'integer'].nil? && opts[:'integer'] > 100.0 + fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 100.0.' end - if !opts[:'integer'].nil? && opts[:'integer'] < 10 - fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 10.' + if !opts[:'integer'].nil? && opts[:'integer'] < 10.0 + fail ArgumentError, 'invalid value for "opts[:"integer"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 10.0.' end - if !opts[:'int32'].nil? && opts[:'int32'] > 200 - fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 200.' + if !opts[:'int32'].nil? && opts[:'int32'] > 200.0 + fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be smaller than or equal to 200.0.' end - if !opts[:'int32'].nil? && opts[:'int32'] < 20 - fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 20.' + if !opts[:'int32'].nil? && opts[:'int32'] < 20.0 + fail ArgumentError, 'invalid value for "opts[:"int32"]" when calling FakeApi.test_endpoint_parameters, must be greater than or equal to 20.0.' end if !opts[:'float'].nil? && opts[:'float'] > 987.6 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 78755496444..39d5490b787 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -40,10 +40,6 @@ module Petstore end # verify the required parameter 'order_id' is set fail ArgumentError, "Missing the required parameter 'order_id' when calling StoreApi.delete_order" if order_id.nil? - if order_id < 1.0 - fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.delete_order, must be greater than or equal to 1.0.' - end - # resource path local_var_path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) @@ -141,12 +137,12 @@ module Petstore end # verify the required parameter 'order_id' is set fail ArgumentError, "Missing the required parameter 'order_id' when calling StoreApi.get_order_by_id" if order_id.nil? - if order_id > 5 - fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be smaller than or equal to 5.' + if order_id > 5.0 + fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be smaller than or equal to 5.0.' end - if order_id < 1 - fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be greater than or equal to 1.' + if order_id < 1.0 + fail ArgumentError, 'invalid value for "order_id" when calling StoreApi.get_order_by_id, must be greater than or equal to 1.0.' end # resource path diff --git a/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb b/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb new file mode 100644 index 00000000000..9dfd19523ea --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb @@ -0,0 +1,233 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end + +require 'date' + +module Petstore + + class Capitalization + attr_accessor :small_camel + + attr_accessor :capital_camel + + attr_accessor :small_snake + + attr_accessor :capital_snake + + attr_accessor :sca_eth_flow_points + + # Name of the pet + attr_accessor :att_name + + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'small_camel' => :'smallCamel', + :'capital_camel' => :'CapitalCamel', + :'small_snake' => :'small_Snake', + :'capital_snake' => :'Capital_Snake', + :'sca_eth_flow_points' => :'SCA_ETH_Flow_Points', + :'att_name' => :'ATT_NAME' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'small_camel' => :'String', + :'capital_camel' => :'String', + :'small_snake' => :'String', + :'capital_snake' => :'String', + :'sca_eth_flow_points' => :'String', + :'att_name' => :'String' + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + if attributes.has_key?(:'smallCamel') + self.small_camel = attributes[:'smallCamel'] + end + + if attributes.has_key?(:'CapitalCamel') + self.capital_camel = attributes[:'CapitalCamel'] + end + + if attributes.has_key?(:'small_Snake') + self.small_snake = attributes[:'small_Snake'] + end + + if attributes.has_key?(:'Capital_Snake') + self.capital_snake = attributes[:'Capital_Snake'] + end + + if attributes.has_key?(:'SCA_ETH_Flow_Points') + self.sca_eth_flow_points = attributes[:'SCA_ETH_Flow_Points'] + end + + if attributes.has_key?(:'ATT_NAME') + self.att_name = attributes[:'ATT_NAME'] + end + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + return true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + small_camel == o.small_camel && + capital_camel == o.capital_camel && + small_snake == o.small_snake && + capital_snake == o.capital_snake && + sca_eth_flow_points == o.sca_eth_flow_points && + att_name == o.att_name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [small_camel, capital_camel, small_snake, capital_snake, sca_eth_flow_points, att_name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb index d8efd0acd22..c57cac73b59 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -100,7 +100,7 @@ module Petstore # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? - enum_string_validator = EnumAttributeValidator.new('String', ["UPPER", "lower"]) + enum_string_validator = EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) return false unless enum_string_validator.valid?(@enum_string) enum_integer_validator = EnumAttributeValidator.new('Integer', ["1", "-1"]) return false unless enum_integer_validator.valid?(@enum_integer) @@ -112,7 +112,7 @@ module Petstore # Custom attribute writer method checking allowed values (enum). # @param [Object] enum_string Object to be assigned def enum_string=(enum_string) - validator = EnumAttributeValidator.new('String', ["UPPER", "lower"]) + validator = EnumAttributeValidator.new('String', ["UPPER", "lower", ""]) unless validator.valid?(enum_string) fail ArgumentError, "invalid value for 'enum_string', must be one of #{validator.allowable_values}." end diff --git a/samples/client/petstore/ruby/spec/models/capitalization_spec.rb b/samples/client/petstore/ruby/spec/models/capitalization_spec.rb new file mode 100644 index 00000000000..372405eb7cd --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/capitalization_spec.rb @@ -0,0 +1,71 @@ +=begin +#Swagger Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Capitalization +# Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) +# Please update as you see appropriate +describe 'Capitalization' do + before do + # run before each test + @instance = Petstore::Capitalization.new + end + + after do + # run after each test + end + + describe 'test an instance of Capitalization' do + it 'should create an instact of Capitalization' do + expect(@instance).to be_instance_of(Petstore::Capitalization) + end + end + describe 'test attribute "small_camel"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "capital_camel"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "small_snake"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "capital_snake"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "sca_eth_flow_points"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + + describe 'test attribute "att_name"' do + it 'should work' do + # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers + end + end + +end + diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala index 776c0844550..3bcadab73c9 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -148,7 +148,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) + Some(apiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) case _ => None } } catch { @@ -190,7 +190,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) + Some(apiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) case _ => None } } catch { @@ -229,7 +229,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[Pet]).asInstanceOf[Pet]) + Some(apiInvoker.deserialize(s, "", classOf[Pet]).asInstanceOf[Pet]) case _ => None } } catch { @@ -358,7 +358,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[ApiResponse]).asInstanceOf[ApiResponse]) + Some(apiInvoker.deserialize(s, "", classOf[ApiResponse]).asInstanceOf[ApiResponse]) case _ => None } } catch { diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala index 4514108bd77..3f72757f9eb 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -102,7 +102,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "map", classOf[Integer]).asInstanceOf[Map[String, Integer]]) + Some(apiInvoker.deserialize(s, "map", classOf[Integer]).asInstanceOf[Map[String, Integer]]) case _ => None } } catch { @@ -141,7 +141,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) + Some(apiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) case _ => None } } catch { @@ -182,7 +182,7 @@ class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) + Some(apiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) case _ => None } } catch { diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala index 441337d1759..df039c1f7cc 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -225,7 +225,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) + Some(apiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) case _ => None } } catch { @@ -271,7 +271,7 @@ class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[String]).asInstanceOf[String]) + Some(apiInvoker.deserialize(s, "", classOf[String]).asInstanceOf[String]) case _ => None } } catch { diff --git a/samples/client/petstore/spring-cloud/pom.xml b/samples/client/petstore/spring-cloud/pom.xml index 0d47370910a..722574a2f1c 100644 --- a/samples/client/petstore/spring-cloud/pom.xml +++ b/samples/client/petstore/spring-cloud/pom.xml @@ -56,10 +56,17 @@ jackson-datatype-threetenbp 2.6.4 + + + javax.validation + validation-api + 1.1.0.Final + provided + org.springframework.boot spring-boot-starter-test test - \ No newline at end of file + diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java index 49a2c91817e..6a3e9b8eeb3 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/PetApi.java @@ -16,7 +16,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "Pet", description = "the Pet API") public interface PetApi { @@ -65,7 +65,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - com.netflix.hystrix.HystrixCommand>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); + com.netflix.hystrix.HystrixCommand>> findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -81,7 +81,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - com.netflix.hystrix.HystrixCommand>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + com.netflix.hystrix.HystrixCommand>> findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java index 393b9b69108..49e70ead367 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/StoreApi.java @@ -15,7 +15,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "Store", description = "the Store API") public interface StoreApi { @@ -52,7 +52,7 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - com.netflix.hystrix.HystrixCommand> getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + com.netflix.hystrix.HystrixCommand> getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java index 1ecef6bfecb..4fa2b81aa6a 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/api/UserApi.java @@ -15,7 +15,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "User", description = "the User API") public interface UserApi { @@ -81,8 +81,8 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - com.netflix.hystrix.HystrixCommand> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + com.netflix.hystrix.HystrixCommand> loginUser( @NotNull @ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java index 3c8cf28ec23..9611305a687 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Category.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * A category for a pet */ diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java index 6d6641bfe9a..63561b90939 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/ModelApiResponse.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Describes the result of uploading an image resource */ diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java index 7993abb951a..c8db6b95510 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.threeten.bp.OffsetDateTime; - +import javax.validation.constraints.*; /** * An order for a pets from the pet store */ diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java index 5cdfc19b38e..bab3ea4ec20 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Pet.java @@ -10,7 +10,7 @@ import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * A pet for sale in the pet store */ @@ -114,6 +114,7 @@ public class Pet { * @return name **/ @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull public String getName() { return name; } @@ -137,6 +138,7 @@ public class Pet { * @return photoUrls **/ @ApiModelProperty(required = true, value = "") + @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java index 7fd1757b21c..f363f8d9f86 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/Tag.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * A tag for a pet */ diff --git a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java index f14694154b4..1766e5dde17 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java +++ b/samples/client/petstore/spring-cloud/src/main/java/io/swagger/model/User.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * A User who is purchasing from the pet store */ diff --git a/samples/client/petstore/spring-stubs/pom.xml b/samples/client/petstore/spring-stubs/pom.xml index 570b33f5a25..52faa280169 100644 --- a/samples/client/petstore/spring-stubs/pom.xml +++ b/samples/client/petstore/spring-stubs/pom.xml @@ -46,5 +46,12 @@ jackson-datatype-threetenbp 2.6.4 + + + javax.validation + validation-api + 1.1.0.Final + provided + - \ No newline at end of file + diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java index 735c9548bcc..2b6bb97460c 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/PetApi.java @@ -16,7 +16,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "pet", description = "the pet API") public interface PetApi { @@ -65,7 +65,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); + ResponseEntity> findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -81,7 +81,7 @@ public interface PetApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + ResponseEntity> findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java index 1eb724e96c9..de152b505c0 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/StoreApi.java @@ -15,7 +15,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "store", description = "the store API") public interface StoreApi { @@ -52,7 +52,7 @@ public interface StoreApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java index e212a819908..28c184dabd1 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/api/UserApi.java @@ -15,7 +15,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "user", description = "the user API") public interface UserApi { @@ -81,8 +81,8 @@ public interface UserApi { produces = "application/json", consumes = "application/json", method = RequestMethod.GET) - ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + ResponseEntity loginUser( @NotNull @ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java index 3c8cf28ec23..9611305a687 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Category.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * A category for a pet */ diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java index 6d6641bfe9a..63561b90939 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/ModelApiResponse.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Describes the result of uploading an image resource */ diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java index 7993abb951a..c8db6b95510 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.threeten.bp.OffsetDateTime; - +import javax.validation.constraints.*; /** * An order for a pets from the pet store */ diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java index 5cdfc19b38e..bab3ea4ec20 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Pet.java @@ -10,7 +10,7 @@ import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * A pet for sale in the pet store */ @@ -114,6 +114,7 @@ public class Pet { * @return name **/ @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull public String getName() { return name; } @@ -137,6 +138,7 @@ public class Pet { * @return photoUrls **/ @ApiModelProperty(required = true, value = "") + @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java index 7fd1757b21c..f363f8d9f86 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/Tag.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * A tag for a pet */ diff --git a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java index f14694154b4..1766e5dde17 100644 --- a/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java +++ b/samples/client/petstore/spring-stubs/src/main/java/io/swagger/model/User.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * A User who is purchasing from the pet store */ diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIHelper.swift index 23e727b6b54..b91cd27851a 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -19,6 +19,16 @@ class APIHelper { return destination } + static func rejectNilHeaders(source: [String:AnyObject?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { guard let source = source else { return nil diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift index ab0ea147e4f..55d7017c456 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs.swift @@ -31,7 +31,7 @@ public class APIBase { public class RequestBuilder { var credential: NSURLCredential? - var headers: [String:String] = [:] + var headers: [String:String] let parameters: [String:AnyObject]? let isBody: Bool let method: String @@ -40,11 +40,12 @@ public class RequestBuilder { /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((NSProgress) -> ())? - required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool, headers: [String:String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody + self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 06789661504..5e5f0df315f 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -51,10 +51,11 @@ public class PetAPI: APIBase { Deletes a pet - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - public class func deletePet(petId petId: Int64, completion: ((error: ErrorType?) -> Void)) { - deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + public class func deletePet(petId petId: Int64, apiKey: String? = nil, completion: ((error: ErrorType?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in completion(error: error); } } @@ -69,10 +70,11 @@ public class PetAPI: APIBase { - name: petstore_auth - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - returns: RequestBuilder */ - public class func deletePetWithRequestBuilder(petId petId: Int64) -> RequestBuilder { + public class func deletePetWithRequestBuilder(petId petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let URLString = PetstoreClientAPI.basePath + path @@ -82,10 +84,14 @@ public class PetAPI: APIBase { let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) + let nillableHeaders: [String: AnyObject?] = [ + "api_key": apiKey + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true, headers: headerParameters) } /** @@ -108,13 +114,13 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ + - examples: [{contentType=application/json, example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}, contentType=application/json}] +}}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -157,20 +163,20 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -179,21 +185,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -202,7 +208,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter tags: (query) Tags to filter by (optional) @@ -242,26 +248,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - API Key: - - type: apiKey api_key - - name: api_key - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -270,21 +276,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -293,7 +299,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 1c575eb79f8..10c878314e7 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -67,12 +67,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - - examples: [{example={ +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@6e901cd0}] + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@6e901cd0}] - returns: RequestBuilder<[String:Int32]> */ @@ -108,36 +108,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -176,36 +176,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index a7497487f85..d6df7754683 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -167,16 +167,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -185,17 +185,17 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}] + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -204,7 +204,7 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] +}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -244,8 +244,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) diff --git a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 4ea47d8926c..66971688891 100644 --- a/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -41,8 +41,8 @@ public struct SynchronizedDictionary { private var managerStore = SynchronizedDictionary() class AlamofireRequestBuilder: RequestBuilder { - required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { - super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift index 23e727b6b54..b91cd27851a 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -19,6 +19,16 @@ class APIHelper { return destination } + static func rejectNilHeaders(source: [String:AnyObject?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { guard let source = source else { return nil diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift index ab0ea147e4f..55d7017c456 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift @@ -31,7 +31,7 @@ public class APIBase { public class RequestBuilder { var credential: NSURLCredential? - var headers: [String:String] = [:] + var headers: [String:String] let parameters: [String:AnyObject]? let isBody: Bool let method: String @@ -40,11 +40,12 @@ public class RequestBuilder { /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((NSProgress) -> ())? - required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool, headers: [String:String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody + self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index de181fba33f..b4cd67db8d2 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -69,10 +69,11 @@ public class PetAPI: APIBase { Deletes a pet - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - public class func deletePet(petId petId: Int64, completion: ((error: ErrorType?) -> Void)) { - deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + public class func deletePet(petId petId: Int64, apiKey: String? = nil, completion: ((error: ErrorType?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in completion(error: error); } } @@ -81,11 +82,12 @@ public class PetAPI: APIBase { Deletes a pet - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - returns: Promise */ - public class func deletePet(petId petId: Int64) -> Promise { + public class func deletePet(petId petId: Int64, apiKey: String? = nil) -> Promise { let deferred = Promise.pendingPromise() - deletePet(petId: petId) { error in + deletePet(petId: petId, apiKey: apiKey) { error in if let error = error { deferred.reject(error) } else { @@ -104,10 +106,11 @@ public class PetAPI: APIBase { - name: petstore_auth - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - returns: RequestBuilder */ - public class func deletePetWithRequestBuilder(petId petId: Int64) -> RequestBuilder { + public class func deletePetWithRequestBuilder(petId petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let URLString = PetstoreClientAPI.basePath + path @@ -117,10 +120,14 @@ public class PetAPI: APIBase { let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) + let nillableHeaders: [String: AnyObject?] = [ + "api_key": apiKey + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true, headers: headerParameters) } /** @@ -160,13 +167,13 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ + - examples: [{contentType=application/json, example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}, contentType=application/json}] +}}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -226,20 +233,20 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -248,21 +255,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -271,7 +278,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter tags: (query) Tags to filter by (optional) @@ -328,26 +335,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - API Key: - - type: apiKey api_key - - name: api_key - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -356,21 +363,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -379,7 +386,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 8736f9ee2e0..75b33b2fd0f 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -101,12 +101,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - - examples: [{example={ +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@6e901cd0}] + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@6e901cd0}] - returns: RequestBuilder<[String:Int32]> */ @@ -159,36 +159,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -244,36 +244,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 1b5ada9da67..98afec0c80a 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -253,16 +253,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -271,17 +271,17 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}] + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -290,7 +290,7 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] +}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -348,8 +348,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) diff --git a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 4ea47d8926c..66971688891 100644 --- a/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -41,8 +41,8 @@ public struct SynchronizedDictionary { private var managerStore = SynchronizedDictionary() class AlamofireRequestBuilder: RequestBuilder { - required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { - super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift index 23e727b6b54..b91cd27851a 100644 --- a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -19,6 +19,16 @@ class APIHelper { return destination } + static func rejectNilHeaders(source: [String:AnyObject?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { guard let source = source else { return nil diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift index ab0ea147e4f..55d7017c456 100644 --- a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift @@ -31,7 +31,7 @@ public class APIBase { public class RequestBuilder { var credential: NSURLCredential? - var headers: [String:String] = [:] + var headers: [String:String] let parameters: [String:AnyObject]? let isBody: Bool let method: String @@ -40,11 +40,12 @@ public class RequestBuilder { /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((NSProgress) -> ())? - required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool, headers: [String:String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody + self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index aa63f4b0df5..971771918ae 100644 --- a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -71,10 +71,11 @@ public class PetAPI: APIBase { Deletes a pet - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - public class func deletePet(petId petId: Int64, completion: ((error: ErrorType?) -> Void)) { - deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + public class func deletePet(petId petId: Int64, apiKey: String? = nil, completion: ((error: ErrorType?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in completion(error: error); } } @@ -83,11 +84,12 @@ public class PetAPI: APIBase { Deletes a pet - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - returns: Observable */ - public class func deletePet(petId petId: Int64) -> Observable { + public class func deletePet(petId petId: Int64, apiKey: String? = nil) -> Observable { return Observable.create { observer -> Disposable in - deletePet(petId: petId) { error in + deletePet(petId: petId, apiKey: apiKey) { error in if let error = error { observer.on(.Error(error as ErrorType)) } else { @@ -108,10 +110,11 @@ public class PetAPI: APIBase { - name: petstore_auth - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - returns: RequestBuilder */ - public class func deletePetWithRequestBuilder(petId petId: Int64) -> RequestBuilder { + public class func deletePetWithRequestBuilder(petId petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let URLString = PetstoreClientAPI.basePath + path @@ -121,10 +124,14 @@ public class PetAPI: APIBase { let parameters = APIHelper.rejectNil(nillableParameters) let convertedParameters = APIHelper.convertBoolToString(parameters) + let nillableHeaders: [String: AnyObject?] = [ + "api_key": apiKey + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true, headers: headerParameters) } /** @@ -166,13 +173,13 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ + - examples: [{contentType=application/json, example={ "name" : "Puma", "type" : "Dog", "color" : "Black", "gender" : "Female", "breed" : "Mixed" -}, contentType=application/json}] +}}] - parameter status: (query) Status values that need to be considered for filter (optional, default to available) @@ -234,20 +241,20 @@ public class PetAPI: APIBase { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -256,21 +263,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example=[ { - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example=[ { + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -} ], contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +} ]}, {contentType=application/xml, example= 123456 doggie @@ -279,7 +286,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter tags: (query) Tags to filter by (optional) @@ -338,26 +345,26 @@ public class PetAPI: APIBase { Find pet by ID - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - API Key: - - type: apiKey api_key - - name: api_key - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -366,21 +373,21 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] - - examples: [{example={ - "tags" : [ { - "id" : 123456789, - "name" : "aeiou" - } ], +}] + - examples: [{contentType=application/json, example={ + "photoUrls" : [ "aeiou" ], + "name" : "doggie", "id" : 123456789, "category" : { - "id" : 123456789, - "name" : "aeiou" + "name" : "aeiou", + "id" : 123456789 }, - "status" : "aeiou", - "name" : "doggie", - "photoUrls" : [ "aeiou" ] -}, contentType=application/json}, {example= + "tags" : [ { + "name" : "aeiou", + "id" : 123456789 + } ], + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 doggie @@ -389,7 +396,7 @@ public class PetAPI: APIBase { string -, contentType=application/xml}] +}] - parameter petId: (path) ID of pet that needs to be fetched diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index d7562019b4e..5a0fff19e52 100644 --- a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -105,12 +105,12 @@ public class StoreAPI: APIBase { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={ + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] - - examples: [{example={ +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@6e901cd0}] + - examples: [{contentType=application/json, example={ "key" : 123 -}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@d1e580af, contentType=application/xml}] +}}, {contentType=application/xml, example=not implemented io.swagger.models.properties.MapProperty@6e901cd0}] - returns: RequestBuilder<[String:Int32]> */ @@ -165,36 +165,36 @@ public class StoreAPI: APIBase { Find purchase order by ID - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter orderId: (path) ID of pet that needs to be fetched @@ -252,36 +252,36 @@ public class StoreAPI: APIBase { Place an order for a pet - POST /store/order - - - examples: [{example={ - "id" : 123456789, + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, +}] + - examples: [{contentType=application/json, example={ "petId" : 123456789, - "complete" : true, - "status" : "aeiou", "quantity" : 123, - "shipDate" : "2000-01-23T04:56:07.000+00:00" -}, contentType=application/json}, {example= + "id" : 123456789, + "shipDate" : "2000-01-23T04:56:07.000+00:00", + "complete" : true, + "status" : "aeiou" +}}, {contentType=application/xml, example= 123456 123456 0 2000-01-23T04:56:07.000Z string true -, contentType=application/xml}] +}] - parameter body: (body) order placed for purchasing the pet (optional) diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index ecae72665b9..0dbc4e7b340 100644 --- a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -263,16 +263,16 @@ public class UserAPI: APIBase { Get user by user name - GET /user/{username} - - - examples: [{example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -281,17 +281,17 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] - - examples: [{example={ - "id" : 123456789, - "lastName" : "aeiou", - "phone" : "aeiou", - "username" : "aeiou", - "email" : "aeiou", - "userStatus" : 123, +}] + - examples: [{contentType=application/json, example={ "firstName" : "aeiou", - "password" : "aeiou" -}, contentType=application/json}, {example= + "lastName" : "aeiou", + "password" : "aeiou", + "userStatus" : 123, + "phone" : "aeiou", + "id" : 123456789, + "email" : "aeiou", + "username" : "aeiou" +}}, {contentType=application/xml, example= 123456 string string @@ -300,7 +300,7 @@ public class UserAPI: APIBase { string string 0 -, contentType=application/xml}] +}] - parameter username: (path) The name that needs to be fetched. Use user1 for testing. @@ -360,8 +360,8 @@ public class UserAPI: APIBase { Logs user into the system - GET /user/login - - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] - - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] + - examples: [{contentType=application/json, example="aeiou"}, {contentType=application/xml, example=string}] - parameter username: (query) The user name for login (optional) - parameter password: (query) The password for login in clear text (optional) diff --git a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 4ea47d8926c..66971688891 100644 --- a/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -41,8 +41,8 @@ public struct SynchronizedDictionary { private var managerStore = SynchronizedDictionary() class AlamofireRequestBuilder: RequestBuilder { - required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { - super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift index 967dcc34735..b612ff90921 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -21,6 +21,16 @@ class APIHelper { return destination } + static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { guard let source = source else { return nil @@ -39,4 +49,17 @@ class APIHelper { return destination } + + static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { + let returnValues = values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + if returnValues.count == 0 { + return nil + } + return returnValues + } + } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs.swift index 2b7eb3003e4..e23fc13395f 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs.swift @@ -31,7 +31,7 @@ open class APIBase { open class RequestBuilder { var credential: URLCredential? - var headers: [String:String] = [:] + var headers: [String:String] let parameters: [String:Any]? let isBody: Bool let method: String @@ -40,11 +40,12 @@ open class RequestBuilder { /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? - required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool) { + required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody + self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 5b25be13088..c928a1bd293 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -39,12 +39,13 @@ open class FakeAPI: APIBase { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -101,8 +102,7 @@ open class FakeAPI: APIBase { open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: ISOFullDate? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -118,14 +118,16 @@ open class FakeAPI: APIBase { "password": password, "callback": callback ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -145,6 +147,23 @@ open class FakeAPI: APIBase { case xyz = "(xyz)" } + /** + * enum for parameter enumHeaderStringArray + */ + public enum EnumHeaderStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumHeaderString + */ + public enum EnumHeaderString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + /** * enum for parameter enumQueryStringArray */ @@ -167,14 +186,16 @@ open class FakeAPI: APIBase { - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - 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: (form) Query parameter enum test (double) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { - testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in completion(error); } } @@ -187,6 +208,8 @@ open class FakeAPI: APIBase { - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - 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) @@ -194,23 +217,34 @@ open class FakeAPI: APIBase { - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ - "enum_query_string_array": enumQueryStringArray, - "enum_query_string": enumQueryString?.rawValue, - "enum_query_integer": enumQueryInteger?.encodeToJSON() + let formParams: [String:Any?] = [ + "enum_form_string_array": enumFormStringArray, + "enum_form_string": enumFormString?.rawValue, + "enum_query_double": enumQueryDouble ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "enum_query_string_array": enumQueryStringArray, + "enum_query_string": enumQueryString?.rawValue, + "enum_query_integer": enumQueryInteger?.encodeToJSON() + ]) + + let nillableHeaders: [String: Any?] = [ + "enum_header_string_array": enumHeaderStringArray, + "enum_header_string": enumHeaderString?.rawValue + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) } } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift index 68104903f50..a9eea5f47ed 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift @@ -38,12 +38,13 @@ open class Fake_classname_tags123API: APIBase { let path = "/fake_classname_test" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index e5efa2337eb..efef8693f78 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -39,22 +39,24 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** Deletes a pet - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { - deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in completion(error); } } @@ -69,23 +71,26 @@ open class PetAPI: APIBase { - name: petstore_auth - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - returns: RequestBuilder */ - open class func deletePetWithRequestBuilder(petId: Int64) -> RequestBuilder { + open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "api_key": apiKey + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) } /** @@ -118,14 +123,14 @@ open class PetAPI: APIBase { - type: oauth2 - name: petstore_auth - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -141,14 +146,14 @@ open class PetAPI: APIBase { "status" : "aeiou" } ]}] - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -171,18 +176,17 @@ open class PetAPI: APIBase { open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "status": status - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + ]) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -206,14 +210,14 @@ open class PetAPI: APIBase { - type: oauth2 - name: petstore_auth - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -229,14 +233,14 @@ open class PetAPI: APIBase { "status" : "aeiou" } ]}] - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -259,18 +263,17 @@ open class PetAPI: APIBase { open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "tags": tags - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + ]) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -294,14 +297,14 @@ open class PetAPI: APIBase { - type: apiKey api_key - name: api_key - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example={ "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -317,14 +320,14 @@ open class PetAPI: APIBase { "status" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example={ "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -348,16 +351,14 @@ open class PetAPI: APIBase { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -389,12 +390,13 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -430,19 +432,20 @@ open class PetAPI: APIBase { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "name": name, "status": status ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -483,19 +486,20 @@ open class PetAPI: APIBase { var path = "/pet/{petId}/uploadImage" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "additionalMetadata": additionalMetadata, "file": file ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 00a9748262c..b375d849065 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -36,16 +36,14 @@ open class StoreAPI: APIBase { var path = "/store/order/{orderId}" path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -76,16 +74,14 @@ open class StoreAPI: APIBase { open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -106,11 +102,11 @@ open class StoreAPI: APIBase { - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -121,11 +117,11 @@ open class StoreAPI: APIBase { "status" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -144,16 +140,14 @@ open class StoreAPI: APIBase { var path = "/store/order/{orderId}" path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -174,11 +168,11 @@ open class StoreAPI: APIBase { - POST /store/order - - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -189,11 +183,11 @@ open class StoreAPI: APIBase { "status" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -212,12 +206,13 @@ open class StoreAPI: APIBase { let path = "/store/order" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index e88fa8f3623..9f440aa1a40 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -36,12 +36,13 @@ open class UserAPI: APIBase { let path = "/user" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -70,12 +71,13 @@ open class UserAPI: APIBase { let path = "/user/createWithArray" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -104,12 +106,13 @@ open class UserAPI: APIBase { let path = "/user/createWithList" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -138,16 +141,14 @@ open class UserAPI: APIBase { var path = "/user/{username}" path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -168,14 +169,14 @@ open class UserAPI: APIBase { - GET /user/{username} - - examples: [{contentType=application/xml, example= - 123456 - string - string - string - string - string - string - 0 + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 }, {contentType=application/json, example={ "firstName" : "aeiou", "lastName" : "aeiou", @@ -187,14 +188,14 @@ open class UserAPI: APIBase { "username" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 - string - string - string - string - string - string - 0 + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 }, {contentType=application/json, example={ "firstName" : "aeiou", "lastName" : "aeiou", @@ -214,16 +215,14 @@ open class UserAPI: APIBase { var path = "/user/{username}" path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -246,8 +245,8 @@ open class UserAPI: APIBase { - - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] - - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text @@ -257,19 +256,18 @@ open class UserAPI: APIBase { open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ - "username": username, + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "username": username, "password": password - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + ]) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -294,16 +292,14 @@ open class UserAPI: APIBase { open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -335,12 +331,13 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index d8e2004302d..801647631e4 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -16,8 +16,8 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { private var managerStore: [String: Alamofire.SessionManager] = [:] open class AlamofireRequestBuilder: RequestBuilder { - required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool) { - super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } /** diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift index 559a2e8a5e1..56b589b3fa8 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models.swift @@ -141,8 +141,7 @@ class Decoders { if let value = source as? T { return .success(value) } - //The last two expressions in this condition must be unnecessary, but it would be good to test this. - if let intermediate = source as? String, let value = Data(base64Encoded: intermediate) as? T, T.self is Data.Type, source is String { + if let intermediate = source as? String, let value = Data(base64Encoded: intermediate) as? T { return .success(value) } @@ -437,6 +436,63 @@ class Decoders { } + // Decoder for [Capitalization] + Decoders.addDecoder(clazz: [Capitalization].self) { (source: AnyObject) -> Decoded<[Capitalization]> in + return Decoders.decode(clazz: [Capitalization].self, source: source) + } + // Decoder for Capitalization + Decoders.addDecoder(clazz: Capitalization.self) { (source: AnyObject) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + + let instance = Capitalization() + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["smallCamel"] as AnyObject?) { + + case let .success(value): instance.smallCamel = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["CapitalCamel"] as AnyObject?) { + + case let .success(value): instance.capitalCamel = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["small_Snake"] as AnyObject?) { + + case let .success(value): instance.smallSnake = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["Capital_Snake"] as AnyObject?) { + + case let .success(value): instance.capitalSnake = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["SCA_ETH_Flow_Points"] as AnyObject?) { + + case let .success(value): instance.sCAETHFlowPoints = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["ATT_NAME"] as AnyObject?) { + + case let .success(value): instance.ATT_NAME = value + case let .failure(error): return .failure(error) + + } + return .success(instance) + } else { + return .failure(.typeMismatch(expected: "Capitalization", actual: "\(source)")) + } + } + + // Decoder for [Cat] Decoders.addDecoder(clazz: [Cat].self) { (source: AnyObject) -> Decoded<[Cat]> in return Decoders.decode(clazz: [Cat].self, source: source) diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift new file mode 100644 index 00000000000..eee1085a69c --- /dev/null +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -0,0 +1,34 @@ +// +// Capitalization.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Capitalization: JSONEncodable { + 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() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["smallCamel"] = self.smallCamel + nillableDictionary["CapitalCamel"] = self.capitalCamel + nillableDictionary["small_Snake"] = self.smallSnake + nillableDictionary["Capital_Snake"] = self.capitalSnake + nillableDictionary["SCA_ETH_Flow_Points"] = self.sCAETHFlowPoints + nillableDictionary["ATT_NAME"] = self.ATT_NAME + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index b3be1c99858..45759cfe0f9 100644 --- a/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift3/default/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -12,6 +12,7 @@ open class EnumTest: JSONEncodable { public enum EnumString: String { case upper = "UPPER" case lower = "lower" + case empty = "" } public enum EnumInteger: Int32 { case number1 = 1 diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift index 967dcc34735..b612ff90921 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -21,6 +21,16 @@ class APIHelper { return destination } + static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { guard let source = source else { return nil @@ -39,4 +49,17 @@ class APIHelper { return destination } + + static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { + let returnValues = values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + if returnValues.count == 0 { + return nil + } + return returnValues + } + } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift index 2b7eb3003e4..e23fc13395f 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs.swift @@ -31,7 +31,7 @@ open class APIBase { open class RequestBuilder { var credential: URLCredential? - var headers: [String:String] = [:] + var headers: [String:String] let parameters: [String:Any]? let isBody: Bool let method: String @@ -40,11 +40,12 @@ open class RequestBuilder { /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? - required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool) { + required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody + self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 3d018807eec..5d2659ed4c7 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -57,12 +57,13 @@ open class FakeAPI: APIBase { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -149,8 +150,7 @@ open class FakeAPI: APIBase { open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: ISOFullDate? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -166,14 +166,16 @@ open class FakeAPI: APIBase { "password": password, "callback": callback ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -193,6 +195,23 @@ open class FakeAPI: APIBase { case xyz = "(xyz)" } + /** + * enum for parameter enumHeaderStringArray + */ + public enum EnumHeaderStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumHeaderString + */ + public enum EnumHeaderString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + /** * enum for parameter enumQueryStringArray */ @@ -215,14 +234,16 @@ open class FakeAPI: APIBase { - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - 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: (form) Query parameter enum test (double) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { - testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in completion(error); } } @@ -232,15 +253,17 @@ open class FakeAPI: APIBase { - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - 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: (form) Query parameter enum test (double) (optional) - returns: Promise */ - open class func testEnumParameters( enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> Promise { + open class func testEnumParameters( enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> Promise { let deferred = Promise.pending() - testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { error in + testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { error in if let error = error { deferred.reject(error) } else { @@ -257,6 +280,8 @@ open class FakeAPI: APIBase { - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - 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) @@ -264,23 +289,34 @@ open class FakeAPI: APIBase { - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ - "enum_query_string_array": enumQueryStringArray, - "enum_query_string": enumQueryString?.rawValue, - "enum_query_integer": enumQueryInteger?.encodeToJSON() + let formParams: [String:Any?] = [ + "enum_form_string_array": enumFormStringArray, + "enum_form_string": enumFormString?.rawValue, + "enum_query_double": enumQueryDouble ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "enum_query_string_array": enumQueryStringArray, + "enum_query_string": enumQueryString?.rawValue, + "enum_query_integer": enumQueryInteger?.encodeToJSON() + ]) + + let nillableHeaders: [String: Any?] = [ + "enum_header_string_array": enumHeaderStringArray, + "enum_header_string": enumHeaderString?.rawValue + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) } } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift index eadaeb3c231..36a50e84d47 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift @@ -56,12 +56,13 @@ open class Fake_classname_tags123API: APIBase { let path = "/fake_classname_test" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 54bfa4842d2..7327edd38a9 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -57,22 +57,24 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** Deletes a pet - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { - deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in completion(error); } } @@ -81,11 +83,12 @@ open class PetAPI: APIBase { Deletes a pet - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - returns: Promise */ - open class func deletePet( petId: Int64) -> Promise { + open class func deletePet( petId: Int64, apiKey: String? = nil) -> Promise { let deferred = Promise.pending() - deletePet(petId: petId) { error in + deletePet(petId: petId, apiKey: apiKey) { error in if let error = error { deferred.reject(error) } else { @@ -104,23 +107,26 @@ open class PetAPI: APIBase { - name: petstore_auth - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - returns: RequestBuilder */ - open class func deletePetWithRequestBuilder(petId: Int64) -> RequestBuilder { + open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "api_key": apiKey + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) } /** @@ -170,14 +176,14 @@ open class PetAPI: APIBase { - type: oauth2 - name: petstore_auth - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -193,14 +199,14 @@ open class PetAPI: APIBase { "status" : "aeiou" } ]}] - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -223,18 +229,17 @@ open class PetAPI: APIBase { open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "status": status - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + ]) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -275,14 +280,14 @@ open class PetAPI: APIBase { - type: oauth2 - name: petstore_auth - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -298,14 +303,14 @@ open class PetAPI: APIBase { "status" : "aeiou" } ]}] - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -328,18 +333,17 @@ open class PetAPI: APIBase { open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "tags": tags - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + ]) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -380,14 +384,14 @@ open class PetAPI: APIBase { - type: apiKey api_key - name: api_key - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example={ "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -403,14 +407,14 @@ open class PetAPI: APIBase { "status" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example={ "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -434,16 +438,14 @@ open class PetAPI: APIBase { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -492,12 +494,13 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -552,19 +555,20 @@ open class PetAPI: APIBase { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "name": name, "status": status ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -624,19 +628,20 @@ open class PetAPI: APIBase { var path = "/pet/{petId}/uploadImage" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "additionalMetadata": additionalMetadata, "file": file ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index c51a9a0d969..100a6ba86a1 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -54,16 +54,14 @@ open class StoreAPI: APIBase { var path = "/store/order/{orderId}" path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -110,16 +108,14 @@ open class StoreAPI: APIBase { open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -157,11 +153,11 @@ open class StoreAPI: APIBase { - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -172,11 +168,11 @@ open class StoreAPI: APIBase { "status" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -195,16 +191,14 @@ open class StoreAPI: APIBase { var path = "/store/order/{orderId}" path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -242,11 +236,11 @@ open class StoreAPI: APIBase { - POST /store/order - - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -257,11 +251,11 @@ open class StoreAPI: APIBase { "status" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -280,12 +274,13 @@ open class StoreAPI: APIBase { let path = "/store/order" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 0e8a2d08edf..926d7dd546c 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -54,12 +54,13 @@ open class UserAPI: APIBase { let path = "/user" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -105,12 +106,13 @@ open class UserAPI: APIBase { let path = "/user/createWithArray" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -156,12 +158,13 @@ open class UserAPI: APIBase { let path = "/user/createWithList" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -207,16 +210,14 @@ open class UserAPI: APIBase { var path = "/user/{username}" path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -254,14 +255,14 @@ open class UserAPI: APIBase { - GET /user/{username} - - examples: [{contentType=application/xml, example= - 123456 - string - string - string - string - string - string - 0 + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 }, {contentType=application/json, example={ "firstName" : "aeiou", "lastName" : "aeiou", @@ -273,14 +274,14 @@ open class UserAPI: APIBase { "username" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 - string - string - string - string - string - string - 0 + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 }, {contentType=application/json, example={ "firstName" : "aeiou", "lastName" : "aeiou", @@ -300,16 +301,14 @@ open class UserAPI: APIBase { var path = "/user/{username}" path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -350,8 +349,8 @@ open class UserAPI: APIBase { - - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] - - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text @@ -361,19 +360,18 @@ open class UserAPI: APIBase { open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ - "username": username, + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "username": username, "password": password - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + ]) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -414,16 +412,14 @@ open class UserAPI: APIBase { open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -473,12 +469,13 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index d8e2004302d..801647631e4 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -16,8 +16,8 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { private var managerStore: [String: Alamofire.SessionManager] = [:] open class AlamofireRequestBuilder: RequestBuilder { - required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool) { - super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } /** diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift index 559a2e8a5e1..56b589b3fa8 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models.swift @@ -141,8 +141,7 @@ class Decoders { if let value = source as? T { return .success(value) } - //The last two expressions in this condition must be unnecessary, but it would be good to test this. - if let intermediate = source as? String, let value = Data(base64Encoded: intermediate) as? T, T.self is Data.Type, source is String { + if let intermediate = source as? String, let value = Data(base64Encoded: intermediate) as? T { return .success(value) } @@ -437,6 +436,63 @@ class Decoders { } + // Decoder for [Capitalization] + Decoders.addDecoder(clazz: [Capitalization].self) { (source: AnyObject) -> Decoded<[Capitalization]> in + return Decoders.decode(clazz: [Capitalization].self, source: source) + } + // Decoder for Capitalization + Decoders.addDecoder(clazz: Capitalization.self) { (source: AnyObject) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + + let instance = Capitalization() + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["smallCamel"] as AnyObject?) { + + case let .success(value): instance.smallCamel = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["CapitalCamel"] as AnyObject?) { + + case let .success(value): instance.capitalCamel = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["small_Snake"] as AnyObject?) { + + case let .success(value): instance.smallSnake = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["Capital_Snake"] as AnyObject?) { + + case let .success(value): instance.capitalSnake = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["SCA_ETH_Flow_Points"] as AnyObject?) { + + case let .success(value): instance.sCAETHFlowPoints = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["ATT_NAME"] as AnyObject?) { + + case let .success(value): instance.ATT_NAME = value + case let .failure(error): return .failure(error) + + } + return .success(instance) + } else { + return .failure(.typeMismatch(expected: "Capitalization", actual: "\(source)")) + } + } + + // Decoder for [Cat] Decoders.addDecoder(clazz: [Cat].self) { (source: AnyObject) -> Decoded<[Cat]> in return Decoders.decode(clazz: [Cat].self, source: source) diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift new file mode 100644 index 00000000000..eee1085a69c --- /dev/null +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -0,0 +1,34 @@ +// +// Capitalization.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Capitalization: JSONEncodable { + 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() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["smallCamel"] = self.smallCamel + nillableDictionary["CapitalCamel"] = self.capitalCamel + nillableDictionary["small_Snake"] = self.smallSnake + nillableDictionary["Capital_Snake"] = self.capitalSnake + nillableDictionary["SCA_ETH_Flow_Points"] = self.sCAETHFlowPoints + nillableDictionary["ATT_NAME"] = self.ATT_NAME + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index b3be1c99858..45759cfe0f9 100644 --- a/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift3/promisekit/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -12,6 +12,7 @@ open class EnumTest: JSONEncodable { public enum EnumString: String { case upper = "UPPER" case lower = "lower" + case empty = "" } public enum EnumInteger: Int32 { case number1 = 1 diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift index 967dcc34735..b612ff90921 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -21,6 +21,16 @@ class APIHelper { return destination } + static func rejectNilHeaders(_ source: [String:Any?]) -> [String:String] { + var destination = [String:String]() + for (key, nillableValue) in source { + if let value: Any = nillableValue { + destination[key] = "\(value)" + } + } + return destination + } + static func convertBoolToString(_ source: [String: Any]?) -> [String:Any]? { guard let source = source else { return nil @@ -39,4 +49,17 @@ class APIHelper { return destination } + + static func mapValuesToQueryItems(values: [String:Any?]) -> [URLQueryItem]? { + let returnValues = values + .filter { $0.1 != nil } + .map { (item: (_key: String, _value: Any?)) -> URLQueryItem in + URLQueryItem(name: item._key, value:"\(item._value!)") + } + if returnValues.count == 0 { + return nil + } + return returnValues + } + } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift index 2b7eb3003e4..e23fc13395f 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs.swift @@ -31,7 +31,7 @@ open class APIBase { open class RequestBuilder { var credential: URLCredential? - var headers: [String:String] = [:] + var headers: [String:String] let parameters: [String:Any]? let isBody: Bool let method: String @@ -40,11 +40,12 @@ open class RequestBuilder { /// Optional block to obtain a reference to the request's progress instance when available. public var onProgressReady: ((Progress) -> ())? - required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool) { + required public init(method: String, URLString: String, parameters: [String:Any]?, isBody: Bool, headers: [String:String] = [:]) { self.method = method self.URLString = URLString self.parameters = parameters self.isBody = isBody + self.headers = headers addHeaders(PetstoreClientAPI.customHeaders) } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift index 2efdb046526..23569a77b92 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -59,12 +59,13 @@ open class FakeAPI: APIBase { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -153,8 +154,7 @@ open class FakeAPI: APIBase { open class func testEndpointParametersWithRequestBuilder(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int32? = nil, int32: Int32? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: Data? = nil, date: ISOFullDate? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "integer": integer?.encodeToJSON(), "int32": int32?.encodeToJSON(), "int64": int64?.encodeToJSON(), @@ -170,14 +170,16 @@ open class FakeAPI: APIBase { "password": password, "callback": callback ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -197,6 +199,23 @@ open class FakeAPI: APIBase { case xyz = "(xyz)" } + /** + * enum for parameter enumHeaderStringArray + */ + public enum EnumHeaderStringArray_testEnumParameters: String { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumHeaderString + */ + public enum EnumHeaderString_testEnumParameters: String { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + /** * enum for parameter enumQueryStringArray */ @@ -219,14 +238,16 @@ open class FakeAPI: APIBase { - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - 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: (form) Query parameter enum test (double) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { - testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + testEnumParametersWithRequestBuilder(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble).execute { (response, error) -> Void in completion(error); } } @@ -236,15 +257,17 @@ open class FakeAPI: APIBase { - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - 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: (form) Query parameter enum test (double) (optional) - returns: Observable */ - open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> Observable { + open class func testEnumParameters(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> Observable { return Observable.create { observer -> Disposable in - testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { error in + testEnumParameters(enumFormStringArray: enumFormStringArray, enumFormString: enumFormString, enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble) { error in if let error = error { observer.on(.error(error as Error)) } else { @@ -263,6 +286,8 @@ open class FakeAPI: APIBase { - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional) - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to -efg) + - 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) @@ -270,23 +295,34 @@ open class FakeAPI: APIBase { - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: Int32? = nil, enumQueryDouble: Double? = nil) -> RequestBuilder { let path = "/fake" let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ - "enum_query_string_array": enumQueryStringArray, - "enum_query_string": enumQueryString?.rawValue, - "enum_query_integer": enumQueryInteger?.encodeToJSON() + let formParams: [String:Any?] = [ + "enum_form_string_array": enumFormStringArray, + "enum_form_string": enumFormString?.rawValue, + "enum_query_double": enumQueryDouble ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "enum_query_string_array": enumQueryStringArray, + "enum_query_string": enumQueryString?.rawValue, + "enum_query_integer": enumQueryInteger?.encodeToJSON() + ]) + + let nillableHeaders: [String: Any?] = [ + "enum_header_string_array": enumHeaderStringArray, + "enum_header_string": enumHeaderString?.rawValue + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) } } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift index 0c6f61f7f3c..b6db957d41d 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/Fake_classname_tags123API.swift @@ -58,12 +58,13 @@ open class Fake_classname_tags123API: APIBase { let path = "/fake_classname_test" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PATCH", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PATCH", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 40a72621dbe..8e54eb50a69 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -59,22 +59,24 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** Deletes a pet - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - parameter completion: completion handler to receive the data and the error objects */ - open class func deletePet(petId: Int64, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { - deletePetWithRequestBuilder(petId: petId).execute { (response, error) -> Void in + open class func deletePet(petId: Int64, apiKey: String? = nil, completion: @escaping ((_ error: ErrorResponse?) -> Void)) { + deletePetWithRequestBuilder(petId: petId, apiKey: apiKey).execute { (response, error) -> Void in completion(error); } } @@ -83,11 +85,12 @@ open class PetAPI: APIBase { Deletes a pet - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - returns: Observable */ - open class func deletePet(petId: Int64) -> Observable { + open class func deletePet(petId: Int64, apiKey: String? = nil) -> Observable { return Observable.create { observer -> Disposable in - deletePet(petId: petId) { error in + deletePet(petId: petId, apiKey: apiKey) { error in if let error = error { observer.on(.error(error as Error)) } else { @@ -108,23 +111,26 @@ open class PetAPI: APIBase { - name: petstore_auth - parameter petId: (path) Pet id to delete + - parameter apiKey: (header) (optional) - returns: RequestBuilder */ - open class func deletePetWithRequestBuilder(petId: Int64) -> RequestBuilder { + open class func deletePetWithRequestBuilder(petId: Int64, apiKey: String? = nil) -> RequestBuilder { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + + let nillableHeaders: [String: Any?] = [ + "api_key": apiKey + ] + let headerParameters = APIHelper.rejectNilHeaders(nillableHeaders) - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false, headers: headerParameters) } /** @@ -176,14 +182,14 @@ open class PetAPI: APIBase { - type: oauth2 - name: petstore_auth - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -199,14 +205,14 @@ open class PetAPI: APIBase { "status" : "aeiou" } ]}] - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -229,18 +235,17 @@ open class PetAPI: APIBase { open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByStatus" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "status": status - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + ]) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -283,14 +288,14 @@ open class PetAPI: APIBase { - type: oauth2 - name: petstore_auth - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -306,14 +311,14 @@ open class PetAPI: APIBase { "status" : "aeiou" } ]}] - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example=[ { "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -336,18 +341,17 @@ open class PetAPI: APIBase { open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { let path = "/pet/findByTags" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ "tags": tags - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + ]) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -390,14 +394,14 @@ open class PetAPI: APIBase { - type: apiKey api_key - name: api_key - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example={ "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -413,14 +417,14 @@ open class PetAPI: APIBase { "status" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 + 123456789 doggie - string + aeiou - string + aeiou }, {contentType=application/json, example={ "photoUrls" : [ "aeiou" ], "name" : "doggie", @@ -444,16 +448,14 @@ open class PetAPI: APIBase { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -504,12 +506,13 @@ open class PetAPI: APIBase { let path = "/pet" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -566,19 +569,20 @@ open class PetAPI: APIBase { var path = "/pet/{petId}" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "name": name, "status": status ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -640,19 +644,20 @@ open class PetAPI: APIBase { var path = "/pet/{petId}/uploadImage" path = path.replacingOccurrences(of: "{petId}", with: "\(petId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path - - let nillableParameters: [String:Any?] = [ + let formParams: [String:Any?] = [ "additionalMetadata": additionalMetadata, "file": file ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let nonNullParameters = APIHelper.rejectNil(formParams) + let parameters = APIHelper.convertBoolToString(nonNullParameters) + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 66eddc831b2..023a565e38c 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -56,16 +56,14 @@ open class StoreAPI: APIBase { var path = "/store/order/{orderId}" path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -114,16 +112,14 @@ open class StoreAPI: APIBase { open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String:Int32]> { let path = "/store/inventory" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder<[String:Int32]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -163,11 +159,11 @@ open class StoreAPI: APIBase { - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -178,11 +174,11 @@ open class StoreAPI: APIBase { "status" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -201,16 +197,14 @@ open class StoreAPI: APIBase { var path = "/store/order/{orderId}" path = path.replacingOccurrences(of: "{orderId}", with: "\(orderId)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -250,11 +244,11 @@ open class StoreAPI: APIBase { - POST /store/order - - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -265,11 +259,11 @@ open class StoreAPI: APIBase { "status" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 - 123456 - 0 + 123456789 + 123456789 + 123 2000-01-23T04:56:07.000Z - string + aeiou true }, {contentType=application/json, example={ "petId" : 123456789, @@ -288,12 +282,13 @@ open class StoreAPI: APIBase { let path = "/store/order" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 856d30fe276..c4b001d2453 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -56,12 +56,13 @@ open class UserAPI: APIBase { let path = "/user" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -109,12 +110,13 @@ open class UserAPI: APIBase { let path = "/user/createWithArray" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -162,12 +164,13 @@ open class UserAPI: APIBase { let path = "/user/createWithList" let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "POST", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "POST", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } /** @@ -215,16 +218,14 @@ open class UserAPI: APIBase { var path = "/user/{username}" path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "DELETE", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "DELETE", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -264,14 +265,14 @@ open class UserAPI: APIBase { - GET /user/{username} - - examples: [{contentType=application/xml, example= - 123456 - string - string - string - string - string - string - 0 + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 }, {contentType=application/json, example={ "firstName" : "aeiou", "lastName" : "aeiou", @@ -283,14 +284,14 @@ open class UserAPI: APIBase { "username" : "aeiou" }}] - examples: [{contentType=application/xml, example= - 123456 - string - string - string - string - string - string - 0 + 123456789 + aeiou + aeiou + aeiou + aeiou + aeiou + aeiou + 123 }, {contentType=application/json, example={ "firstName" : "aeiou", "lastName" : "aeiou", @@ -310,16 +311,14 @@ open class UserAPI: APIBase { var path = "/user/{username}" path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -362,8 +361,8 @@ open class UserAPI: APIBase { - - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - responseHeaders: [X-Rate-Limit(Int32), X-Expires-After(Date)] - - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] - - examples: [{contentType=application/xml, example=string}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] + - examples: [{contentType=application/xml, example=aeiou}, {contentType=application/json, example="aeiou"}] - parameter username: (query) The user name for login - parameter password: (query) The password for login in clear text @@ -373,19 +372,18 @@ open class UserAPI: APIBase { open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { let path = "/user/login" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil - let nillableParameters: [String:Any?] = [ - "username": username, + let url = NSURLComponents(string: URLString) + url?.queryItems = APIHelper.mapValuesToQueryItems(values:[ + "username": username, "password": password - ] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + ]) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: false) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -428,16 +426,14 @@ open class UserAPI: APIBase { open class func logoutUserWithRequestBuilder() -> RequestBuilder { let path = "/user/logout" let URLString = PetstoreClientAPI.basePath + path + let parameters: [String:Any]? = nil + + let url = NSURLComponents(string: URLString) + - let nillableParameters: [String:Any?] = [:] - - let parameters = APIHelper.rejectNil(nillableParameters) - - let convertedParameters = APIHelper.convertBoolToString(parameters) - let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "GET", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "GET", URLString: (url?.string ?? URLString), parameters: parameters, isBody: false) } /** @@ -489,12 +485,13 @@ open class UserAPI: APIBase { path = path.replacingOccurrences(of: "{username}", with: "\(username)", options: .literal, range: nil) let URLString = PetstoreClientAPI.basePath + path let parameters = body.encodeToJSON() as? [String:AnyObject] - - let convertedParameters = APIHelper.convertBoolToString(parameters) - + + let url = NSURLComponents(string: URLString) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() - return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: true) + return requestBuilder.init(method: "PUT", URLString: (url?.string ?? URLString), parameters: parameters, isBody: true) } } diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index d8e2004302d..801647631e4 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -16,8 +16,8 @@ class AlamofireRequestBuilderFactory: RequestBuilderFactory { private var managerStore: [String: Alamofire.SessionManager] = [:] open class AlamofireRequestBuilder: RequestBuilder { - required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool) { - super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + required public init(method: String, URLString: String, parameters: [String : Any]?, isBody: Bool, headers: [String : String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody, headers: headers) } /** diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift index 559a2e8a5e1..56b589b3fa8 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models.swift @@ -141,8 +141,7 @@ class Decoders { if let value = source as? T { return .success(value) } - //The last two expressions in this condition must be unnecessary, but it would be good to test this. - if let intermediate = source as? String, let value = Data(base64Encoded: intermediate) as? T, T.self is Data.Type, source is String { + if let intermediate = source as? String, let value = Data(base64Encoded: intermediate) as? T { return .success(value) } @@ -437,6 +436,63 @@ class Decoders { } + // Decoder for [Capitalization] + Decoders.addDecoder(clazz: [Capitalization].self) { (source: AnyObject) -> Decoded<[Capitalization]> in + return Decoders.decode(clazz: [Capitalization].self, source: source) + } + // Decoder for Capitalization + Decoders.addDecoder(clazz: Capitalization.self) { (source: AnyObject) -> Decoded in + if let sourceDictionary = source as? [AnyHashable: Any] { + + let instance = Capitalization() + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["smallCamel"] as AnyObject?) { + + case let .success(value): instance.smallCamel = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["CapitalCamel"] as AnyObject?) { + + case let .success(value): instance.capitalCamel = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["small_Snake"] as AnyObject?) { + + case let .success(value): instance.smallSnake = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["Capital_Snake"] as AnyObject?) { + + case let .success(value): instance.capitalSnake = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["SCA_ETH_Flow_Points"] as AnyObject?) { + + case let .success(value): instance.sCAETHFlowPoints = value + case let .failure(error): return .failure(error) + + } + + switch Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["ATT_NAME"] as AnyObject?) { + + case let .success(value): instance.ATT_NAME = value + case let .failure(error): return .failure(error) + + } + return .success(instance) + } else { + return .failure(.typeMismatch(expected: "Capitalization", actual: "\(source)")) + } + } + + // Decoder for [Cat] Decoders.addDecoder(clazz: [Cat].self) { (source: AnyObject) -> Decoded<[Cat]> in return Decoders.decode(clazz: [Cat].self, source: source) diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift new file mode 100644 index 00000000000..eee1085a69c --- /dev/null +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/Capitalization.swift @@ -0,0 +1,34 @@ +// +// Capitalization.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +open class Capitalization: JSONEncodable { + 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() {} + + // MARK: JSONEncodable + open func encodeToJSON() -> Any { + var nillableDictionary = [String:Any?]() + nillableDictionary["smallCamel"] = self.smallCamel + nillableDictionary["CapitalCamel"] = self.capitalCamel + nillableDictionary["small_Snake"] = self.smallSnake + nillableDictionary["Capital_Snake"] = self.capitalSnake + nillableDictionary["SCA_ETH_Flow_Points"] = self.sCAETHFlowPoints + nillableDictionary["ATT_NAME"] = self.ATT_NAME + let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift index b3be1c99858..45759cfe0f9 100644 --- a/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift +++ b/samples/client/petstore/swift3/rxswift/PetstoreClient/Classes/Swaggers/Models/EnumTest.swift @@ -12,6 +12,7 @@ open class EnumTest: JSONEncodable { public enum EnumString: String { case upper = "UPPER" case lower = "lower" + case empty = "" } public enum EnumInteger: Int32 { case number1 = 1 diff --git a/samples/client/petstore/typescript-angular/API/Client/InlineResponse200.ts b/samples/client/petstore/typescript-angular/API/Client/InlineResponse200.ts deleted file mode 100644 index 079eac61bc6..00000000000 --- a/samples/client/petstore/typescript-angular/API/Client/InlineResponse200.ts +++ /dev/null @@ -1,32 +0,0 @@ -/// - -namespace API.Client { - 'use strict'; - - export interface InlineResponse200 { - - "tags"?: Array; - - "id": number; - - "category"?: any; - - /** - * pet status in the store - */ - "status"?: InlineResponse200.StatusEnum; - - "name"?: string; - - "photoUrls"?: Array; - } - - export namespace InlineResponse200 { - - export enum StatusEnum { - available = 'available', - pending = 'pending', - sold = 'sold' - } - } -} diff --git a/samples/client/petstore/typescript-angular/API/Client/Model200Response.ts b/samples/client/petstore/typescript-angular/API/Client/Model200Response.ts deleted file mode 100644 index ef34114f4a3..00000000000 --- a/samples/client/petstore/typescript-angular/API/Client/Model200Response.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -namespace API.Client { - 'use strict'; - - export interface Model200Response { - - "name"?: number; - } - -} diff --git a/samples/client/petstore/typescript-angular/API/Client/ModelReturn.ts b/samples/client/petstore/typescript-angular/API/Client/ModelReturn.ts deleted file mode 100644 index c147566cf47..00000000000 --- a/samples/client/petstore/typescript-angular/API/Client/ModelReturn.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -namespace API.Client { - 'use strict'; - - export interface ModelReturn { - - "return"?: number; - } - -} diff --git a/samples/client/petstore/typescript-angular/API/Client/Name.ts b/samples/client/petstore/typescript-angular/API/Client/Name.ts deleted file mode 100644 index 9277422d52f..00000000000 --- a/samples/client/petstore/typescript-angular/API/Client/Name.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -namespace API.Client { - 'use strict'; - - export interface Name { - - "name"?: number; - } - -} diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts deleted file mode 100644 index ec5ab968c9d..00000000000 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ /dev/null @@ -1,289 +0,0 @@ -/** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - -/// - -/* tslint:disable:no-unused-variable member-ordering */ - -namespace API.Client { - 'use strict'; - - export class PetApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; - - constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath !== undefined) { - this.basePath = basePath; - } - } - - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } - - /** - * Add a new pet to the store - * - * @param body Pet object that needs to be added to the store - */ - public addPet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { - method: 'POST', - url: localVarPath, - json: true, - data: body, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Deletes a pet - * - * @param petId Pet id to delete - * @param apiKey - */ - public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new Error('Required parameter petId was null or undefined when calling deletePet.'); - } - headerParams['api_key'] = apiKey; - - let httpRequestParams: any = { - method: 'DELETE', - url: localVarPath, - json: true, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * 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 - */ - public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { - const localVarPath = this.basePath + '/pet/findByStatus'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - if (status !== undefined) { - queryParameters['status'] = status; - } - - let httpRequestParams: any = { - method: 'GET', - url: localVarPath, - json: true, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * 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 - */ - public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { - const localVarPath = this.basePath + '/pet/findByTags'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - if (tags !== undefined) { - queryParameters['tags'] = tags; - } - - let httpRequestParams: any = { - method: 'GET', - url: localVarPath, - json: true, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - */ - public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new Error('Required parameter petId was null or undefined when calling getPetById.'); - } - let httpRequestParams: any = { - method: 'GET', - url: localVarPath, - json: true, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Update an existing pet - * - * @param body Pet object that needs to be added to the store - */ - public updatePet (body?: Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/pet'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { - method: 'PUT', - url: localVarPath, - json: true, - data: body, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * 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 - * @param status Updated status of the pet - */ - public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/pet/{petId}' - .replace('{' + 'petId' + '}', String(petId)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); - } - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - formParams['name'] = name; - - formParams['status'] = status; - - let httpRequestParams: any = { - method: 'POST', - url: localVarPath, - json: false, - data: this.$httpParamSerializer(formParams), - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * uploads an image - * - * @param petId ID of pet to update - * @param additionalMetadata Additional data to pass to server - * @param file file to upload - */ - public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/pet/{petId}/uploadImage' - .replace('{' + 'petId' + '}', String(petId)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let formParams: any = {}; - - // verify required parameter 'petId' is not null or undefined - if (petId === null || petId === undefined) { - throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); - } - headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - formParams['additionalMetadata'] = additionalMetadata; - - formParams['file'] = file; - - let httpRequestParams: any = { - method: 'POST', - url: localVarPath, - json: false, - data: this.$httpParamSerializer(formParams), - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - } -} diff --git a/samples/client/petstore/typescript-angular/API/Client/SpecialModelName.ts b/samples/client/petstore/typescript-angular/API/Client/SpecialModelName.ts deleted file mode 100644 index 550ab8cd008..00000000000 --- a/samples/client/petstore/typescript-angular/API/Client/SpecialModelName.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -namespace API.Client { - 'use strict'; - - export interface SpecialModelName { - - "$Special[propertyName]"?: number; - } - -} diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts deleted file mode 100644 index 9be77cc81a1..00000000000 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - -/// - -/* tslint:disable:no-unused-variable member-ordering */ - -namespace API.Client { - 'use strict'; - - export class StoreApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; - - constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath !== undefined) { - this.basePath = basePath; - } - } - - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } - - /** - * 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 - */ - public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'orderId' is not null or undefined - if (orderId === null || orderId === undefined) { - throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); - } - let httpRequestParams: any = { - method: 'DELETE', - url: localVarPath, - json: true, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Returns pet inventories by status - * Returns a map of status codes to quantities - */ - public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> { - const localVarPath = this.basePath + '/store/inventory'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { - method: 'GET', - url: localVarPath, - json: true, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * 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 - */ - public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { - const localVarPath = this.basePath + '/store/order/{orderId}' - .replace('{' + 'orderId' + '}', String(orderId)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'orderId' is not null or undefined - if (orderId === null || orderId === undefined) { - throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); - } - let httpRequestParams: any = { - method: 'GET', - url: localVarPath, - json: true, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Place an order for a pet - * - * @param body order placed for purchasing the pet - */ - public placeOrder (body?: Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { - const localVarPath = this.basePath + '/store/order'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { - method: 'POST', - url: localVarPath, - json: true, - data: body, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - } -} diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts deleted file mode 100644 index cd69c69c47e..00000000000 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ /dev/null @@ -1,262 +0,0 @@ -/** - * Swagger Petstore - * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@wordnik.com - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - -/// - -/* tslint:disable:no-unused-variable member-ordering */ - -namespace API.Client { - 'use strict'; - - export class UserApi { - protected basePath = 'http://petstore.swagger.io/v2'; - public defaultHeaders : any = {}; - - static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; - - constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { - if (basePath !== undefined) { - this.basePath = basePath; - } - } - - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } - - /** - * Create user - * This can only be done by the logged in user. - * @param body Created user object - */ - public createUser (body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/user'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { - method: 'POST', - url: localVarPath, - json: true, - data: body, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithArrayInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/user/createWithArray'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { - method: 'POST', - url: localVarPath, - json: true, - data: body, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Creates list of users with given input array - * - * @param body List of user object - */ - public createUsersWithListInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/user/createWithList'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { - method: 'POST', - url: localVarPath, - json: true, - data: body, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Delete user - * This can only be done by the logged in user. - * @param username The name that needs to be deleted - */ - public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'username' is not null or undefined - if (username === null || username === undefined) { - throw new Error('Required parameter username was null or undefined when calling deleteUser.'); - } - let httpRequestParams: any = { - method: 'DELETE', - url: localVarPath, - json: true, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. - */ - public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'username' is not null or undefined - if (username === null || username === undefined) { - throw new Error('Required parameter username was null or undefined when calling getUserByName.'); - } - let httpRequestParams: any = { - method: 'GET', - url: localVarPath, - json: true, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Logs user into the system - * - * @param username The user name for login - * @param password The password for login in clear text - */ - public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { - const localVarPath = this.basePath + '/user/login'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - if (username !== undefined) { - queryParameters['username'] = username; - } - - if (password !== undefined) { - queryParameters['password'] = password; - } - - let httpRequestParams: any = { - method: 'GET', - url: localVarPath, - json: true, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Logs out current logged in user session - * - */ - public logoutUser (extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/user/logout'; - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - let httpRequestParams: any = { - method: 'GET', - url: localVarPath, - json: true, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - /** - * Updated user - * This can only be done by the logged in user. - * @param username name that need to be deleted - * @param body Updated user object - */ - public updateUser (username: string, body?: User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { - const localVarPath = this.basePath + '/user/{username}' - .replace('{' + 'username' + '}', String(username)); - - let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); - // verify required parameter 'username' is not null or undefined - if (username === null || username === undefined) { - throw new Error('Required parameter username was null or undefined when calling updateUser.'); - } - let httpRequestParams: any = { - method: 'PUT', - url: localVarPath, - json: true, - data: body, - params: queryParameters, - headers: headerParams - }; - - if (extraHttpRequestParams) { - httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); - } - - return this.$http(httpRequestParams); - } - } -} diff --git a/samples/client/petstore/typescript-angular/API/Client/api.d.ts b/samples/client/petstore/typescript-angular/API/Client/api.d.ts deleted file mode 100644 index f2a86d96e96..00000000000 --- a/samples/client/petstore/typescript-angular/API/Client/api.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/// -/// -/// -/// -/// - -/// -/// -/// diff --git a/samples/client/petstore/typescript-angular/api.module.ts b/samples/client/petstore/typescript-angular/api.module.ts new file mode 100644 index 00000000000..825758a0792 --- /dev/null +++ b/samples/client/petstore/typescript-angular/api.module.ts @@ -0,0 +1,9 @@ +import * as api from './api/api'; +import * as angular from 'angular'; + +const apiModule = angular.module('api', []) +.service('PetApi', api.PetApi) +.service('StoreApi', api.StoreApi) +.service('UserApi', api.UserApi) + +export default apiModule; diff --git a/samples/client/petstore/typescript-angular/api/PetApi.ts b/samples/client/petstore/typescript-angular/api/PetApi.ts new file mode 100644 index 00000000000..887f87a1be9 --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/PetApi.ts @@ -0,0 +1,268 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from '../model/models'; + +/* tslint:disable:no-unused-variable member-ordering */ + +export class PetApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; + + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { + if (basePath !== undefined) { + this.basePath = basePath; + } + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + public addPet (body?: models.Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + public deletePet (petId: number, apiKey?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + headerParams['api_key'] = apiKey; + + let httpRequestParams: ng.IRequestConfig = { + method: 'DELETE', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * 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 + */ + public findPetsByStatus (status?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + const localVarPath = this.basePath + '/pet/findByStatus'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + if (status !== undefined) { + queryParameters['status'] = status; + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * 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 + */ + public findPetsByTags (tags?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise> { + const localVarPath = this.basePath + '/pet/findByTags'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + if (tags !== undefined) { + queryParameters['tags'] = tags; + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + */ + public getPetById (petId: number, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public updatePet (body?: models.Pet, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { + method: 'PUT', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * 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 + * @param status Updated status of the pet + */ + public updatePetWithForm (petId: string, name?: string, status?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet/{petId}' + .replace('{' + 'petId' + '}', String(petId)); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let formParams: any = {}; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['name'] = name; + + formParams['status'] = status; + + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: this.$httpParamSerializer(formParams), + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + public uploadFile (petId: number, additionalMetadata?: string, file?: any, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/pet/{petId}/uploadImage' + .replace('{' + 'petId' + '}', String(petId)); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let formParams: any = {}; + + // verify required parameter 'petId' is not null or undefined + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['additionalMetadata'] = additionalMetadata; + + formParams['file'] = file; + + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: this.$httpParamSerializer(formParams), + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } +} diff --git a/samples/client/petstore/typescript-angular/api/StoreApi.ts b/samples/client/petstore/typescript-angular/api/StoreApi.ts new file mode 100644 index 00000000000..efb81af53df --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/StoreApi.ts @@ -0,0 +1,131 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from '../model/models'; + +/* tslint:disable:no-unused-variable member-ordering */ + +export class StoreApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; + + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { + if (basePath !== undefined) { + this.basePath = basePath; + } + } + + /** + * 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 + */ + public deleteOrder (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + let httpRequestParams: ng.IRequestConfig = { + method: 'DELETE', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + */ + public getInventory (extraHttpRequestParams?: any ) : ng.IHttpPromise<{ [key: string]: number; }> { + const localVarPath = this.basePath + '/store/inventory'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * 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 + */ + public getOrderById (orderId: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/store/order/{orderId}' + .replace('{' + 'orderId' + '}', String(orderId)); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'orderId' is not null or undefined + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + */ + public placeOrder (body?: models.Order, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/store/order'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } +} diff --git a/samples/client/petstore/typescript-angular/api/UserApi.ts b/samples/client/petstore/typescript-angular/api/UserApi.ts new file mode 100644 index 00000000000..15689b0c82d --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/UserApi.ts @@ -0,0 +1,241 @@ +/** + * Swagger Petstore + * This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@wordnik.com + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + +import * as models from '../model/models'; + +/* tslint:disable:no-unused-variable member-ordering */ + +export class UserApi { + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders : any = {}; + + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; + + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { + if (basePath !== undefined) { + this.basePath = basePath; + } + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + public createUser (body?: models.User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithArrayInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user/createWithArray'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public createUsersWithListInput (body?: Array, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user/createWithList'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { + method: 'POST', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + public deleteUser (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + let httpRequestParams: ng.IRequestConfig = { + method: 'DELETE', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + public getUserByName (username: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + */ + public loginUser (username?: string, password?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise { + const localVarPath = this.basePath + '/user/login'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + if (username !== undefined) { + queryParameters['username'] = username; + } + + if (password !== undefined) { + queryParameters['password'] = password; + } + + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Logs out current logged in user session + * + */ + public logoutUser (extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user/logout'; + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + let httpRequestParams: ng.IRequestConfig = { + method: 'GET', + url: localVarPath, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + */ + public updateUser (username: string, body?: models.User, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/user/{username}' + .replace('{' + 'username' + '}', String(username)); + + let queryParameters: any = {}; + let headerParams: any = (Object).assign({}, this.defaultHeaders); + // verify required parameter 'username' is not null or undefined + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + let httpRequestParams: ng.IRequestConfig = { + method: 'PUT', + url: localVarPath, + data: body, + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = (Object).assign(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } +} diff --git a/samples/client/petstore/typescript-angular/api/api.ts b/samples/client/petstore/typescript-angular/api/api.ts new file mode 100644 index 00000000000..0d1e9f047fd --- /dev/null +++ b/samples/client/petstore/typescript-angular/api/api.ts @@ -0,0 +1,7 @@ +export * from './PetApi'; +import { PetApi } from './PetApi'; +export * from './StoreApi'; +import { StoreApi } from './StoreApi'; +export * from './UserApi'; +import { UserApi } from './UserApi'; +export const APIS = [ PetApi, StoreApi, UserApi, ]; diff --git a/samples/client/petstore/typescript-angular/index.ts b/samples/client/petstore/typescript-angular/index.ts new file mode 100644 index 00000000000..557365516ad --- /dev/null +++ b/samples/client/petstore/typescript-angular/index.ts @@ -0,0 +1,2 @@ +export * from './api/api'; +export * from './model/models'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular/API/Client/Category.ts b/samples/client/petstore/typescript-angular/model/Category.ts similarity index 76% rename from samples/client/petstore/typescript-angular/API/Client/Category.ts rename to samples/client/petstore/typescript-angular/model/Category.ts index 072eecdd58b..57ac55012d1 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Category.ts +++ b/samples/client/petstore/typescript-angular/model/Category.ts @@ -10,16 +10,10 @@ * Do not edit the class manually. */ -/// - -namespace API.Client { - 'use strict'; - - export interface Category { - "id"?: number; - - "name"?: string; - - } +import * as models from './models'; +export interface Category { + "id"?: number; + "name"?: string; } + diff --git a/samples/client/petstore/typescript-angular/API/Client/Order.ts b/samples/client/petstore/typescript-angular/model/Order.ts similarity index 50% rename from samples/client/petstore/typescript-angular/API/Client/Order.ts rename to samples/client/petstore/typescript-angular/model/Order.ts index cff3486ef6c..d559f06efe6 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Order.ts +++ b/samples/client/petstore/typescript-angular/model/Order.ts @@ -10,34 +10,24 @@ * Do not edit the class manually. */ -/// +import * as models from './models'; -namespace API.Client { - 'use strict'; +export interface Order { + "id"?: number; + "petId"?: number; + "quantity"?: number; + "shipDate"?: Date; + /** + * Order Status + */ + "status"?: Order.StatusEnum; + "complete"?: boolean; +} - export interface Order { - "id"?: number; - - "petId"?: number; - - "quantity"?: number; - - "shipDate"?: Date; - - /** - * Order Status - */ - "status"?: Order.StatusEnum; - - "complete"?: boolean; - - } - - export namespace Order { - export enum StatusEnum { - Placed = 'placed', - Approved = 'approved', - Delivered = 'delivered' - } +export namespace Order { + export enum StatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' } } diff --git a/samples/client/petstore/typescript-angular/API/Client/Pet.ts b/samples/client/petstore/typescript-angular/model/Pet.ts similarity index 50% rename from samples/client/petstore/typescript-angular/API/Client/Pet.ts rename to samples/client/petstore/typescript-angular/model/Pet.ts index 587ac1eb9f0..ebf8cb345ab 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Pet.ts +++ b/samples/client/petstore/typescript-angular/model/Pet.ts @@ -10,34 +10,24 @@ * Do not edit the class manually. */ -/// +import * as models from './models'; -namespace API.Client { - 'use strict'; +export interface Pet { + "id"?: number; + "category"?: models.Category; + "name": string; + "photoUrls": Array; + "tags"?: Array; + /** + * pet status in the store + */ + "status"?: Pet.StatusEnum; +} - export interface Pet { - "id"?: number; - - "category"?: Category; - - "name": string; - - "photoUrls": Array; - - "tags"?: Array; - - /** - * pet status in the store - */ - "status"?: Pet.StatusEnum; - - } - - export namespace Pet { - export enum StatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' - } +export namespace Pet { + export enum StatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' } } diff --git a/samples/client/petstore/typescript-angular/API/Client/Tag.ts b/samples/client/petstore/typescript-angular/model/Tag.ts similarity index 76% rename from samples/client/petstore/typescript-angular/API/Client/Tag.ts rename to samples/client/petstore/typescript-angular/model/Tag.ts index db86127ca7c..3c6c7e14f8f 100644 --- a/samples/client/petstore/typescript-angular/API/Client/Tag.ts +++ b/samples/client/petstore/typescript-angular/model/Tag.ts @@ -10,16 +10,10 @@ * Do not edit the class manually. */ -/// - -namespace API.Client { - 'use strict'; - - export interface Tag { - "id"?: number; - - "name"?: string; - - } +import * as models from './models'; +export interface Tag { + "id"?: number; + "name"?: string; } + diff --git a/samples/client/petstore/typescript-angular/API/Client/User.ts b/samples/client/petstore/typescript-angular/model/User.ts similarity index 57% rename from samples/client/petstore/typescript-angular/API/Client/User.ts rename to samples/client/petstore/typescript-angular/model/User.ts index 71caf720c5a..b4671197abf 100644 --- a/samples/client/petstore/typescript-angular/API/Client/User.ts +++ b/samples/client/petstore/typescript-angular/model/User.ts @@ -10,31 +10,19 @@ * Do not edit the class manually. */ -/// - -namespace API.Client { - 'use strict'; - - export interface User { - "id"?: number; - - "username"?: string; - - "firstName"?: string; - - "lastName"?: string; - - "email"?: string; - - "password"?: string; - - "phone"?: string; - - /** - * User Status - */ - "userStatus"?: number; - - } +import * as models from './models'; +export interface User { + "id"?: number; + "username"?: string; + "firstName"?: string; + "lastName"?: string; + "email"?: string; + "password"?: string; + "phone"?: string; + /** + * User Status + */ + "userStatus"?: number; } + diff --git a/samples/client/petstore/typescript-angular/model/models.ts b/samples/client/petstore/typescript-angular/model/models.ts new file mode 100644 index 00000000000..92dac02846c --- /dev/null +++ b/samples/client/petstore/typescript-angular/model/models.ts @@ -0,0 +1,5 @@ +export * from './Category'; +export * from './Order'; +export * from './Pet'; +export * from './Tag'; +export * from './User'; diff --git a/samples/client/petstore/typescript-angular/tsconfig.json b/samples/client/petstore/typescript-angular/tsconfig.json index 9bf11bd4cee..86be0964e31 100644 --- a/samples/client/petstore/typescript-angular/tsconfig.json +++ b/samples/client/petstore/typescript-angular/tsconfig.json @@ -5,15 +5,7 @@ "out": "client.js" }, "files": [ - "API/Client/Category.ts", - "API/Client/Pet.ts", - "API/Client/StoreApi.ts", - "API/Client/User.ts", - "API/Client/api.d.ts", - "API/Client/Order.ts", - "API/Client/PetApi.ts", - "API/Client/Tag.ts", - "API/Client/UserApi.ts", + "./index.ts", "typings/tsd.d.ts" ] } diff --git a/samples/client/petstore/typescript-angular2/default/api/api.ts b/samples/client/petstore/typescript-angular2/default/api/api.ts index b7d674969f5..734223c2269 100644 --- a/samples/client/petstore/typescript-angular2/default/api/api.ts +++ b/samples/client/petstore/typescript-angular2/default/api/api.ts @@ -1,3 +1,4 @@ export * from './pet.service'; export * from './store.service'; export * from './user.service'; +export const APIS = [ PetService, StoreService, UserService, ]; diff --git a/samples/client/petstore/typescript-angular2/default/api/pet.service.ts b/samples/client/petstore/typescript-angular2/default/api/pet.service.ts index 14eb4b9e794..6746558021f 100644 --- a/samples/client/petstore/typescript-angular2/default/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular2/default/api/pet.service.ts @@ -20,7 +20,7 @@ import '../rxjs-operators'; import { Pet } from '../model/pet'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -217,37 +217,34 @@ export class PetService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -269,7 +266,6 @@ export class PetService { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } - headers.set('api_key', String(apiKey)); @@ -278,28 +274,26 @@ export class PetService { 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -316,39 +310,38 @@ export class PetService { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - if (status !== undefined) { - queryParameters.set('status', status); + if (status) { + status.forEach((element) => { + queryParameters.append('status', element); + }) } - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -365,39 +358,38 @@ export class PetService { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - if (tags !== undefined) { - queryParameters.set('tags', tags); + if (tags) { + tags.forEach((element) => { + queryParameters.append('tags', element); + }) } - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -419,45 +411,36 @@ export class PetService { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } - // authentication (api_key) required - if (this.configuration.apiKey) - { + if (this.configuration.apiKey) { headers.set('api_key', this.configuration.apiKey); } + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -475,37 +458,34 @@ export class PetService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -528,8 +508,6 @@ export class PetService { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } - - // to determine the Content-Type header let consumes: string[] = [ 'application/x-www-form-urlencoded' @@ -545,23 +523,23 @@ export class PetService { 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - + if (name !== undefined) { - formParams.set('name', name); + formParams.set('name', name); } + if (status !== undefined) { - formParams.set('status', status); + formParams.set('status', status); } let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -570,10 +548,10 @@ export class PetService { body: formParams, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -596,8 +574,6 @@ export class PetService { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } - - // to determine the Content-Type header let consumes: string[] = [ 'multipart/form-data' @@ -614,23 +590,23 @@ export class PetService { 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - + if (additionalMetadata !== undefined) { - formParams.set('additionalMetadata', additionalMetadata); + formParams.set('additionalMetadata', additionalMetadata); } + if (file !== undefined) { - formParams.set('file', file); + formParams.set('file', file); } let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -639,10 +615,10 @@ export class PetService { body: formParams, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/default/api/store.service.ts b/samples/client/petstore/typescript-angular2/default/api/store.service.ts index 912ec0517df..b7d2fbf66ae 100644 --- a/samples/client/petstore/typescript-angular2/default/api/store.service.ts +++ b/samples/client/petstore/typescript-angular2/default/api/store.service.ts @@ -20,7 +20,7 @@ import '../rxjs-operators'; import { Order } from '../model/order'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -151,26 +151,22 @@ export class StoreService { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -187,31 +183,27 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (api_key) required - if (this.configuration.apiKey) - { + if (this.configuration.apiKey) { headers.set('api_key', this.configuration.apiKey); } + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -233,26 +225,22 @@ export class StoreService { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -270,28 +258,25 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/default/api/user.service.ts b/samples/client/petstore/typescript-angular2/default/api/user.service.ts index e95be165e12..78c0ce2e8eb 100644 --- a/samples/client/petstore/typescript-angular2/default/api/user.service.ts +++ b/samples/client/petstore/typescript-angular2/default/api/user.service.ts @@ -20,7 +20,7 @@ import '../rxjs-operators'; import { User } from '../model/user'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -213,28 +213,25 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -252,28 +249,25 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -291,28 +285,25 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -334,26 +325,22 @@ export class UserService { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -375,26 +362,22 @@ export class UserService { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -413,12 +396,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (username !== undefined) { - queryParameters.set('username', username); - } - if (password !== undefined) { - queryParameters.set('password', password); + if(username instanceof Date) { + queryParameters.set('username', username.d.toISOString()); + } else { + queryParameters.set('username', username); + } } + if (password !== undefined) { + if(password instanceof Date) { + queryParameters.set('password', password.d.toISOString()); + } else { + queryParameters.set('password', password); + } + } // to determine the Accept header @@ -426,19 +417,17 @@ export class UserService { 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -455,26 +444,22 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -497,28 +482,25 @@ export class UserService { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/default/variables.ts b/samples/client/petstore/typescript-angular2/default/variables.ts index 27b987e9b23..944e688f1b1 100644 --- a/samples/client/petstore/typescript-angular2/default/variables.ts +++ b/samples/client/petstore/typescript-angular2/default/variables.ts @@ -1,3 +1,9 @@ import { OpaqueToken } from '@angular/core'; -export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file +export const BASE_PATH = new OpaqueToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/npm/README.md b/samples/client/petstore/typescript-angular2/npm/README.md index 8a9b25d452a..b320f559464 100644 --- a/samples/client/petstore/typescript-angular2/npm/README.md +++ b/samples/client/petstore/typescript-angular2/npm/README.md @@ -1,4 +1,4 @@ -## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201701051741 +## @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201702102323 ### Building @@ -19,7 +19,7 @@ navigate to the folder of your consuming project and run one of next commando's. _published:_ ``` -npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201701051741 --save +npm install @swagger/angular2-typescript-petstore@0.0.1-SNAPSHOT.201702102323 --save ``` _unPublished (not recommended):_ @@ -41,4 +41,4 @@ import { BASE_PATH } from './path-to-swagger-gen-service/index'; bootstrap(AppComponent, [ { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, ]); -``` +``` \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular2/npm/api/api.ts b/samples/client/petstore/typescript-angular2/npm/api/api.ts index b7d674969f5..734223c2269 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/api.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/api.ts @@ -1,3 +1,4 @@ export * from './pet.service'; export * from './store.service'; export * from './user.service'; +export const APIS = [ PetService, StoreService, UserService, ]; diff --git a/samples/client/petstore/typescript-angular2/npm/api/pet.service.ts b/samples/client/petstore/typescript-angular2/npm/api/pet.service.ts index 14eb4b9e794..6746558021f 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/pet.service.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/pet.service.ts @@ -20,7 +20,7 @@ import '../rxjs-operators'; import { Pet } from '../model/pet'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -217,37 +217,34 @@ export class PetService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -269,7 +266,6 @@ export class PetService { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling deletePet.'); } - headers.set('api_key', String(apiKey)); @@ -278,28 +274,26 @@ export class PetService { 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -316,39 +310,38 @@ export class PetService { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - if (status !== undefined) { - queryParameters.set('status', status); + if (status) { + status.forEach((element) => { + queryParameters.append('status', element); + }) } - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -365,39 +358,38 @@ export class PetService { let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - if (tags !== undefined) { - queryParameters.set('tags', tags); + if (tags) { + tags.forEach((element) => { + queryParameters.append('tags', element); + }) } - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -419,45 +411,36 @@ export class PetService { throw new Error('Required parameter petId was null or undefined when calling getPetById.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + // authentication (api_key) required - if (this.configuration.apiKey) - { - headers.set('api_key', this.configuration.apiKey); - } - // authentication (api_key) required - if (this.configuration.apiKey) - { + if (this.configuration.apiKey) { headers.set('api_key', this.configuration.apiKey); } + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -475,37 +458,34 @@ export class PetService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -528,8 +508,6 @@ export class PetService { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); } - - // to determine the Content-Type header let consumes: string[] = [ 'application/x-www-form-urlencoded' @@ -545,23 +523,23 @@ export class PetService { 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - + if (name !== undefined) { - formParams.set('name', name); + formParams.set('name', name); } + if (status !== undefined) { - formParams.set('status', status); + formParams.set('status', status); } let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -570,10 +548,10 @@ export class PetService { body: formParams, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -596,8 +574,6 @@ export class PetService { if (petId === null || petId === undefined) { throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); } - - // to determine the Content-Type header let consumes: string[] = [ 'multipart/form-data' @@ -614,23 +590,23 @@ export class PetService { 'application/json', 'application/xml' ]; - + // authentication (petstore_auth) required // oauth required - if (this.configuration.accessToken) - { + if (this.configuration.accessToken) { let accessToken = typeof this.configuration.accessToken === 'function' ? this.configuration.accessToken() : this.configuration.accessToken; headers.set('Authorization', 'Bearer ' + accessToken); } - + if (additionalMetadata !== undefined) { - formParams.set('additionalMetadata', additionalMetadata); + formParams.set('additionalMetadata', additionalMetadata); } + if (file !== undefined) { - formParams.set('file', file); + formParams.set('file', file); } let requestOptions: RequestOptionsArgs = new RequestOptions({ @@ -639,10 +615,10 @@ export class PetService { body: formParams, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/npm/api/store.service.ts b/samples/client/petstore/typescript-angular2/npm/api/store.service.ts index 912ec0517df..b7d2fbf66ae 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/store.service.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/store.service.ts @@ -20,7 +20,7 @@ import '../rxjs-operators'; import { Order } from '../model/order'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -151,26 +151,22 @@ export class StoreService { throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -187,31 +183,27 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + // authentication (api_key) required - if (this.configuration.apiKey) - { + if (this.configuration.apiKey) { headers.set('api_key', this.configuration.apiKey); } + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -233,26 +225,22 @@ export class StoreService { throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -270,28 +258,25 @@ export class StoreService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/npm/api/user.service.ts b/samples/client/petstore/typescript-angular2/npm/api/user.service.ts index e95be165e12..78c0ce2e8eb 100644 --- a/samples/client/petstore/typescript-angular2/npm/api/user.service.ts +++ b/samples/client/petstore/typescript-angular2/npm/api/user.service.ts @@ -20,7 +20,7 @@ import '../rxjs-operators'; import { User } from '../model/user'; -import { BASE_PATH } from '../variables'; +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @@ -213,28 +213,25 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -252,28 +249,25 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -291,28 +285,25 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -334,26 +325,22 @@ export class UserService { throw new Error('Required parameter username was null or undefined when calling deleteUser.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -375,26 +362,22 @@ export class UserService { throw new Error('Required parameter username was null or undefined when calling getUserByName.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -413,12 +396,20 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (username !== undefined) { - queryParameters.set('username', username); - } - if (password !== undefined) { - queryParameters.set('password', password); + if(username instanceof Date) { + queryParameters.set('username', username.d.toISOString()); + } else { + queryParameters.set('username', username); + } } + if (password !== undefined) { + if(password instanceof Date) { + queryParameters.set('password', password.d.toISOString()); + } else { + queryParameters.set('password', password); + } + } // to determine the Accept header @@ -426,19 +417,17 @@ export class UserService { 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -455,26 +444,22 @@ export class UserService { let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + - - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); @@ -497,28 +482,25 @@ export class UserService { throw new Error('Required parameter username was null or undefined when calling updateUser.'); } - - // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml' ]; - + headers.set('Content-Type', 'application/json'); - let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612 search: queryParameters }); - + // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { - requestOptions = this.extendObj(requestOptions, extraHttpRequestParams); + requestOptions = (Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); diff --git a/samples/client/petstore/typescript-angular2/npm/package.json b/samples/client/petstore/typescript-angular2/npm/package.json index 8b631d78947..1e14f0fb963 100644 --- a/samples/client/petstore/typescript-angular2/npm/package.json +++ b/samples/client/petstore/typescript-angular2/npm/package.json @@ -1,6 +1,6 @@ { "name": "@swagger/angular2-typescript-petstore", - "version": "0.0.1-SNAPSHOT.201701051741", + "version": "0.0.1-SNAPSHOT.201702102323", "description": "swagger client for @swagger/angular2-typescript-petstore", "author": "Swagger Codegen Contributors", "keywords": [ diff --git a/samples/client/petstore/typescript-angular2/npm/variables.ts b/samples/client/petstore/typescript-angular2/npm/variables.ts index 27b987e9b23..944e688f1b1 100644 --- a/samples/client/petstore/typescript-angular2/npm/variables.ts +++ b/samples/client/petstore/typescript-angular2/npm/variables.ts @@ -1,3 +1,9 @@ import { OpaqueToken } from '@angular/core'; -export const BASE_PATH = new OpaqueToken('basePath'); \ No newline at end of file +export const BASE_PATH = new OpaqueToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/default/api.ts b/samples/client/petstore/typescript-node/default/api.ts index 5b80c2160be..6e000ccd383 100644 --- a/samples/client/petstore/typescript-node/default/api.ts +++ b/samples/client/petstore/typescript-node/default/api.ts @@ -461,14 +461,6 @@ export class PetApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Add a new pet to the store * @@ -477,7 +469,7 @@ export class PetApi { public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -529,7 +521,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -584,7 +576,7 @@ export class PetApi { public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByStatus'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -638,7 +630,7 @@ export class PetApi { public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByTags'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -693,7 +685,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -750,7 +742,7 @@ export class PetApi { public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -803,7 +795,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -868,7 +860,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}/uploadImage' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -963,14 +955,6 @@ export class StoreApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -980,7 +964,7 @@ export class StoreApi { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1031,7 +1015,7 @@ export class StoreApi { public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { const localVarPath = this.basePath + '/store/inventory'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1082,7 +1066,7 @@ export class StoreApi { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1135,7 +1119,7 @@ export class StoreApi { public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { const localVarPath = this.basePath + '/store/order'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1216,14 +1200,6 @@ export class UserApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Create user * This can only be done by the logged in user. @@ -1232,7 +1208,7 @@ export class UserApi { public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1280,7 +1256,7 @@ export class UserApi { public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithArray'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1328,7 +1304,7 @@ export class UserApi { public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithList'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1377,7 +1353,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1430,7 +1406,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1484,7 +1460,7 @@ export class UserApi { public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { const localVarPath = this.basePath + '/user/login'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1539,7 +1515,7 @@ export class UserApi { public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/logout'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1588,7 +1564,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; diff --git a/samples/client/petstore/typescript-node/npm/api.ts b/samples/client/petstore/typescript-node/npm/api.ts index 5b80c2160be..6e000ccd383 100644 --- a/samples/client/petstore/typescript-node/npm/api.ts +++ b/samples/client/petstore/typescript-node/npm/api.ts @@ -461,14 +461,6 @@ export class PetApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Add a new pet to the store * @@ -477,7 +469,7 @@ export class PetApi { public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -529,7 +521,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -584,7 +576,7 @@ export class PetApi { public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByStatus'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -638,7 +630,7 @@ export class PetApi { public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { const localVarPath = this.basePath + '/pet/findByTags'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -693,7 +685,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -750,7 +742,7 @@ export class PetApi { public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/pet'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -803,7 +795,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -868,7 +860,7 @@ export class PetApi { const localVarPath = this.basePath + '/pet/{petId}/uploadImage' .replace('{' + 'petId' + '}', String(petId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -963,14 +955,6 @@ export class StoreApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -980,7 +964,7 @@ export class StoreApi { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1031,7 +1015,7 @@ export class StoreApi { public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { const localVarPath = this.basePath + '/store/inventory'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1082,7 +1066,7 @@ export class StoreApi { const localVarPath = this.basePath + '/store/order/{orderId}' .replace('{' + 'orderId' + '}', String(orderId)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1135,7 +1119,7 @@ export class StoreApi { public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { const localVarPath = this.basePath + '/store/order'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1216,14 +1200,6 @@ export class UserApi { set accessToken(token: string) { this.authentications.petstore_auth.accessToken = token; } - private extendObj(objA: T1, objB: T2) { - for(let key in objB){ - if(objB.hasOwnProperty(key)){ - objA[key] = objB[key]; - } - } - return objA; - } /** * Create user * This can only be done by the logged in user. @@ -1232,7 +1208,7 @@ export class UserApi { public createUser (body?: User) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1280,7 +1256,7 @@ export class UserApi { public createUsersWithArrayInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithArray'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1328,7 +1304,7 @@ export class UserApi { public createUsersWithListInput (body?: Array) : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/createWithList'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1377,7 +1353,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1430,7 +1406,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1484,7 +1460,7 @@ export class UserApi { public loginUser (username?: string, password?: string) : Promise<{ response: http.ClientResponse; body: string; }> { const localVarPath = this.basePath + '/user/login'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1539,7 +1515,7 @@ export class UserApi { public logoutUser () : Promise<{ response: http.ClientResponse; body?: any; }> { const localVarPath = this.basePath + '/user/logout'; let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; @@ -1588,7 +1564,7 @@ export class UserApi { const localVarPath = this.basePath + '/user/{username}' .replace('{' + 'username' + '}', String(username)); let queryParameters: any = {}; - let headerParams: any = this.extendObj({}, this.defaultHeaders); + let headerParams: any = (Object).assign({}, this.defaultHeaders); let formParams: any = {}; diff --git a/samples/html/index.html b/samples/html/index.html index 5d4bf9f1493..60e62451c1c 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -356,18 +356,18 @@ font-style: italic;

    Example data

    Content-Type: application/json
    [ {
    -  "tags" : [ {
    -    "id" : 123456789,
    -    "name" : "aeiou"
    -  } ],
    +  "photoUrls" : [ "aeiou" ],
    +  "name" : "doggie",
       "id" : 123456789,
       "category" : {
    -    "id" : 123456789,
    -    "name" : "aeiou"
    +    "name" : "aeiou",
    +    "id" : 123456789
       },
    -  "status" : "aeiou",
    -  "name" : "doggie",
    -  "photoUrls" : [ "aeiou" ]
    +  "tags" : [ {
    +    "name" : "aeiou",
    +    "id" : 123456789
    +  } ],
    +  "status" : "aeiou"
     } ]

    Produces

    @@ -429,18 +429,18 @@ font-style: italic;

    Example data

    Content-Type: application/json
    [ {
    -  "tags" : [ {
    -    "id" : 123456789,
    -    "name" : "aeiou"
    -  } ],
    +  "photoUrls" : [ "aeiou" ],
    +  "name" : "doggie",
       "id" : 123456789,
       "category" : {
    -    "id" : 123456789,
    -    "name" : "aeiou"
    +    "name" : "aeiou",
    +    "id" : 123456789
       },
    -  "status" : "aeiou",
    -  "name" : "doggie",
    -  "photoUrls" : [ "aeiou" ]
    +  "tags" : [ {
    +    "name" : "aeiou",
    +    "id" : 123456789
    +  } ],
    +  "status" : "aeiou"
     } ]

    Produces

    @@ -502,18 +502,18 @@ font-style: italic;

    Example data

    Content-Type: application/json
    {
    -  "tags" : [ {
    -    "id" : 123456789,
    -    "name" : "aeiou"
    -  } ],
    +  "photoUrls" : [ "aeiou" ],
    +  "name" : "doggie",
       "id" : 123456789,
       "category" : {
    -    "id" : 123456789,
    -    "name" : "aeiou"
    +    "name" : "aeiou",
    +    "id" : 123456789
       },
    -  "status" : "aeiou",
    -  "name" : "doggie",
    -  "photoUrls" : [ "aeiou" ]
    +  "tags" : [ {
    +    "name" : "aeiou",
    +    "id" : 123456789
    +  } ],
    +  "status" : "aeiou"
     }

    Produces

    @@ -679,9 +679,9 @@ font-style: italic;

    Example data

    Content-Type: application/json
    {
    -  "message" : "aeiou",
       "code" : 123,
    -  "type" : "aeiou"
    +  "type" : "aeiou",
    +  "message" : "aeiou"
     }

    Produces

    @@ -818,12 +818,12 @@ font-style: italic;

    Example data

    Content-Type: application/json
    {
    -  "id" : 123456789,
       "petId" : 123456789,
    -  "complete" : true,
    -  "status" : "aeiou",
       "quantity" : 123,
    -  "shipDate" : "2000-01-23T04:56:07.000+00:00"
    +  "id" : 123456789,
    +  "shipDate" : "2000-01-23T04:56:07.000+00:00",
    +  "complete" : true,
    +  "status" : "aeiou"
     }

    Produces

    @@ -887,12 +887,12 @@ font-style: italic;

    Example data

    Content-Type: application/json
    {
    -  "id" : 123456789,
       "petId" : 123456789,
    -  "complete" : true,
    -  "status" : "aeiou",
       "quantity" : 123,
    -  "shipDate" : "2000-01-23T04:56:07.000+00:00"
    +  "id" : 123456789,
    +  "shipDate" : "2000-01-23T04:56:07.000+00:00",
    +  "complete" : true,
    +  "status" : "aeiou"
     }

    Produces

    @@ -1109,14 +1109,14 @@ font-style: italic;

    Example data

    Content-Type: application/json
    {
    -  "id" : 123456789,
    -  "lastName" : "aeiou",
    -  "phone" : "aeiou",
    -  "username" : "aeiou",
    -  "email" : "aeiou",
    -  "userStatus" : 123,
       "firstName" : "aeiou",
    -  "password" : "aeiou"
    +  "lastName" : "aeiou",
    +  "password" : "aeiou",
    +  "userStatus" : 123,
    +  "phone" : "aeiou",
    +  "id" : 123456789,
    +  "email" : "aeiou",
    +  "username" : "aeiou"
     }

    Produces

    diff --git a/samples/html2/index.html b/samples/html2/index.html index 26881d448da..bec62b55586 100644 --- a/samples/html2/index.html +++ b/samples/html2/index.html @@ -1006,6 +1006,8 @@ margin-bottom: 20px;
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -1161,6 +1163,46 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $body = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store
    +
    +eval { 
    +    $api_instance->addPet(body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->addPet: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +body =  # Pet | Pet object that needs to be added to the store
    +
    +try: 
    +    # Add a new pet to the store
    +    api_instance.addPet(body)
    +except ApiException as e:
    +    print("Exception when calling PetApi->addPet: %s\n" % e)
    +

    Parameters

    @@ -1253,6 +1295,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -1417,6 +1461,48 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $petId = 789; # Long | Pet id to delete
    +my $apiKey = apiKey_example; # String | 
    +
    +eval { 
    +    $api_instance->deletePet(petId => $petId, apiKey => $apiKey);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->deletePet: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +petId = 789 # Long | Pet id to delete
    +apiKey = apiKey_example # String |  (optional)
    +
    +try: 
    +    # Deletes a pet
    +    api_instance.deletePet(petId, apiKey=apiKey)
    +except ApiException as e:
    +    print("Exception when calling PetApi->deletePet: %s\n" % e)
    +

    Parameters

    @@ -1446,7 +1532,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_deletePet_petId'); result.empty(); result.append(view.render()); @@ -1486,7 +1572,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_deletePet_apiKey'); result.empty(); result.append(view.render()); @@ -1538,6 +1624,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -1700,6 +1788,48 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $status = []; # array[String] | Status values that need to be considered for filter
    +
    +eval { 
    +    my $result = $api_instance->findPetsByStatus(status => $status);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->findPetsByStatus: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +status =  # array[String] | Status values that need to be considered for filter
    +
    +try: 
    +    # Finds Pets by status
    +    api_response = api_instance.findPetsByStatus(status)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling PetApi->findPetsByStatus: %s\n" % e)
    +

    Parameters

    @@ -1728,8 +1858,8 @@ try { "type" : "array", "items" : { "type" : "string", - "default" : "available", - "enum" : [ "available", "pending", "sold" ] + "enum" : [ "available", "pending", "sold" ], + "default" : "available" }, "collectionFormat" : "csv" }; @@ -1738,7 +1868,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_findPetsByStatus_status'); result.empty(); result.append(view.render()); @@ -1832,6 +1962,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -1994,6 +2126,48 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $tags = []; # array[String] | Tags to filter by
    +
    +eval { 
    +    my $result = $api_instance->findPetsByTags(tags => $tags);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->findPetsByTags: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +tags =  # array[String] | Tags to filter by
    +
    +try: 
    +    # Finds Pets by tags
    +    api_response = api_instance.findPetsByTags(tags)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling PetApi->findPetsByTags: %s\n" % e)
    +

    Parameters

    @@ -2030,7 +2204,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_findPetsByTags_tags'); result.empty(); result.append(view.render()); @@ -2124,11 +2298,13 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • -
    curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/pet/{petId}"
    +
    curl -X get -H "api_key: [[apiKey]]" "http://petstore.swagger.io/v2/pet/{petId}"
    import io.swagger.client.*;
    @@ -2296,6 +2472,52 @@ try {
     }
     ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure API key authorization: api_key
    +$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY';
    +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer";
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $petId = 789; # Long | ID of pet to return
    +
    +eval { 
    +    my $result = $api_instance->getPetById(petId => $petId);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->getPetById: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure API key authorization: api_key
    +swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'
    +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +# swagger_client.configuration.api_key_prefix['api_key'] = 'Bearer'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +petId = 789 # Long | ID of pet to return
    +
    +try: 
    +    # Find pet by ID
    +    api_response = api_instance.getPetById(petId)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling PetApi->getPetById: %s\n" % e)
    +

    Parameters

    @@ -2325,7 +2547,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_getPetById_petId'); result.empty(); result.append(view.render()); @@ -2422,6 +2644,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -2577,6 +2801,46 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $body = WWW::SwaggerClient::Object::Pet->new(); # Pet | Pet object that needs to be added to the store
    +
    +eval { 
    +    $api_instance->updatePet(body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->updatePet: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +body =  # Pet | Pet object that needs to be added to the store
    +
    +try: 
    +    # Update an existing pet
    +    api_instance.updatePet(body)
    +except ApiException as e:
    +    print("Exception when calling PetApi->updatePet: %s\n" % e)
    +

    Parameters

    @@ -2673,6 +2937,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -2844,6 +3110,50 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $petId = 789; # Long | ID of pet that needs to be updated
    +my $name = name_example; # String | Updated name of the pet
    +my $status = status_example; # String | Updated status of the pet
    +
    +eval { 
    +    $api_instance->updatePetWithForm(petId => $petId, name => $name, status => $status);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->updatePetWithForm: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +petId = 789 # Long | 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)
    +
    +try: 
    +    # Updates a pet in the store with form data
    +    api_instance.updatePetWithForm(petId, name=name, status=status)
    +except ApiException as e:
    +    print("Exception when calling PetApi->updatePetWithForm: %s\n" % e)
    +

    Parameters

    @@ -2873,7 +3183,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_updatePetWithForm_petId'); result.empty(); result.append(view.render()); @@ -2916,7 +3226,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_updatePetWithForm_name'); result.empty(); result.append(view.render()); @@ -2949,7 +3259,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_updatePetWithForm_status'); result.empty(); result.append(view.render()); @@ -2999,6 +3309,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -3140,7 +3452,7 @@ namespace Example var apiInstance = new PetApi(); var petId = 789; // Long | ID of pet to update var additionalMetadata = additionalMetadata_example; // String | Additional data to pass to server (optional) - var file = /path/to/file.txt; // File | file to upload (optional) + var file = new File(); // File | file to upload (optional) try { @@ -3177,6 +3489,52 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::PetApi;
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +$WWW::SwaggerClient::Configuration::access_token = 'YOUR_ACCESS_TOKEN';
    +
    +my $api_instance = WWW::SwaggerClient::PetApi->new();
    +my $petId = 789; # Long | ID of pet to update
    +my $additionalMetadata = additionalMetadata_example; # String | Additional data to pass to server
    +my $file = /path/to/file.txt; # File | file to upload
    +
    +eval { 
    +    my $result = $api_instance->uploadFile(petId => $petId, additionalMetadata => $additionalMetadata, file => $file);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling PetApi->uploadFile: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure OAuth2 access token for authorization: petstore_auth
    +swagger_client.configuration.access_token = 'YOUR_ACCESS_TOKEN'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.PetApi()
    +petId = 789 # Long | ID of pet to update
    +additionalMetadata = additionalMetadata_example # String | Additional data to pass to server (optional)
    +file = /path/to/file.txt # File | file to upload (optional)
    +
    +try: 
    +    # uploads an image
    +    api_response = api_instance.uploadFile(petId, additionalMetadata=additionalMetadata, file=file)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling PetApi->uploadFile: %s\n" % e)
    +

    Parameters

    @@ -3206,7 +3564,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_uploadFile_petId'); result.empty(); result.append(view.render()); @@ -3249,7 +3607,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_uploadFile_additionalMetadata'); result.empty(); result.append(view.render()); @@ -3282,7 +3640,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_uploadFile_file'); result.empty(); result.append(view.render()); @@ -3375,6 +3733,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -3509,6 +3869,40 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::StoreApi;
    +
    +my $api_instance = WWW::SwaggerClient::StoreApi->new();
    +my $orderId = orderId_example; # String | ID of the order that needs to be deleted
    +
    +eval { 
    +    $api_instance->deleteOrder(orderId => $orderId);
    +};
    +if ($@) {
    +    warn "Exception when calling StoreApi->deleteOrder: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.StoreApi()
    +orderId = orderId_example # String | ID of the order that needs to be deleted
    +
    +try: 
    +    # Delete purchase order by ID
    +    api_instance.deleteOrder(orderId)
    +except ApiException as e:
    +    print("Exception when calling StoreApi->deleteOrder: %s\n" % e)
    +

    Parameters

    @@ -3530,15 +3924,14 @@ try { "in" : "path", "description" : "ID of the order that needs to be deleted", "required" : true, - "type" : "string", - "minimum" : 1.0 + "type" : "string" }; var schema = schemaWrapper; - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_deleteOrder_orderId'); result.empty(); result.append(view.render()); @@ -3593,11 +3986,13 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • -
    curl -X get -H "api_key: [[apiKey]]"  "http://petstore.swagger.io/v2/store/inventory"
    +
    curl -X get -H "api_key: [[apiKey]]" "http://petstore.swagger.io/v2/store/inventory"
    import io.swagger.client.*;
    @@ -3757,6 +4152,50 @@ try {
     }
     ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::StoreApi;
    +
    +# Configure API key authorization: api_key
    +$WWW::SwaggerClient::Configuration::api_key->{'api_key'} = 'YOUR_API_KEY';
    +# uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +#$WWW::SwaggerClient::Configuration::api_key_prefix->{'api_key'} = "Bearer";
    +
    +my $api_instance = WWW::SwaggerClient::StoreApi->new();
    +
    +eval { 
    +    my $result = $api_instance->getInventory();
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling StoreApi->getInventory: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# Configure API key authorization: api_key
    +swagger_client.configuration.api_key['api_key'] = 'YOUR_API_KEY'
    +# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    +# swagger_client.configuration.api_key_prefix['api_key'] = 'Bearer'
    +
    +# create an instance of the API class
    +api_instance = swagger_client.StoreApi()
    +
    +try: 
    +    # Returns pet inventories by status
    +    api_response = api_instance.getInventory()
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling StoreApi->getInventory: %s\n" % e)
    +

    Parameters

    @@ -3842,6 +4281,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -3983,6 +4424,42 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::StoreApi;
    +
    +my $api_instance = WWW::SwaggerClient::StoreApi->new();
    +my $orderId = 789; # Long | ID of pet that needs to be fetched
    +
    +eval { 
    +    my $result = $api_instance->getOrderById(orderId => $orderId);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling StoreApi->getOrderById: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.StoreApi()
    +orderId = 789 # Long | ID of pet that needs to be fetched
    +
    +try: 
    +    # Find purchase order by ID
    +    api_response = api_instance.getOrderById(orderId)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling StoreApi->getOrderById: %s\n" % e)
    +

    Parameters

    @@ -4014,7 +4491,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_getOrderById_orderId'); result.empty(); result.append(view.render()); @@ -4111,6 +4588,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -4252,6 +4731,42 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::StoreApi;
    +
    +my $api_instance = WWW::SwaggerClient::StoreApi->new();
    +my $body = WWW::SwaggerClient::Object::Order->new(); # Order | order placed for purchasing the pet
    +
    +eval { 
    +    my $result = $api_instance->placeOrder(body => $body);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling StoreApi->placeOrder: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.StoreApi()
    +body =  # Order | order placed for purchasing the pet
    +
    +try: 
    +    # Place an order for a pet
    +    api_response = api_instance.placeOrder(body)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling StoreApi->placeOrder: %s\n" % e)
    +

    Parameters

    @@ -4389,6 +4904,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -4523,6 +5040,40 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $body = WWW::SwaggerClient::Object::User->new(); # User | Created user object
    +
    +eval { 
    +    $api_instance->createUser(body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->createUser: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +body =  # User | Created user object
    +
    +try: 
    +    # Create user
    +    api_instance.createUser(body)
    +except ApiException as e:
    +    print("Exception when calling UserApi->createUser: %s\n" % e)
    +

    Parameters

    @@ -4615,6 +5166,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -4749,6 +5302,40 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $body = [WWW::SwaggerClient::Object::array[User]->new()]; # array[User] | List of user object
    +
    +eval { 
    +    $api_instance->createUsersWithArrayInput(body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->createUsersWithArrayInput: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +body =  # array[User] | List of user object
    +
    +try: 
    +    # Creates list of users with given input array
    +    api_instance.createUsersWithArrayInput(body)
    +except ApiException as e:
    +    print("Exception when calling UserApi->createUsersWithArrayInput: %s\n" % e)
    +

    Parameters

    @@ -4844,6 +5431,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -4978,6 +5567,40 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $body = [WWW::SwaggerClient::Object::array[User]->new()]; # array[User] | List of user object
    +
    +eval { 
    +    $api_instance->createUsersWithListInput(body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->createUsersWithListInput: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +body =  # array[User] | List of user object
    +
    +try: 
    +    # Creates list of users with given input array
    +    api_instance.createUsersWithListInput(body)
    +except ApiException as e:
    +    print("Exception when calling UserApi->createUsersWithListInput: %s\n" % e)
    +

    Parameters

    @@ -5073,6 +5696,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -5207,6 +5832,40 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $username = username_example; # String | The name that needs to be deleted
    +
    +eval { 
    +    $api_instance->deleteUser(username => $username);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->deleteUser: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +username = username_example # String | The name that needs to be deleted
    +
    +try: 
    +    # Delete user
    +    api_instance.deleteUser(username)
    +except ApiException as e:
    +    print("Exception when calling UserApi->deleteUser: %s\n" % e)
    +

    Parameters

    @@ -5235,7 +5894,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_deleteUser_username'); result.empty(); result.append(view.render()); @@ -5290,6 +5949,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -5431,6 +6092,42 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $username = username_example; # String | The name that needs to be fetched. Use user1 for testing. 
    +
    +eval { 
    +    my $result = $api_instance->getUserByName(username => $username);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->getUserByName: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +username = username_example # String | The name that needs to be fetched. Use user1 for testing. 
    +
    +try: 
    +    # Get user by user name
    +    api_response = api_instance.getUserByName(username)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling UserApi->getUserByName: %s\n" % e)
    +

    Parameters

    @@ -5459,7 +6156,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_getUserByName_username'); result.empty(); result.append(view.render()); @@ -5556,6 +6253,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -5705,6 +6404,44 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $username = username_example; # String | The user name for login
    +my $password = password_example; # String | The password for login in clear text
    +
    +eval { 
    +    my $result = $api_instance->loginUser(username => $username, password => $password);
    +    print Dumper($result);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->loginUser: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +username = username_example # String | The user name for login
    +password = password_example # String | The password for login in clear text
    +
    +try: 
    +    # Logs user into the system
    +    api_response = api_instance.loginUser(username, password)
    +    pprint(api_response)
    +except ApiException as e:
    +    print("Exception when calling UserApi->loginUser: %s\n" % e)
    +

    Parameters

    @@ -5737,7 +6474,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_loginUser_username'); result.empty(); result.append(view.render()); @@ -5770,7 +6507,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_loginUser_password'); result.empty(); result.append(view.render()); @@ -5873,6 +6610,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -5999,6 +6738,38 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +
    +eval { 
    +    $api_instance->logoutUser();
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->logoutUser: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +
    +try: 
    +    # Logs out current logged in user session
    +    api_instance.logoutUser()
    +except ApiException as e:
    +    print("Exception when calling UserApi->logoutUser: %s\n" % e)
    +

    Parameters

    @@ -6040,6 +6811,8 @@ try {
  • C#
  • PHP
  • +
  • Perl
  • +
  • Python
  • @@ -6182,6 +6955,42 @@ try { } ?>
    + +
    +
    use Data::Dumper;
    +use WWW::SwaggerClient::Configuration;
    +use WWW::SwaggerClient::UserApi;
    +
    +my $api_instance = WWW::SwaggerClient::UserApi->new();
    +my $username = username_example; # String | name that need to be deleted
    +my $body = WWW::SwaggerClient::Object::User->new(); # User | Updated user object
    +
    +eval { 
    +    $api_instance->updateUser(username => $username, body => $body);
    +};
    +if ($@) {
    +    warn "Exception when calling UserApi->updateUser: $@\n";
    +}
    +
    + +
    +
    from __future__ import print_statement
    +import time
    +import swagger_client
    +from swagger_client.rest import ApiException
    +from pprint import pprint
    +
    +# create an instance of the API class
    +api_instance = swagger_client.UserApi()
    +username = username_example # String | name that need to be deleted
    +body =  # User | Updated user object
    +
    +try: 
    +    # Updated user
    +    api_instance.updateUser(username, body)
    +except ApiException as e:
    +    print("Exception when calling UserApi->updateUser: %s\n" % e)
    +

    Parameters

    @@ -6210,7 +7019,7 @@ try { - var view = new JSONSchemaView(schema,0); + var view = new JSONSchemaView(schema,1); var result = $('#d2e199_updateUser_username'); result.empty(); result.append(view.render()); @@ -6303,7 +7112,7 @@ try {
    - Generated 2016-12-16T18:07:47.864+08:00 + Generated 2017-01-24T11:58:21.560-05:00
    diff --git a/samples/server/petstore/aspnetcore/IO.Swagger.sln b/samples/server/petstore/aspnetcore/IO.Swagger.sln index 4289d2b3652..866d0d2802c 100644 --- a/samples/server/petstore/aspnetcore/IO.Swagger.sln +++ b/samples/server/petstore/aspnetcore/IO.Swagger.sln @@ -7,7 +7,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution global.json = global.json EndProjectSection EndProject -Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.xproj", "{85CF9021-4522-4D1B-871B-D4C1C6483FA1}" +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.xproj", "{795C6B14-1C3E-45F5-AF6F-EE47B197FF1E}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,10 +15,10 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {85CF9021-4522-4D1B-871B-D4C1C6483FA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {85CF9021-4522-4D1B-871B-D4C1C6483FA1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {85CF9021-4522-4D1B-871B-D4C1C6483FA1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {85CF9021-4522-4D1B-871B-D4C1C6483FA1}.Release|Any CPU.Build.0 = Release|Any CPU + {795C6B14-1C3E-45F5-AF6F-EE47B197FF1E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {795C6B14-1C3E-45F5-AF6F-EE47B197FF1E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {795C6B14-1C3E-45F5-AF6F-EE47B197FF1E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {795C6B14-1C3E-45F5-AF6F-EE47B197FF1E}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/samples/server/petstore/aspnetcore/global.json b/samples/server/petstore/aspnetcore/global.json index e5360d025ec..ac4c4297ab6 100644 --- a/samples/server/petstore/aspnetcore/global.json +++ b/samples/server/petstore/aspnetcore/global.json @@ -1,7 +1,7 @@ { - "projects": [ "src", "test" ], + "projects": [ "src" ], "sdk": { - "version": "1.0.0-preview2-003121", + "version": "1.0.0-preview3-003171", "runtime": "coreclr" } } \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/IO.Swagger.xproj b/samples/server/petstore/aspnetcore/src/IO.Swagger/IO.Swagger.xproj index 2454fd383ae..577ab91b009 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/IO.Swagger.xproj +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/IO.Swagger.xproj @@ -6,7 +6,7 @@
    - {85CF9021-4522-4D1B-871B-D4C1C6483FA1} + {795C6B14-1C3E-45F5-AF6F-EE47B197FF1E} IO.Swagger .\obj .\bin\ diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/ApiResponse.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/ApiResponse.cs index 962d0de469e..2782644943b 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/ApiResponse.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/ApiResponse.cs @@ -20,19 +20,21 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// Describes the result of uploading an image resource /// [DataContract] public partial class ApiResponse : IEquatable { + /// /// Initializes a new instance of the class. /// /// Code. /// Type. /// Message. - public ApiResponse(int? Code = null, string Type = null, string Message = null) + public ApiResponse(int? Code = default(int?), string Type = default(string), string Message = default(string)) { this.Code = Code; this.Type = Type; @@ -45,20 +47,17 @@ namespace IO.Swagger.Models /// [DataMember(Name="code")] public int? Code { get; set; } - /// /// Gets or Sets Type /// [DataMember(Name="type")] public string Type { get; set; } - /// /// Gets or Sets Message /// [DataMember(Name="message")] public string Message { get; set; } - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Category.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Category.cs index 7bb9e6119ba..55a7bcdc113 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Category.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Category.cs @@ -20,18 +20,20 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// A category for a pet /// [DataContract] public partial class Category : IEquatable { + /// /// Initializes a new instance of the class. /// /// Id. /// Name. - public Category(long? Id = null, string Name = null) + public Category(long? Id = default(long?), string Name = default(string)) { this.Id = Id; this.Name = Name; @@ -43,14 +45,12 @@ namespace IO.Swagger.Models /// [DataMember(Name="id")] public long? Id { get; set; } - /// /// Gets or Sets Name /// [DataMember(Name="name")] public string Name { get; set; } - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Order.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Order.cs index b30b60be618..7b3d9cf31c7 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Order.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Order.cs @@ -20,12 +20,45 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// An order for a pets from the pet store /// [DataContract] public partial class Order : IEquatable { + /// + /// Order Status + /// + /// Order Status + public enum StatusEnum + { + + /// + /// Enum PlacedEnum for "placed" + /// + [EnumMember(Value = "placed")] + PlacedEnum, + + /// + /// Enum ApprovedEnum for "approved" + /// + [EnumMember(Value = "approved")] + ApprovedEnum, + + /// + /// Enum DeliveredEnum for "delivered" + /// + [EnumMember(Value = "delivered")] + DeliveredEnum + } + /// + /// Order Status + /// + /// Order Status + [DataMember(Name="status")] + public StatusEnum? Status { get; set; } + /// /// Initializes a new instance of the class. /// @@ -35,7 +68,7 @@ namespace IO.Swagger.Models /// ShipDate. /// Order Status. /// Complete (default to false). - public Order(long? Id = null, long? PetId = null, int? Quantity = null, DateTime? ShipDate = null, string Status = null, bool? Complete = null) + 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; @@ -59,39 +92,27 @@ namespace IO.Swagger.Models /// [DataMember(Name="id")] public long? Id { get; set; } - /// /// Gets or Sets PetId /// [DataMember(Name="petId")] public long? PetId { get; set; } - /// /// Gets or Sets Quantity /// [DataMember(Name="quantity")] public int? Quantity { get; set; } - /// /// Gets or Sets ShipDate /// [DataMember(Name="shipDate")] public DateTime? ShipDate { get; set; } - - /// - /// Order Status - /// - /// Order Status - [DataMember(Name="status")] - public string Status { get; set; } - /// /// Gets or Sets Complete /// [DataMember(Name="complete")] public bool? Complete { get; set; } - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Pet.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Pet.cs index be90b4bbb1d..a6454c61726 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Pet.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Pet.cs @@ -20,12 +20,45 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// A pet for sale in the pet store /// [DataContract] public partial class Pet : IEquatable { + /// + /// pet status in the store + /// + /// pet status in the store + public enum StatusEnum + { + + /// + /// Enum AvailableEnum for "available" + /// + [EnumMember(Value = "available")] + AvailableEnum, + + /// + /// Enum PendingEnum for "pending" + /// + [EnumMember(Value = "pending")] + PendingEnum, + + /// + /// Enum SoldEnum for "sold" + /// + [EnumMember(Value = "sold")] + SoldEnum + } + /// + /// pet status in the store + /// + /// pet status in the store + [DataMember(Name="status")] + public StatusEnum? Status { get; set; } + /// /// Initializes a new instance of the class. /// @@ -35,7 +68,7 @@ namespace IO.Swagger.Models /// PhotoUrls (required). /// Tags. /// pet status in the store. - public Pet(long? Id = null, Category Category = null, string Name = null, List PhotoUrls = null, List Tags = null, string Status = null) + 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) if (Name == null) @@ -67,39 +100,27 @@ namespace IO.Swagger.Models /// [DataMember(Name="id")] public long? Id { get; set; } - /// /// Gets or Sets Category /// [DataMember(Name="category")] public Category Category { get; set; } - /// /// Gets or Sets Name /// [DataMember(Name="name")] public string Name { get; set; } - /// /// Gets or Sets PhotoUrls /// [DataMember(Name="photoUrls")] public List PhotoUrls { get; set; } - /// /// Gets or Sets Tags /// [DataMember(Name="tags")] public List Tags { get; set; } - /// - /// pet status in the store - /// - /// pet status in the store - [DataMember(Name="status")] - public string Status { get; set; } - - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Tag.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Tag.cs index 1a813910f15..ea2ca1d6c1e 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Tag.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/Tag.cs @@ -20,18 +20,20 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// A tag for a pet /// [DataContract] public partial class Tag : IEquatable { + /// /// Initializes a new instance of the class. /// /// Id. /// Name. - public Tag(long? Id = null, string Name = null) + public Tag(long? Id = default(long?), string Name = default(string)) { this.Id = Id; this.Name = Name; @@ -43,14 +45,12 @@ namespace IO.Swagger.Models /// [DataMember(Name="id")] public long? Id { get; set; } - /// /// Gets or Sets Name /// [DataMember(Name="name")] public string Name { get; set; } - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/User.cs b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/User.cs index c935fc09316..54b0a00d989 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/User.cs +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/Models/User.cs @@ -20,12 +20,14 @@ using Newtonsoft.Json; namespace IO.Swagger.Models { + /// /// A User who is purchasing from the pet store /// [DataContract] public partial class User : IEquatable { + /// /// Initializes a new instance of the class. /// @@ -37,7 +39,7 @@ namespace IO.Swagger.Models /// Password. /// Phone. /// User Status. - public User(long? Id = null, string Username = null, string FirstName = null, string LastName = null, string Email = null, string Password = null, string Phone = null, int? UserStatus = null) + 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?)) { this.Id = Id; this.Username = Username; @@ -55,43 +57,36 @@ namespace IO.Swagger.Models /// [DataMember(Name="id")] public long? Id { get; set; } - /// /// Gets or Sets Username /// [DataMember(Name="username")] public string Username { get; set; } - /// /// Gets or Sets FirstName /// [DataMember(Name="firstName")] public string FirstName { get; set; } - /// /// Gets or Sets LastName /// [DataMember(Name="lastName")] public string LastName { get; set; } - /// /// Gets or Sets Email /// [DataMember(Name="email")] public string Email { get; set; } - /// /// Gets or Sets Password /// [DataMember(Name="password")] public string Password { get; set; } - /// /// Gets or Sets Phone /// [DataMember(Name="phone")] public string Phone { get; set; } - /// /// User Status /// @@ -99,7 +94,6 @@ namespace IO.Swagger.Models [DataMember(Name="userStatus")] public int? UserStatus { get; set; } - /// /// Returns the string presentation of the object /// diff --git a/samples/server/petstore/aspnetcore/src/IO.Swagger/project.json b/samples/server/petstore/aspnetcore/src/IO.Swagger/project.json index ca8ac967209..de2fe74640d 100644 --- a/samples/server/petstore/aspnetcore/src/IO.Swagger/project.json +++ b/samples/server/petstore/aspnetcore/src/IO.Swagger/project.json @@ -22,7 +22,8 @@ "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0", "Microsoft.EntityFrameworkCore": "1.0.0", "Swashbuckle.SwaggerGen": "6.0.0-beta901", - "Swashbuckle.SwaggerUi": "6.0.0-beta901" + "Swashbuckle.SwaggerUi": "6.0.0-beta901", + "Newtonsoft.Json": "9.0.1" }, "tools": { diff --git a/samples/server/petstore/finch/.swagger-codegen-ignore b/samples/server/petstore/finch/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/finch/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/finch/LICENSE b/samples/server/petstore/finch/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/finch/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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 + + http://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. diff --git a/samples/server/petstore/finch/README.md b/samples/server/petstore/finch/README.md new file mode 100644 index 00000000000..327870827fd --- /dev/null +++ b/samples/server/petstore/finch/README.md @@ -0,0 +1,10 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled scalatra server. + +This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: + +[README](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file diff --git a/samples/server/petstore/finch/build.sbt b/samples/server/petstore/finch/build.sbt new file mode 100644 index 00000000000..b58544b46bd --- /dev/null +++ b/samples/server/petstore/finch/build.sbt @@ -0,0 +1,61 @@ +scalariformSettings + +organization := "io.swagger" + +name := "finch-sample" + +version := "0.1.0-SNAPSHOT" + +scalaVersion := "2.11.8" + +resolvers += Resolver.sonatypeRepo("snapshots") + +resolvers += "TM" at "http://maven.twttr.com" + +resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository" + +resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/" + +resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/" + +Defaults.itSettings + +scalacOptions ++= Seq( + "-deprecation", + "-encoding", "UTF-8", + "-feature", + "-language:existentials", + "-language:higherKinds", + "-language:implicitConversions", + "-unchecked", + "-Yno-adapted-args", + "-Ywarn-dead-code", + "-Ywarn-numeric-widen", + "-Xfuture", + "-Xlint", +// "-Ywarn-unused-import", + "-language:postfixOps" +) + +lazy val `it-config-sbt-project` = project.in(file(".")).configs(IntegrationTest) + +libraryDependencies ++= Seq( + "com.github.finagle" %% "finch-core" % "0.12.0", + "com.github.finagle" %% "finch-circe" % "0.12.0", + "io.circe" %% "circe-generic" % "0.7.0", + "io.circe" %% "circe-java8" % "0.7.0", + "com.twitter" %% "util-core" % "6.40.0", + "com.github.finagle" %% "finch-test" % "0.12.0" % "test", + "org.scalacheck" %% "scalacheck" % "1.13.4" % "test", + "org.scalatest" %% "scalatest" % "3.0.0" % "test" +) + +assemblyMergeStrategy in assembly := { + case "application.conf" => MergeStrategy.concat + case "about.html" => MergeStrategy.discard + case x => + val oldStrategy = (assemblyMergeStrategy in assembly).value + oldStrategy(x) +} + +addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full) diff --git a/samples/server/petstore/finch/project/build.properties b/samples/server/petstore/finch/project/build.properties new file mode 100644 index 00000000000..27e88aa115a --- /dev/null +++ b/samples/server/petstore/finch/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.13.13 diff --git a/samples/server/petstore/finch/project/plugins.sbt b/samples/server/petstore/finch/project/plugins.sbt new file mode 100644 index 00000000000..761afa5688e --- /dev/null +++ b/samples/server/petstore/finch/project/plugins.sbt @@ -0,0 +1,7 @@ +resolvers += Resolver.typesafeRepo("releases") + +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.3") + +// addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.1.4") + +addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.6.0") diff --git a/samples/server/petstore/finch/sbt b/samples/server/petstore/finch/sbt new file mode 100644 index 00000000000..08e58821219 --- /dev/null +++ b/samples/server/petstore/finch/sbt @@ -0,0 +1,525 @@ +#!/usr/bin/env bash +# +# A more capable sbt runner, coincidentally also called sbt. +# Author: Paul Phillips + +# todo - make this dynamic +declare -r sbt_release_version="0.13.6" +declare -r sbt_unreleased_version="0.13.6" +declare -r buildProps="project/build.properties" + +declare sbt_jar sbt_dir sbt_create sbt_version +declare scala_version sbt_explicit_version +declare verbose noshare batch trace_level log_level +declare sbt_saved_stty debugUs + +echoerr () { echo >&2 "$@"; } +vlog () { [[ -n "$verbose" ]] && echoerr "$@"; } + +# spaces are possible, e.g. sbt.version = 0.13.0 +build_props_sbt () { + [[ -r "$buildProps" ]] && \ + grep '^sbt\.version' "$buildProps" | tr '=' ' ' | awk '{ print $2; }' +} + +update_build_props_sbt () { + local ver="$1" + local old="$(build_props_sbt)" + + [[ -r "$buildProps" ]] && [[ "$ver" != "$old" ]] && { + perl -pi -e "s/^sbt\.version\b.*\$/sbt.version=${ver}/" "$buildProps" + grep -q '^sbt.version[ =]' "$buildProps" || printf "\nsbt.version=%s\n" "$ver" >> "$buildProps" + + vlog "!!!" + vlog "!!! Updated file $buildProps setting sbt.version to: $ver" + vlog "!!! Previous value was: $old" + vlog "!!!" + } +} + +set_sbt_version () { + sbt_version="${sbt_explicit_version:-$(build_props_sbt)}" + [[ -n "$sbt_version" ]] || sbt_version=$sbt_release_version + export sbt_version +} + +# restore stty settings (echo in particular) +onSbtRunnerExit() { + [[ -n "$sbt_saved_stty" ]] || return + vlog "" + vlog "restoring stty: $sbt_saved_stty" + stty "$sbt_saved_stty" + unset sbt_saved_stty +} + +# save stty and trap exit, to ensure echo is reenabled if we are interrupted. +trap onSbtRunnerExit EXIT +sbt_saved_stty="$(stty -g 2>/dev/null)" +vlog "Saved stty: $sbt_saved_stty" + +# this seems to cover the bases on OSX, and someone will +# have to tell me about the others. +get_script_path () { + local path="$1" + [[ -L "$path" ]] || { echo "$path" ; return; } + + local target="$(readlink "$path")" + if [[ "${target:0:1}" == "/" ]]; then + echo "$target" + else + echo "${path%/*}/$target" + fi +} + +die() { + echo "Aborting: $@" + exit 1 +} + +make_url () { + version="$1" + + case "$version" in + 0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;; + 0.10.* ) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + 0.11.[12]) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + *) echo "$sbt_launch_repo/org.scala-sbt/sbt-launch/$version/sbt-launch.jar" ;; + esac +} + +init_default_option_file () { + local overriding_var="${!1}" + local default_file="$2" + if [[ ! -r "$default_file" && "$overriding_var" =~ ^@(.*)$ ]]; then + local envvar_file="${BASH_REMATCH[1]}" + if [[ -r "$envvar_file" ]]; then + default_file="$envvar_file" + fi + fi + echo "$default_file" +} + +declare -r cms_opts="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC" +declare -r jit_opts="-XX:ReservedCodeCacheSize=256m -XX:+TieredCompilation" +declare -r default_jvm_opts_common="-Xms512m -Xmx1536m -Xss2m $jit_opts $cms_opts" +declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" +declare -r latest_28="2.8.2" +declare -r latest_29="2.9.3" +declare -r latest_210="2.10.4" +declare -r latest_211="2.11.2" + +declare -r script_path="$(get_script_path "$BASH_SOURCE")" +declare -r script_name="${script_path##*/}" + +# some non-read-onlies set with defaults +declare java_cmd="java" +declare sbt_opts_file="$(init_default_option_file SBT_OPTS .sbtopts)" +declare jvm_opts_file="$(init_default_option_file JVM_OPTS .jvmopts)" +declare sbt_launch_repo="http://typesafe.artifactoryonline.com/typesafe/ivy-releases" + +# pull -J and -D options to give to java. +declare -a residual_args +declare -a java_args +declare -a scalac_args +declare -a sbt_commands + +# args to jvm/sbt via files or environment variables +declare -a extra_jvm_opts extra_sbt_opts + +# if set, use JAVA_HOME over java found in path +[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java" + +# directory to store sbt launchers +declare sbt_launch_dir="$HOME/.sbt/launchers" +[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir" +[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers.XXXXXX)" + +java_version () { + local version=$("$java_cmd" -version 2>&1 | grep -e 'java version' | awk '{ print $3 }' | tr -d \") + vlog "Detected Java version: $version" + echo "${version:2:1}" +} + +# MaxPermSize critical on pre-8 jvms but incurs noisy warning on 8+ +default_jvm_opts () { + local v="$(java_version)" + if [[ $v -ge 8 ]]; then + echo "$default_jvm_opts_common" + else + echo "-XX:MaxPermSize=384m $default_jvm_opts_common" + fi +} + +build_props_scala () { + if [[ -r "$buildProps" ]]; then + versionLine="$(grep '^build.scala.versions' "$buildProps")" + versionString="${versionLine##build.scala.versions=}" + echo "${versionString%% .*}" + fi +} + +execRunner () { + # print the arguments one to a line, quoting any containing spaces + vlog "# Executing command line:" && { + for arg; do + if [[ -n "$arg" ]]; then + if printf "%s\n" "$arg" | grep -q ' '; then + printf >&2 "\"%s\"\n" "$arg" + else + printf >&2 "%s\n" "$arg" + fi + fi + done + vlog "" + } + + [[ -n "$batch" ]] && exec /dev/null; then + curl --fail --silent "$url" --output "$jar" + elif which wget >/dev/null; then + wget --quiet -O "$jar" "$url" + fi + } && [[ -r "$jar" ]] +} + +acquire_sbt_jar () { + sbt_url="$(jar_url "$sbt_version")" + sbt_jar="$(jar_file "$sbt_version")" + + [[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar" +} + +usage () { + cat < display stack traces with a max of frames (default: -1, traces suppressed) + -debug-inc enable debugging log for the incremental compiler + -no-colors disable ANSI color codes + -sbt-create start sbt even if current directory contains no sbt project + -sbt-dir path to global settings/plugins directory (default: ~/.sbt/) + -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11+) + -ivy path to local Ivy repository (default: ~/.ivy2) + -no-share use all local caches; no sharing + -offline put sbt in offline mode + -jvm-debug Turn on JVM debugging, open at the given port. + -batch Disable interactive mode + -prompt Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted + + # sbt version (default: sbt.version from $buildProps if present, otherwise $sbt_release_version) + -sbt-force-latest force the use of the latest release of sbt: $sbt_release_version + -sbt-version use the specified version of sbt (default: $sbt_release_version) + -sbt-dev use the latest pre-release version of sbt: $sbt_unreleased_version + -sbt-jar use the specified jar as the sbt launcher + -sbt-launch-dir directory to hold sbt launchers (default: ~/.sbt/launchers) + -sbt-launch-repo repo url for downloading sbt launcher jar (default: $sbt_launch_repo) + + # scala version (default: as chosen by sbt) + -28 use $latest_28 + -29 use $latest_29 + -210 use $latest_210 + -211 use $latest_211 + -scala-home use the scala build at the specified directory + -scala-version use the specified version of scala + -binary-version use the specified scala version when searching for dependencies + + # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) + -java-home alternate JAVA_HOME + + # passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution + # The default set is used if JVM_OPTS is unset and no -jvm-opts file is found + $(default_jvm_opts) + JVM_OPTS environment variable holding either the jvm args directly, or + the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts') + Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument. + -jvm-opts file containing jvm args (if not given, .jvmopts in project root is used if present) + -Dkey=val pass -Dkey=val directly to the jvm + -J-X pass option -X directly to the jvm (-J is stripped) + + # passing options to sbt, OR to this runner + SBT_OPTS environment variable holding either the sbt args directly, or + the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts') + Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument. + -sbt-opts file containing sbt args (if not given, .sbtopts in project root is used if present) + -S-X add -X to sbt's scalacOptions (-S is stripped) +EOM +} + +addJava () { + vlog "[addJava] arg = '$1'" + java_args=( "${java_args[@]}" "$1" ) +} +addSbt () { + vlog "[addSbt] arg = '$1'" + sbt_commands=( "${sbt_commands[@]}" "$1" ) +} +setThisBuild () { + vlog "[addBuild] args = '$@'" + local key="$1" && shift + addSbt "set $key in ThisBuild := $@" +} + +addScalac () { + vlog "[addScalac] arg = '$1'" + scalac_args=( "${scalac_args[@]}" "$1" ) +} +addResidual () { + vlog "[residual] arg = '$1'" + residual_args=( "${residual_args[@]}" "$1" ) +} +addResolver () { + addSbt "set resolvers += $1" +} +addDebugger () { + addJava "-Xdebug" + addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1" +} +setScalaVersion () { + [[ "$1" == *"-SNAPSHOT" ]] && addResolver 'Resolver.sonatypeRepo("snapshots")' + addSbt "++ $1" +} + +process_args () +{ + require_arg () { + local type="$1" + local opt="$2" + local arg="$3" + + if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then + die "$opt requires <$type> argument" + fi + } + while [[ $# -gt 0 ]]; do + case "$1" in + -h|-help) usage; exit 1 ;; + -v) verbose=true && shift ;; + -d) addSbt "--debug" && shift ;; + -w) addSbt "--warn" && shift ;; + -q) addSbt "--error" && shift ;; + -x) debugUs=true && shift ;; + -trace) require_arg integer "$1" "$2" && trace_level="$2" && shift 2 ;; + -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; + -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; + -no-share) noshare=true && shift ;; + -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; + -sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;; + -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; + -offline) addSbt "set offline := true" && shift ;; + -jvm-debug) require_arg port "$1" "$2" && addDebugger "$2" && shift 2 ;; + -batch) batch=true && shift ;; + -prompt) require_arg "expr" "$1" "$2" && setThisBuild shellPrompt "(s => { val e = Project.extract(s) ; $2 })" && shift 2 ;; + + -sbt-create) sbt_create=true && shift ;; + -sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;; + -sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;; + -sbt-force-latest) sbt_explicit_version="$sbt_release_version" && shift ;; + -sbt-dev) sbt_explicit_version="$sbt_unreleased_version" && shift ;; + -sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;; + -sbt-launch-repo) require_arg path "$1" "$2" && sbt_launch_repo="$2" && shift 2 ;; + -scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;; + -binary-version) require_arg version "$1" "$2" && setThisBuild scalaBinaryVersion "\"$2\"" && shift 2 ;; + -scala-home) require_arg path "$1" "$2" && setThisBuild scalaHome "Some(file(\"$2\"))" && shift 2 ;; + -java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;; + -sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;; + -jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;; + + -D*) addJava "$1" && shift ;; + -J*) addJava "${1:2}" && shift ;; + -S*) addScalac "${1:2}" && shift ;; + -28) setScalaVersion "$latest_28" && shift ;; + -29) setScalaVersion "$latest_29" && shift ;; + -210) setScalaVersion "$latest_210" && shift ;; + -211) setScalaVersion "$latest_211" && shift ;; + + *) addResidual "$1" && shift ;; + esac + done +} + +# process the direct command line arguments +process_args "$@" + +# skip #-styled comments and blank lines +readConfigFile() { + while read line; do + [[ $line =~ ^# ]] || [[ -z $line ]] || echo "$line" + done < "$1" +} + +# if there are file/environment sbt_opts, process again so we +# can supply args to this runner +if [[ -r "$sbt_opts_file" ]]; then + vlog "Using sbt options defined in file $sbt_opts_file" + while read opt; do extra_sbt_opts+=("$opt"); done < <(readConfigFile "$sbt_opts_file") +elif [[ -n "$SBT_OPTS" && ! ("$SBT_OPTS" =~ ^@.*) ]]; then + vlog "Using sbt options defined in variable \$SBT_OPTS" + extra_sbt_opts=( $SBT_OPTS ) +else + vlog "No extra sbt options have been defined" +fi + +[[ -n "${extra_sbt_opts[*]}" ]] && process_args "${extra_sbt_opts[@]}" + +# reset "$@" to the residual args +set -- "${residual_args[@]}" +argumentCount=$# + +# set sbt version +set_sbt_version + +# only exists in 0.12+ +setTraceLevel() { + case "$sbt_version" in + "0.7."* | "0.10."* | "0.11."* ) echoerr "Cannot set trace level in sbt version $sbt_version" ;; + *) setThisBuild traceLevel $trace_level ;; + esac +} + +# set scalacOptions if we were given any -S opts +[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\"" + +# Update build.properties on disk to set explicit version - sbt gives us no choice +[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version" +vlog "Detected sbt version $sbt_version" + +[[ -n "$scala_version" ]] && vlog "Overriding scala version to $scala_version" + +# no args - alert them there's stuff in here +(( argumentCount > 0 )) || { + vlog "Starting $script_name: invoke with -help for other options" + residual_args=( shell ) +} + +# verify this is an sbt dir or -create was given +[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || { + cat < apis -> operations = ??? + // NOTE: ??? throws a not implemented exception + + /** + * + * @return A Unit + */ + def Pet_addPet(body: Pet): Unit = ??? + + /** + * + * @return A Unit + */ + def Pet_deletePet(petId: Long, apiKey: String): Unit = ??? + + /** + * + * @return A Seq[Pet] + */ + def Pet_findPetsByStatus(status: Seq[String]): Seq[Pet] = ??? + + /** + * + * @return A Seq[Pet] + */ + def Pet_findPetsByTags(tags: Seq[String]): Seq[Pet] = ??? + + /** + * + * @return A Pet + */ + def Pet_getPetById(petId: Long): Pet = ??? + + /** + * + * @return A Unit + */ + def Pet_updatePet(body: Pet): Unit = ??? + + /** + * + * @return A Unit + */ + def Pet_updatePetWithForm(petId: Long, name: String, status: String): Unit = ??? + + /** + * + * @return A ApiResponse + */ + def Pet_uploadFile(petId: Long, additionalMetadata: String, file: File): ApiResponse = ??? + + /** + * + * @return A Unit + */ + def Store_deleteOrder(orderId: String): Unit = ??? + + /** + * + * @return A Map[String, Int] + */ + def Store_getInventory(): Map[String, Int] = ??? + + /** + * + * @return A Order + */ + def Store_getOrderById(orderId: Long): Order = ??? + + /** + * + * @return A Order + */ + def Store_placeOrder(body: Order): Order = ??? + + /** + * + * @return A Unit + */ + def User_createUser(body: User): Unit = ??? + + /** + * + * @return A Unit + */ + def User_createUsersWithArrayInput(body: Seq[User]): Unit = ??? + + /** + * + * @return A Unit + */ + def User_createUsersWithListInput(body: Seq[User]): Unit = ??? + + /** + * + * @return A Unit + */ + def User_deleteUser(username: String): Unit = ??? + + /** + * + * @return A User + */ + def User_getUserByName(username: String): User = ??? + + /** + * + * @return A String + */ + def User_loginUser(username: String, password: String): String = ??? + + /** + * + * @return A Unit + */ + def User_logoutUser(): Unit = ??? + + /** + * + * @return A Unit + */ + def User_updateUser(username: String, body: User): Unit = ??? + +} \ No newline at end of file diff --git a/samples/server/petstore/finch/src/main/scala/Server.scala b/samples/server/petstore/finch/src/main/scala/Server.scala new file mode 100644 index 00000000000..716b6eae52e --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/Server.scala @@ -0,0 +1,36 @@ +package io.swagger.petstore + +import io.finch._ +import io.finch.circe._ +import io.circe.{ Decoder, ObjectEncoder } +import io.circe.generic.auto._ +import io.circe.generic.semiauto +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import com.twitter.finagle.Http +import com.twitter.finagle.util.LoadService +import com.twitter.util.{ Await, Future } + +class Server { + + // Loads implementation defined in resources/META-INF/services/io.swagger.petstore.DataAccessor + val db = LoadService[DataAccessor]() match { + case accessor :: _ => accessor + case _ => new DataAccessor {} + } + + val service = endpoint.makeService(db) + + val server = Http.serve(":8080", service) //creates service + + def close(): Future[Unit] = { + Await.ready(server.close()) + } +} + +/** + * Launches the PetstoreAPI service when the system is ready. + */ +object Server extends Server with App { + Await.ready(server) +} diff --git a/samples/server/petstore/finch/src/main/scala/endpoint.scala b/samples/server/petstore/finch/src/main/scala/endpoint.scala new file mode 100644 index 00000000000..df0093b7b13 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/endpoint.scala @@ -0,0 +1,48 @@ +package io.swagger.petstore + +import com.twitter.finagle.Service +import com.twitter.finagle.http.{ Request, Response } +import com.twitter.finagle.http.exp.Multipart.FileUpload +import com.twitter.util.Future +import io.finch._, items._ +import io.circe.{ Encoder, Json } +import io.finch.circe._ +import io.circe.generic.semiauto._ + +import io.swagger.petstore.apis._ + +/** + * Provides the paths and endpoints for all the API's public service methods. + */ +object endpoint { + + def errorToJson(e: Exception): Json = e match { + case Error.NotPresent(_) => + Json.obj("error" -> Json.fromString("something_not_present")) + case Error.NotParsed(_, _, _) => + Json.obj("error" -> Json.fromString("something_not_parsed")) + case Error.NotValid(_, _) => + Json.obj("error" -> Json.fromString("something_not_valid")) + case error: PetstoreError => + Json.obj("error" -> Json.fromString(error.message)) + } + + implicit val ee: Encoder[Exception] = Encoder.instance { + case e: Error => errorToJson(e) + case Errors(nel) => Json.arr(nel.toList.map(errorToJson): _*) + } + + /** + * Compiles together all the endpoints relating to public service methods. + * + * @return A service that contains all provided endpoints of the API. + */ + def makeService(da: DataAccessor): Service[Request, Response] = ( + PetApi.endpoints(da) :+: + StoreApi.endpoints(da) :+: + UserApi.endpoints(da) + ).handle({ + case e: PetstoreError => NotFound(e) + }).toService + +} \ No newline at end of file diff --git a/samples/server/petstore/finch/src/main/scala/errors.scala b/samples/server/petstore/finch/src/main/scala/errors.scala new file mode 100644 index 00000000000..69e3831c15d --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/errors.scala @@ -0,0 +1,27 @@ +package io.swagger.petstore + +/** + * The parent error from which most PetstoreAPI errors extend. Thrown whenever something in the api goes wrong. + */ +abstract class PetstoreError(msg: String) extends Exception(msg) { + def message: String +} + +/** + * Thrown when the object given is invalid + * @param message An error message + */ +case class InvalidInput(message: String) extends PetstoreError(message) + +/** + * Thrown when the given object is missing a unique ID. + * @param message An error message + */ +case class MissingIdentifier(message: String) extends PetstoreError(message) + +/** + * Thrown when the given record does not exist in the database. + * @param message An error message + */ +case class RecordNotFound(message: String) extends PetstoreError(message) + diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/PetApi.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/PetApi.scala new file mode 100644 index 00000000000..420279685d3 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/PetApi.scala @@ -0,0 +1,148 @@ +package io.swagger.petstore.apis + +import java.io._ +import java.util.Date +import io.swagger.petstore._ +import io.swagger.petstore.models._ +import io.swagger.petstore.models.Pet +import java.io.File +import io.swagger.petstore.models.ApiResponse +import io.finch.circe._ +import io.circe.generic.semiauto._ +import com.twitter.concurrent.AsyncStream +import com.twitter.finagle.Service +import com.twitter.finagle.Http +import com.twitter.finagle.http.{ Request, Response } +import com.twitter.finagle.http.exp.Multipart.{ FileUpload, InMemoryFileUpload, OnDiskFileUpload } +import com.twitter.util.Future +import com.twitter.io.Buf +import io.finch._, items._ +import java.io.File + +object PetApi { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + def endpoints(da: DataAccessor) = + addPet(da) :+: + deletePet(da) :+: + findPetsByStatus(da) :+: + findPetsByTags(da) :+: + getPetById(da) :+: + updatePet(da) :+: + updatePetWithForm(da) :+: + uploadFile(da) + + /** + * + * @return And endpoint representing a Unit + */ + private def addPet(da: DataAccessor): Endpoint[Unit] = + post("pet" :: jsonBody[Pet]) { (body: Pet) => + da.Pet_addPet(body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def deletePet(da: DataAccessor): Endpoint[Unit] = + delete("pet" :: long :: string) { (petId: Long, apiKey: String) => + da.Pet_deletePet(petId, apiKey) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Seq[Pet] + */ + private def findPetsByStatus(da: DataAccessor): Endpoint[Seq[Pet]] = + get("pet" :: "findByStatus" :: params("status")) { (status: Seq[String]) => + Ok(da.Pet_findPetsByStatus(status)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Seq[Pet] + */ + private def findPetsByTags(da: DataAccessor): Endpoint[Seq[Pet]] = + get("pet" :: "findByTags" :: params("tags")) { (tags: Seq[String]) => + Ok(da.Pet_findPetsByTags(tags)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Pet + */ + private def getPetById(da: DataAccessor): Endpoint[Pet] = + get("pet" :: long) { (petId: Long) => + Ok(da.Pet_getPetById(petId)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def updatePet(da: DataAccessor): Endpoint[Unit] = + put("pet" :: jsonBody[Pet]) { (body: Pet) => + da.Pet_updatePet(body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def updatePetWithForm(da: DataAccessor): Endpoint[Unit] = + post("pet" :: long :: string :: string) { (petId: Long, name: String, status: String) => + da.Pet_updatePetWithForm(petId, name, status) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a ApiResponse + */ + private def uploadFile(da: DataAccessor): Endpoint[ApiResponse] = + post("pet" :: long :: "uploadImage" :: string :: fileUpload("file")) { (petId: Long, additionalMetadata: String, file: FileUpload) => + Ok(da.Pet_uploadFile(petId, additionalMetadata, file)) + } handle { + case e: Exception => BadRequest(e) + } + + implicit private def fileUploadToFile(fileUpload: FileUpload): File = { + fileUpload match { + case upload: InMemoryFileUpload => + bytesToFile(Buf.ByteArray.Owned.extract(upload.content)) + case upload: OnDiskFileUpload => + upload.content + case _ => null + } + } + + private def bytesToFile(input: Array[Byte]): java.io.File = { + val file = File.createTempFile("tmpPetApi", null) + val output = new FileOutputStream(file) + output.write(input) + file + } + + // This assists in params(string) application (which must be Seq[A] in parameter list) when the param is used as a List[A] elsewhere. + implicit def seqList[A](input: Seq[A]): List[A] = input.toList +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/StoreApi.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/StoreApi.scala new file mode 100644 index 00000000000..38dda7b4786 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/StoreApi.scala @@ -0,0 +1,95 @@ +package io.swagger.petstore.apis + +import java.io._ +import java.util.Date +import io.swagger.petstore._ +import io.swagger.petstore.models._ +import io.swagger.petstore.models.Order +import io.finch.circe._ +import io.circe.generic.semiauto._ +import com.twitter.concurrent.AsyncStream +import com.twitter.finagle.Service +import com.twitter.finagle.Http +import com.twitter.finagle.http.{ Request, Response } +import com.twitter.finagle.http.exp.Multipart.{ FileUpload, InMemoryFileUpload, OnDiskFileUpload } +import com.twitter.util.Future +import com.twitter.io.Buf +import io.finch._, items._ +import java.io.File + +object StoreApi { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + def endpoints(da: DataAccessor) = + deleteOrder(da) :+: + getInventory(da) :+: + getOrderById(da) :+: + placeOrder(da) + + /** + * + * @return And endpoint representing a Unit + */ + private def deleteOrder(da: DataAccessor): Endpoint[Unit] = + delete("store" :: "order" :: string) { (orderId: String) => + da.Store_deleteOrder(orderId) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Map[String, Int] + */ + private def getInventory(da: DataAccessor): Endpoint[Map[String, Int]] = + get("store" :: "inventory") { + Ok(da.Store_getInventory()) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Order + */ + private def getOrderById(da: DataAccessor): Endpoint[Order] = + get("store" :: "order" :: long) { (orderId: Long) => + Ok(da.Store_getOrderById(orderId)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Order + */ + private def placeOrder(da: DataAccessor): Endpoint[Order] = + post("store" :: "order" :: jsonBody[Order]) { (body: Order) => + Ok(da.Store_placeOrder(body)) + } handle { + case e: Exception => BadRequest(e) + } + + implicit private def fileUploadToFile(fileUpload: FileUpload): File = { + fileUpload match { + case upload: InMemoryFileUpload => + bytesToFile(Buf.ByteArray.Owned.extract(upload.content)) + case upload: OnDiskFileUpload => + upload.content + case _ => null + } + } + + private def bytesToFile(input: Array[Byte]): java.io.File = { + val file = File.createTempFile("tmpStoreApi", null) + val output = new FileOutputStream(file) + output.write(input) + file + } + + // This assists in params(string) application (which must be Seq[A] in parameter list) when the param is used as a List[A] elsewhere. + implicit def seqList[A](input: Seq[A]): List[A] = input.toList +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/UserApi.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/UserApi.scala new file mode 100644 index 00000000000..560509a349c --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/UserApi.scala @@ -0,0 +1,149 @@ +package io.swagger.petstore.apis + +import java.io._ +import java.util.Date +import io.swagger.petstore._ +import io.swagger.petstore.models._ +import io.swagger.petstore.models.User +import scala.collection.immutable.Seq +import io.finch.circe._ +import io.circe.generic.semiauto._ +import com.twitter.concurrent.AsyncStream +import com.twitter.finagle.Service +import com.twitter.finagle.Http +import com.twitter.finagle.http.{ Request, Response } +import com.twitter.finagle.http.exp.Multipart.{ FileUpload, InMemoryFileUpload, OnDiskFileUpload } +import com.twitter.util.Future +import com.twitter.io.Buf +import io.finch._, items._ +import java.io.File + +object UserApi { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + def endpoints(da: DataAccessor) = + createUser(da) :+: + createUsersWithArrayInput(da) :+: + createUsersWithListInput(da) :+: + deleteUser(da) :+: + getUserByName(da) :+: + loginUser(da) :+: + logoutUser(da) :+: + updateUser(da) + + /** + * + * @return And endpoint representing a Unit + */ + private def createUser(da: DataAccessor): Endpoint[Unit] = + post("user" :: jsonBody[User]) { (body: User) => + da.User_createUser(body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def createUsersWithArrayInput(da: DataAccessor): Endpoint[Unit] = + post("user" :: "createWithArray" :: jsonBody[Seq[User]]) { (body: Seq[User]) => + da.User_createUsersWithArrayInput(body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def createUsersWithListInput(da: DataAccessor): Endpoint[Unit] = + post("user" :: "createWithList" :: jsonBody[Seq[User]]) { (body: Seq[User]) => + da.User_createUsersWithListInput(body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def deleteUser(da: DataAccessor): Endpoint[Unit] = + delete("user" :: string) { (username: String) => + da.User_deleteUser(username) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a User + */ + private def getUserByName(da: DataAccessor): Endpoint[User] = + get("user" :: string) { (username: String) => + Ok(da.User_getUserByName(username)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a String + */ + private def loginUser(da: DataAccessor): Endpoint[String] = + get("user" :: "login" :: string :: string) { (username: String, password: String) => + Ok(da.User_loginUser(username, password)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def logoutUser(da: DataAccessor): Endpoint[Unit] = + get("user" :: "logout") { + da.User_logoutUser() + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def updateUser(da: DataAccessor): Endpoint[Unit] = + put("user" :: string :: jsonBody[User]) { (username: String, body: User) => + da.User_updateUser(username, body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + implicit private def fileUploadToFile(fileUpload: FileUpload): File = { + fileUpload match { + case upload: InMemoryFileUpload => + bytesToFile(Buf.ByteArray.Owned.extract(upload.content)) + case upload: OnDiskFileUpload => + upload.content + case _ => null + } + } + + private def bytesToFile(input: Array[Byte]): java.io.File = { + val file = File.createTempFile("tmpUserApi", null) + val output = new FileOutputStream(file) + output.write(input) + file + } + + // This assists in params(string) application (which must be Seq[A] in parameter list) when the param is used as a List[A] elsewhere. + implicit def seqList[A](input: Seq[A]): List[A] = input.toList +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/ApiResponse.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/ApiResponse.scala new file mode 100644 index 00000000000..248833a4e75 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/ApiResponse.scala @@ -0,0 +1,27 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ + +/** + * Describes the result of uploading an image resource + * @param code + * @param _type + * @param message + */ +case class ApiResponse( + code: Option[Int], + _type: Option[String], + message: Option[String] +) + +object ApiResponse { + /** + * Creates the codec for converting ApiResponse from and to JSON. + */ + implicit val decoder: Decoder[ApiResponse] = deriveDecoder + implicit val encoder: ObjectEncoder[ApiResponse] = deriveEncoder +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Category.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Category.scala new file mode 100644 index 00000000000..ceb17f6b7e7 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Category.scala @@ -0,0 +1,25 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ + +/** + * A category for a pet + * @param id + * @param name + */ +case class Category( + id: Option[Long], + name: Option[String] +) + +object Category { + /** + * Creates the codec for converting Category from and to JSON. + */ + implicit val decoder: Decoder[Category] = deriveDecoder + implicit val encoder: ObjectEncoder[Category] = deriveEncoder +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Order.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Order.scala new file mode 100644 index 00000000000..08743ebbf13 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Order.scala @@ -0,0 +1,34 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ +import java.time.LocalDateTime + +/** + * An order for a pets from the pet store + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ +case class Order( + id: Option[Long], + petId: Option[Long], + quantity: Option[Int], + shipDate: Option[LocalDateTime], + status: Option[String], + complete: Option[Boolean] +) + +object Order { + /** + * Creates the codec for converting Order from and to JSON. + */ + implicit val decoder: Decoder[Order] = deriveDecoder + implicit val encoder: ObjectEncoder[Order] = deriveEncoder +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Pet.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Pet.scala new file mode 100644 index 00000000000..4a17021b726 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Pet.scala @@ -0,0 +1,36 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ +import io.swagger.petstore.models.Category +import io.swagger.petstore.models.Tag +import scala.collection.immutable.Seq + +/** + * A pet for sale in the pet store + * @param id + * @param category + * @param name + * @param photoUrls + * @param tags + * @param status pet status in the store + */ +case class Pet( + id: Option[Long], + category: Option[Category], + name: String, + photoUrls: Seq[String], + tags: Option[Seq[Tag]], + status: Option[String] +) + +object Pet { + /** + * Creates the codec for converting Pet from and to JSON. + */ + implicit val decoder: Decoder[Pet] = deriveDecoder + implicit val encoder: ObjectEncoder[Pet] = deriveEncoder +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Tag.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Tag.scala new file mode 100644 index 00000000000..5fb213c0c3f --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Tag.scala @@ -0,0 +1,25 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ + +/** + * A tag for a pet + * @param id + * @param name + */ +case class Tag( + id: Option[Long], + name: Option[String] +) + +object Tag { + /** + * Creates the codec for converting Tag from and to JSON. + */ + implicit val decoder: Decoder[Tag] = deriveDecoder + implicit val encoder: ObjectEncoder[Tag] = deriveEncoder +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/User.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/User.scala new file mode 100644 index 00000000000..6556cdb437a --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/User.scala @@ -0,0 +1,37 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ + +/** + * A User who is purchasing from the pet store + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ +case class User( + id: Option[Long], + username: Option[String], + firstName: Option[String], + lastName: Option[String], + email: Option[String], + password: Option[String], + phone: Option[String], + userStatus: Option[Int] +) + +object User { + /** + * Creates the codec for converting User from and to JSON. + */ + implicit val decoder: Decoder[User] = deriveDecoder + implicit val encoder: ObjectEncoder[User] = deriveEncoder +} diff --git a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java index 02fa4fc2283..9a0c2fb6107 100644 --- a/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/java-inflector/src/gen/java/io/swagger/model/EnumTest.java @@ -19,7 +19,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml b/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml index 118ca53356a..cef4a8e8100 100644 --- a/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml +++ b/samples/server/petstore/java-inflector/src/main/swagger/swagger.yaml @@ -1100,6 +1100,7 @@ definitions: enum: - "UPPER" - "lower" + - "" enum_integer: type: "integer" format: "int32" diff --git a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/model/EnumTest.java index 446649217c8..dc00d569c7e 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/io/swagger/model/EnumTest.java @@ -18,7 +18,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/.swagger-codegen-ignore b/samples/server/petstore/jaxrs-cxf-annotated-base-path/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/jaxrs-cxf-annotated-base-path/pom.xml b/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml new file mode 100644 index 00000000000..cdf3a68ed8f --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml @@ -0,0 +1,177 @@ + + 4.0.0 + io.swagger + swagger-cxf-server + war + swagger-cxf-server + 1.0.0 + + src/main/java + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + maven-war-plugin + 2.1.1 + + false + + + + + + + io.swagger + swagger-jaxrs + compile + ${swagger-core-version} + + + ch.qos.logback + logback-classic + ${logback-version} + compile + + + ch.qos.logback + logback-core + ${logback-version} + compile + + + junit + junit + ${junit-version} + test + + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + test + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description-swagger + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-ws-policy + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-wsdl + ${cxf-version} + compile + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 1.7 + ${java.version} + ${java.version} + 1.5.10 + 9.2.9.v20150224 + 2.22.2 + 4.12 + 1.1.7 + 2.5 + 3.1.8 + UTF-8 + + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..524bc0085c1 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/PetApi.java @@ -0,0 +1,75 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/v2") +@Api(value = "/", description = "") +public interface PetApi { + + @POST + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Add a new pet to the store", tags={ "pet", }) + public void addPet(Pet body); + + @DELETE + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Deletes a pet", tags={ "pet", }) + public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + + @GET + @Path("/pet/findByStatus") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by status", tags={ "pet", }) + public List findPetsByStatus(@QueryParam("status")List status); + + @GET + @Path("/pet/findByTags") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by tags", tags={ "pet", }) + public List findPetsByTags(@QueryParam("tags")List tags); + + @GET + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find pet by ID", tags={ "pet", }) + public Pet getPetById(@PathParam("petId") Long petId); + + @PUT + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Update an existing pet", tags={ "pet", }) + public void updatePet(Pet body); + + @POST + @Path("/pet/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updates a pet in the store with form data", tags={ "pet", }) + public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + + @POST + @Path("/pet/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @ApiOperation(value = "uploads an image", tags={ "pet" }) + 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-annotated-base-path/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..747f772dad3 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/StoreApi.java @@ -0,0 +1,46 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/v2") +@Api(value = "/", description = "") +public interface StoreApi { + + @DELETE + @Path("/store/order/{orderId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete purchase order by ID", tags={ "store", }) + public void deleteOrder(@PathParam("orderId") String orderId); + + @GET + @Path("/store/inventory") + @Produces({ "application/json" }) + @ApiOperation(value = "Returns pet inventories by status", tags={ "store", }) + public Map getInventory(); + + @GET + @Path("/store/order/{orderId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find purchase order by ID", tags={ "store", }) + public Order getOrderById(@PathParam("orderId") Long orderId); + + @POST + @Path("/store/order") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Place an order for a pet", tags={ "store" }) + public Order placeOrder(Order body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..94d94a703fa --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/api/UserApi.java @@ -0,0 +1,70 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/v2") +@Api(value = "/", description = "") +public interface UserApi { + + @POST + @Path("/user") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Create user", tags={ "user", }) + public void createUser(User body); + + @POST + @Path("/user/createWithArray") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + public void createUsersWithArrayInput(List body); + + @POST + @Path("/user/createWithList") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + public void createUsersWithListInput(List body); + + @DELETE + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete user", tags={ "user", }) + public void deleteUser(@PathParam("username") String username); + + @GET + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Get user by user name", tags={ "user", }) + public User getUserByName(@PathParam("username") String username); + + @GET + @Path("/user/login") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs user into the system", tags={ "user", }) + public String loginUser(@QueryParam("username")String username, @QueryParam("password")String password); + + @GET + @Path("/user/logout") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs out current logged in user session", tags={ "user", }) + public void logoutUser(); + + @PUT + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updated user", tags={ "user" }) + public void updateUser(@PathParam("username") String username, User body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..591a6e22a69 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Category.java @@ -0,0 +1,65 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A category for a pet") +public class Category { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private String name = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..f3c6f56cfc4 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,78 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="Describes the result of uploading an image resource") +public class ModelApiResponse { + + @ApiModelProperty(example = "null", value = "") + private Integer code = null; + @ApiModelProperty(example = "null", value = "") + private String type = null; + @ApiModelProperty(example = "null", value = "") + private String message = null; + + /** + * Get code + * @return code + **/ + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + /** + * Get type + * @return type + **/ + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + /** + * Get message + * @return message + **/ + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..af6f5e0e38e --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Order.java @@ -0,0 +1,150 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="An order for a pets from the pet store") +public class Order { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private Long petId = null; + @ApiModelProperty(example = "null", value = "") + private Integer quantity = null; + @ApiModelProperty(example = "null", value = "") + private javax.xml.datatype.XMLGregorianCalendar shipDate = null; + +@XmlType(name="StatusEnum") +@XmlEnum(String.class) +public enum StatusEnum { + + @XmlEnumValue("placed") PLACED(String.valueOf("placed")), @XmlEnumValue("approved") APPROVED(String.valueOf("approved")), @XmlEnumValue("delivered") DELIVERED(String.valueOf("delivered")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "Order Status") + private StatusEnum status = null; + @ApiModelProperty(example = "null", value = "") + private Boolean complete = false; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get petId + * @return petId + **/ + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + /** + * Get quantity + * @return quantity + **/ + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + /** + * Get shipDate + * @return shipDate + **/ + public javax.xml.datatype.XMLGregorianCalendar getShipDate() { + return shipDate; + } + public void setShipDate(javax.xml.datatype.XMLGregorianCalendar shipDate) { + this.shipDate = shipDate; + } + /** + * Order Status + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + /** + * Get complete + * @return complete + **/ + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..0cfc0a30ee0 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Pet.java @@ -0,0 +1,154 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A pet for sale in the pet store") +public class Pet { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private Category category = null; + @ApiModelProperty(example = "doggie", required = true, value = "") + private String name = null; + @ApiModelProperty(example = "null", required = true, value = "") + private List photoUrls = new ArrayList(); + @ApiModelProperty(example = "null", value = "") + private List tags = new ArrayList(); + +@XmlType(name="StatusEnum") +@XmlEnum(String.class) +public enum StatusEnum { + + @XmlEnumValue("available") AVAILABLE(String.valueOf("available")), @XmlEnumValue("pending") PENDING(String.valueOf("pending")), @XmlEnumValue("sold") SOLD(String.valueOf("sold")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "pet status in the store") + private StatusEnum status = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get category + * @return category + **/ + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + /** + * Get photoUrls + * @return photoUrls + **/ + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + /** + * Get tags + * @return tags + **/ + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + /** + * pet status in the store + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..4eb99ad2fc1 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/Tag.java @@ -0,0 +1,65 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A tag for a pet") +public class Tag { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private String name = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/User.java new file mode 100644 index 00000000000..005d9aa8c74 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/io/swagger/model/User.java @@ -0,0 +1,143 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A User who is purchasing from the pet store") +public class User { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private String username = null; + @ApiModelProperty(example = "null", value = "") + private String firstName = null; + @ApiModelProperty(example = "null", value = "") + private String lastName = null; + @ApiModelProperty(example = "null", value = "") + private String email = null; + @ApiModelProperty(example = "null", value = "") + private String password = null; + @ApiModelProperty(example = "null", value = "") + private String phone = null; + @ApiModelProperty(example = "null", value = "User Status") + private Integer userStatus = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get username + * @return username + **/ + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + /** + * Get firstName + * @return firstName + **/ + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + /** + * Get lastName + * @return lastName + **/ + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + /** + * Get email + * @return email + **/ + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + /** + * Get password + * @return password + **/ + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + /** + * Get phone + * @return phone + **/ + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + /** + * User Status + * @return userStatus + **/ + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java new file mode 100644 index 00000000000..d9b9345d339 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -0,0 +1,71 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +public class PetApiServiceImpl implements PetApi { + public void addPet(Pet body) { + // TODO: Implement... + + + } + + public void deletePet(Long petId, String apiKey) { + // TODO: Implement... + + + } + + public List findPetsByStatus(List status) { + // TODO: Implement... + + return null; + } + + public List findPetsByTags(List tags) { + // TODO: Implement... + + return null; + } + + public Pet getPetById(Long petId) { + // TODO: Implement... + + return null; + } + + public void updatePet(Pet body) { + // TODO: Implement... + + + } + + public void updatePetWithForm(Long petId, String name, String status) { + // TODO: Implement... + + + } + + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, Attachment fileDetail) { + // TODO: Implement... + + return null; + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java new file mode 100644 index 00000000000..3f791097b6b --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -0,0 +1,46 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import java.util.Map; +import io.swagger.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +public class StoreApiServiceImpl implements StoreApi { + public void deleteOrder(String orderId) { + // TODO: Implement... + + + } + + public Map getInventory() { + // TODO: Implement... + + return null; + } + + public Order getOrderById(Long orderId) { + // TODO: Implement... + + return null; + } + + public Order placeOrder(Order body) { + // TODO: Implement... + + return null; + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java new file mode 100644 index 00000000000..861273cfb7b --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -0,0 +1,70 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import java.util.List; +import io.swagger.model.User; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +public class UserApiServiceImpl implements UserApi { + public void createUser(User body) { + // TODO: Implement... + + + } + + public void createUsersWithArrayInput(List body) { + // TODO: Implement... + + + } + + public void createUsersWithListInput(List body) { + // TODO: Implement... + + + } + + public void deleteUser(String username) { + // TODO: Implement... + + + } + + public User getUserByName(String username) { + // TODO: Implement... + + return null; + } + + public String loginUser(String username, String password) { + // TODO: Implement... + + return null; + } + + public void logoutUser() { + // TODO: Implement... + + + } + + public void updateUser(String username, User body) { + // TODO: Implement... + + + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/io/swagger/api/PetApiTest.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/io/swagger/api/PetApiTest.java new file mode 100644 index 00000000000..bbb67c24390 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/io/swagger/api/PetApiTest.java @@ -0,0 +1,221 @@ +/** + * Swagger Petstore + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * 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 + * + * http://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 io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for PetApi + */ +public class PetApiTest { + + + private PetApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", PetApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() { + Pet body = null; + //api.addPet(body); + + // TODO: test validations + + + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() { + Long petId = null; + String apiKey = null; + //api.deletePet(petId, apiKey); + + // TODO: test validations + + + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() { + List status = null; + //List response = api.findPetsByStatus(status); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() { + List tags = null; + //List response = api.findPetsByTags(tags); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() { + Long petId = null; + //Pet response = api.getPetById(petId); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() { + Pet body = null; + //api.updatePet(body); + + // TODO: test validations + + + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() { + Long petId = null; + String name = null; + String status = null; + //api.updatePetWithForm(petId, name, status); + + // TODO: test validations + + + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() { + Long petId = null; + String additionalMetadata = null; + org.apache.cxf.jaxrs.ext.multipart.Attachment file = null; + //ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + //assertNotNull(response); + // TODO: test validations + + + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/io/swagger/api/StoreApiTest.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/io/swagger/api/StoreApiTest.java new file mode 100644 index 00000000000..af89e255a9f --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/io/swagger/api/StoreApiTest.java @@ -0,0 +1,142 @@ +/** + * Swagger Petstore + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * 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 + * + * http://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 io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + + private StoreApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", StoreApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() { + String orderId = null; + //api.deleteOrder(orderId); + + // TODO: test validations + + + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() { + //Map response = api.getInventory(); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() { + Long orderId = null; + //Order response = api.getOrderById(orderId); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() { + Order body = null; + //Order response = api.placeOrder(body); + //assertNotNull(response); + // TODO: test validations + + + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/io/swagger/api/UserApiTest.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/io/swagger/api/UserApiTest.java new file mode 100644 index 00000000000..f789f0fc936 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/test/java/io/swagger/api/UserApiTest.java @@ -0,0 +1,216 @@ +/** + * Swagger Petstore + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * 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 + * + * http://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 io.swagger.api; + +import java.util.List; +import io.swagger.model.User; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for UserApi + */ +public class UserApiTest { + + + private UserApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", UserApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() { + User body = null; + //api.createUser(body); + + // TODO: test validations + + + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() { + List body = null; + //api.createUsersWithArrayInput(body); + + // TODO: test validations + + + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() { + List body = null; + //api.createUsersWithListInput(body); + + // TODO: test validations + + + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() { + String username = null; + //api.deleteUser(username); + + // TODO: test validations + + + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() { + String username = null; + //User response = api.getUserByName(username); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() { + String username = null; + String password = null; + //String response = api.loginUser(username, password); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() { + //api.logoutUser(); + + // TODO: test validations + + + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() { + String username = null; + User body = null; + //api.updateUser(username, body); + + // TODO: test validations + + + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-cdi/pom.xml b/samples/server/petstore/jaxrs-cxf-cdi/pom.xml index 4534f2961ac..0b12e6bd4a4 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/pom.xml +++ b/samples/server/petstore/jaxrs-cxf-cdi/pom.xml @@ -76,6 +76,14 @@ swagger-annotations [1.5.3,2) + + + + javax.validation + validation-api + 1.1.0.Final + provided + diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java index df620e58666..830049c297c 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApi.java @@ -13,18 +13,20 @@ import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import io.swagger.annotations.*; +import java.io.InputStream; import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; import java.util.List; - +import javax.validation.constraints.*; @Path("/pet") @RequestScoped @Api(description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + public class PetApi { @@ -78,7 +80,7 @@ public class PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter",required=true, allowableValues="available, pending, sold") @QueryParam("status") List status) { + public Response findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter",required=true, allowableValues="available, pending, sold") @QueryParam("status") List status) { return delegate.findPetsByStatus(status, securityContext); } @@ -95,7 +97,7 @@ public class PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByTags(@ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags) { + public Response findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by",required=true) @QueryParam("tags") List tags) { return delegate.findPetsByTags(tags, securityContext); } @@ -161,6 +163,6 @@ public class PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathParam("petId") Long petId, @Multipart(value = "additionalMetadata", required = false) String additionalMetadata, @Multipart(value = "file", required = false) InputStream fileInputStream, @Multipart(value = "file" , required = false) Attachment fileDetail) { - return delegate.uploadFile(petId, additionalMetadata, inputStream, fileDetail, securityContext); + return delegate.uploadFile(petId, additionalMetadata, fileInputStream, fileDetail, securityContext); } } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java index 924bf6ea7da..ac8e4a52ff7 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/PetApiService.java @@ -4,6 +4,7 @@ import io.swagger.api.*; import io.swagger.model.*; import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; import java.io.File; import io.swagger.model.ModelApiResponse; @@ -16,7 +17,7 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + public interface PetApiService { public Response addPet(Pet body, SecurityContext securityContext); public Response deletePet(Long petId, String apiKey, SecurityContext securityContext); diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java index 9531172123c..37aadc28199 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApi.java @@ -12,18 +12,20 @@ import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import io.swagger.annotations.*; +import java.io.InputStream; import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; import java.util.List; - +import javax.validation.constraints.*; @Path("/store") @RequestScoped @Api(description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + public class StoreApi { @@ -66,7 +68,7 @@ public class StoreApi { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId) { + public Response getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathParam("orderId") Long orderId) { return delegate.getOrderById(orderId, securityContext); } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java index 3ea40b6fbc1..45580cf4183 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/StoreApiService.java @@ -4,6 +4,7 @@ import io.swagger.api.*; import io.swagger.model.*; import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; import java.util.Map; import io.swagger.model.Order; @@ -15,7 +16,7 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + public interface StoreApiService { public Response deleteOrder(String orderId, SecurityContext securityContext); public Response getInventory(SecurityContext securityContext); diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java index cc052a69955..c733612ed1a 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApi.java @@ -12,18 +12,20 @@ import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import io.swagger.annotations.*; +import java.io.InputStream; import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; import java.util.List; - +import javax.validation.constraints.*; @Path("/user") @RequestScoped @Api(description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + public class UserApi { @@ -98,7 +100,7 @@ public class UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - public Response loginUser(@ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username, @ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password) { + public Response loginUser( @NotNull @ApiParam(value = "The user name for login",required=true) @QueryParam("username") String username, @NotNull @ApiParam(value = "The password for login in clear text",required=true) @QueryParam("password") String password) { return delegate.loginUser(username, password, securityContext); } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java index 14187d1302f..ed05f0abe27 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/api/UserApiService.java @@ -4,6 +4,7 @@ import io.swagger.api.*; import io.swagger.model.*; import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; import java.util.List; import io.swagger.model.User; @@ -15,7 +16,7 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + public interface UserApiService { public Response createUser(User body, SecurityContext securityContext); public Response createUsersWithArrayInput(List body, SecurityContext securityContext); diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java index 79ba2971c54..fee23f1bfaf 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Category.java @@ -3,7 +3,7 @@ package io.swagger.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; - +import javax.validation.constraints.*; /** * A category for a pet @@ -11,6 +11,9 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.*; import java.util.Objects; + +import javax.xml.bind.annotation.*; + @ApiModel(description = "A category for a pet") public class Category { diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java index a42de8ae1e1..39d83d433e5 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -3,7 +3,7 @@ package io.swagger.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; - +import javax.validation.constraints.*; /** * Describes the result of uploading an image resource @@ -11,6 +11,9 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.*; import java.util.Objects; + +import javax.xml.bind.annotation.*; + @ApiModel(description = "Describes the result of uploading an image resource") public class ModelApiResponse { diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java index d1fd9f10f03..21e1acca64d 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Order.java @@ -3,7 +3,7 @@ package io.swagger.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; - +import javax.validation.constraints.*; /** * An order for a pets from the pet store @@ -11,6 +11,9 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.*; import java.util.Objects; + +import javax.xml.bind.annotation.*; + @ApiModel(description = "An order for a pets from the pet store") public class Order { @@ -20,22 +23,38 @@ public class Order { private Integer quantity = null; private java.util.Date shipDate = null; -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlType; +@XmlType(name="StatusEnum") +@XmlEnum(String.class) +public enum StatusEnum { -@XmlType(name="Order") -@XmlEnum -public enum Order { - {values=[placed, approved, delivered], enumVars=[{name=PLACED, value="placed"}, {name=APPROVED, value="approved"}, {name=DELIVERED, value="delivered"}]}, - - public String value() { - return name(); + @XmlEnumValue("placed") PLACED(String.valueOf("placed")), @XmlEnumValue("approved") APPROVED(String.valueOf("approved")), @XmlEnumValue("delivered") DELIVERED(String.valueOf("delivered")); + + + private String value; + + StatusEnum (String v) { + value = v; } - public static Order fromValue(String v) { - return valueOf(v); + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; } } + private StatusEnum status = null; private Boolean complete = false; diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java index ebbe32b810f..c346608f0c8 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Pet.java @@ -7,7 +7,7 @@ import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * A pet for sale in the pet store @@ -15,6 +15,9 @@ import java.util.List; import io.swagger.annotations.*; import java.util.Objects; + +import javax.xml.bind.annotation.*; + @ApiModel(description = "A pet for sale in the pet store") public class Pet { @@ -25,22 +28,38 @@ public class Pet { private List photoUrls = new ArrayList(); private List tags = new ArrayList(); -import javax.xml.bind.annotation.XmlEnum; -import javax.xml.bind.annotation.XmlType; +@XmlType(name="StatusEnum") +@XmlEnum(String.class) +public enum StatusEnum { -@XmlType(name="Pet") -@XmlEnum -public enum Pet { - {values=[available, pending, sold], enumVars=[{name=AVAILABLE, value="available"}, {name=PENDING, value="pending"}, {name=SOLD, value="sold"}]}, - - public String value() { - return name(); + @XmlEnumValue("available") AVAILABLE(String.valueOf("available")), @XmlEnumValue("pending") PENDING(String.valueOf("pending")), @XmlEnumValue("sold") SOLD(String.valueOf("sold")); + + + private String value; + + StatusEnum (String v) { + value = v; } - public static Pet fromValue(String v) { - return valueOf(v); + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; } } + private StatusEnum status = null; /** @@ -87,6 +106,7 @@ public enum Pet { @ApiModelProperty(example = "doggie", required = true, value = "") @JsonProperty("name") + @NotNull public String getName() { return name; } @@ -104,6 +124,7 @@ public enum Pet { @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("photoUrls") + @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java index dc277dedce7..f60b51d5397 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/Tag.java @@ -3,7 +3,7 @@ package io.swagger.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; - +import javax.validation.constraints.*; /** * A tag for a pet @@ -11,6 +11,9 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.*; import java.util.Objects; + +import javax.xml.bind.annotation.*; + @ApiModel(description = "A tag for a pet") public class Tag { diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java index 0cc5cae6d6e..2548a22c89c 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/io/swagger/model/User.java @@ -3,7 +3,7 @@ package io.swagger.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; - +import javax.validation.constraints.*; /** * A User who is purchasing from the pet store @@ -11,6 +11,9 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.*; import java.util.Objects; + +import javax.xml.bind.annotation.*; + @ApiModel(description = "A User who is purchasing from the pet store") public class User { diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/RestApplication.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/RestApplication.java index 1ae54938776..3b43beeb9be 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/RestApplication.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/RestApplication.java @@ -1,9 +1,9 @@ -package io.swagger.api; - -import javax.ws.rs.ApplicationPath; -import javax.ws.rs.core.Application; - -@ApplicationPath("/") -public class RestApplication extends Application { - // Add implementation-specific details here +package io.swagger.api; + +import javax.ws.rs.ApplicationPath; +import javax.ws.rs.core.Application; + +@ApplicationPath("/") +public class RestApplication extends Application { + // Add implementation-specific details here } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 3a03e87fc7d..c56aee7e580 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -18,7 +18,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @RequestScoped -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + public class PetApiServiceImpl implements PetApiService { @Override public Response addPet(Pet body, SecurityContext securityContext) { diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index fed0fa6c0f0..50bd4b8501b 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -17,7 +17,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @RequestScoped -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + public class StoreApiServiceImpl implements StoreApiService { @Override public Response deleteOrder(String orderId, SecurityContext securityContext) { diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 4f4b3db2382..2870f45fb4c 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -17,7 +17,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @RequestScoped -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSCXFCDIServerCodegen", date = "2016-11-17T08:53:42.205Z") + public class UserApiServiceImpl implements UserApiService { @Override public Response createUser(User body, SecurityContext securityContext) { diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/webapp/WEB-INF/beans.xml b/samples/server/petstore/jaxrs-cxf-cdi/src/main/webapp/WEB-INF/beans.xml index cb6d500d43f..f9f7d3d948b 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/webapp/WEB-INF/beans.xml +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/webapp/WEB-INF/beans.xml @@ -1,13 +1,13 @@ - - - - - + + + + + \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-cdi/swagger.json b/samples/server/petstore/jaxrs-cxf-cdi/swagger.json index f48e38d5cb2..18ccb05b4ba 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/swagger.json +++ b/samples/server/petstore/jaxrs-cxf-cdi/swagger.json @@ -375,8 +375,8 @@ "description" : "ID of pet that needs to be fetched", "required" : true, "type" : "integer", - "maximum" : 5.0, - "minimum" : 1.0, + "maximum" : 5, + "minimum" : 1, "format" : "int64" } ], "responses" : { @@ -405,8 +405,7 @@ "in" : "path", "description" : "ID of the order that needs to be deleted", "required" : true, - "type" : "string", - "minimum" : 1.0 + "type" : "string" } ], "responses" : { "400" : { diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/.swagger-codegen-ignore b/samples/server/petstore/jaxrs-cxf-non-spring-app/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/jaxrs-cxf-non-spring-app/pom.xml b/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml new file mode 100644 index 00000000000..cdf3a68ed8f --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml @@ -0,0 +1,177 @@ + + 4.0.0 + io.swagger + swagger-cxf-server + war + swagger-cxf-server + 1.0.0 + + src/main/java + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + maven-war-plugin + 2.1.1 + + false + + + + + + + io.swagger + swagger-jaxrs + compile + ${swagger-core-version} + + + ch.qos.logback + logback-classic + ${logback-version} + compile + + + ch.qos.logback + logback-core + ${logback-version} + compile + + + junit + junit + ${junit-version} + test + + + + org.apache.cxf + cxf-rt-rs-client + ${cxf-version} + test + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-rs-service-description-swagger + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-ws-policy + ${cxf-version} + compile + + + org.apache.cxf + cxf-rt-wsdl + ${cxf-version} + compile + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 1.7 + ${java.version} + ${java.version} + 1.5.10 + 9.2.9.v20150224 + 2.22.2 + 4.12 + 1.1.7 + 2.5 + 3.1.8 + UTF-8 + + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..4ef2db0e204 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/PetApi.java @@ -0,0 +1,75 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +public interface PetApi { + + @POST + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Add a new pet to the store", tags={ "pet", }) + public void addPet(Pet body); + + @DELETE + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Deletes a pet", tags={ "pet", }) + public void deletePet(@PathParam("petId") Long petId, @HeaderParam("api_key") String apiKey); + + @GET + @Path("/pet/findByStatus") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by status", tags={ "pet", }) + public List findPetsByStatus(@QueryParam("status")List status); + + @GET + @Path("/pet/findByTags") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Finds Pets by tags", tags={ "pet", }) + public List findPetsByTags(@QueryParam("tags")List tags); + + @GET + @Path("/pet/{petId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find pet by ID", tags={ "pet", }) + public Pet getPetById(@PathParam("petId") Long petId); + + @PUT + @Path("/pet") + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Update an existing pet", tags={ "pet", }) + public void updatePet(Pet body); + + @POST + @Path("/pet/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updates a pet in the store with form data", tags={ "pet", }) + public void updatePetWithForm(@PathParam("petId") Long petId, @Multipart(value = "name", required = false) String name, @Multipart(value = "status", required = false) String status); + + @POST + @Path("/pet/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @ApiOperation(value = "uploads an image", tags={ "pet" }) + 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-non-spring-app/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..e26c47769b4 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/StoreApi.java @@ -0,0 +1,46 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +public interface StoreApi { + + @DELETE + @Path("/store/order/{orderId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete purchase order by ID", tags={ "store", }) + public void deleteOrder(@PathParam("orderId") String orderId); + + @GET + @Path("/store/inventory") + @Produces({ "application/json" }) + @ApiOperation(value = "Returns pet inventories by status", tags={ "store", }) + public Map getInventory(); + + @GET + @Path("/store/order/{orderId}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find purchase order by ID", tags={ "store", }) + public Order getOrderById(@PathParam("orderId") Long orderId); + + @POST + @Path("/store/order") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Place an order for a pet", tags={ "store" }) + public Order placeOrder(Order body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..a51b1fe0c70 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/api/UserApi.java @@ -0,0 +1,70 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; + +@Path("/") +@Api(value = "/", description = "") +public interface UserApi { + + @POST + @Path("/user") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Create user", tags={ "user", }) + public void createUser(User body); + + @POST + @Path("/user/createWithArray") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + public void createUsersWithArrayInput(List body); + + @POST + @Path("/user/createWithList") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Creates list of users with given input array", tags={ "user", }) + public void createUsersWithListInput(List body); + + @DELETE + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Delete user", tags={ "user", }) + public void deleteUser(@PathParam("username") String username); + + @GET + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Get user by user name", tags={ "user", }) + public User getUserByName(@PathParam("username") String username); + + @GET + @Path("/user/login") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs user into the system", tags={ "user", }) + public String loginUser(@QueryParam("username")String username, @QueryParam("password")String password); + + @GET + @Path("/user/logout") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Logs out current logged in user session", tags={ "user", }) + public void logoutUser(); + + @PUT + @Path("/user/{username}") + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Updated user", tags={ "user" }) + public void updateUser(@PathParam("username") String username, User body); +} + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..591a6e22a69 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Category.java @@ -0,0 +1,65 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A category for a pet") +public class Category { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private String name = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..f3c6f56cfc4 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,78 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="Describes the result of uploading an image resource") +public class ModelApiResponse { + + @ApiModelProperty(example = "null", value = "") + private Integer code = null; + @ApiModelProperty(example = "null", value = "") + private String type = null; + @ApiModelProperty(example = "null", value = "") + private String message = null; + + /** + * Get code + * @return code + **/ + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + /** + * Get type + * @return type + **/ + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + /** + * Get message + * @return message + **/ + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..af6f5e0e38e --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Order.java @@ -0,0 +1,150 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="An order for a pets from the pet store") +public class Order { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private Long petId = null; + @ApiModelProperty(example = "null", value = "") + private Integer quantity = null; + @ApiModelProperty(example = "null", value = "") + private javax.xml.datatype.XMLGregorianCalendar shipDate = null; + +@XmlType(name="StatusEnum") +@XmlEnum(String.class) +public enum StatusEnum { + + @XmlEnumValue("placed") PLACED(String.valueOf("placed")), @XmlEnumValue("approved") APPROVED(String.valueOf("approved")), @XmlEnumValue("delivered") DELIVERED(String.valueOf("delivered")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "Order Status") + private StatusEnum status = null; + @ApiModelProperty(example = "null", value = "") + private Boolean complete = false; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get petId + * @return petId + **/ + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + /** + * Get quantity + * @return quantity + **/ + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + /** + * Get shipDate + * @return shipDate + **/ + public javax.xml.datatype.XMLGregorianCalendar getShipDate() { + return shipDate; + } + public void setShipDate(javax.xml.datatype.XMLGregorianCalendar shipDate) { + this.shipDate = shipDate; + } + /** + * Order Status + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + /** + * Get complete + * @return complete + **/ + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..0cfc0a30ee0 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Pet.java @@ -0,0 +1,154 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A pet for sale in the pet store") +public class Pet { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private Category category = null; + @ApiModelProperty(example = "doggie", required = true, value = "") + private String name = null; + @ApiModelProperty(example = "null", required = true, value = "") + private List photoUrls = new ArrayList(); + @ApiModelProperty(example = "null", value = "") + private List tags = new ArrayList(); + +@XmlType(name="StatusEnum") +@XmlEnum(String.class) +public enum StatusEnum { + + @XmlEnumValue("available") AVAILABLE(String.valueOf("available")), @XmlEnumValue("pending") PENDING(String.valueOf("pending")), @XmlEnumValue("sold") SOLD(String.valueOf("sold")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "pet status in the store") + private StatusEnum status = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get category + * @return category + **/ + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + /** + * Get photoUrls + * @return photoUrls + **/ + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + /** + * Get tags + * @return tags + **/ + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + /** + * pet status in the store + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..4eb99ad2fc1 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/Tag.java @@ -0,0 +1,65 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A tag for a pet") +public class Tag { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private String name = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/User.java new file mode 100644 index 00000000000..005d9aa8c74 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/io/swagger/model/User.java @@ -0,0 +1,143 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="A User who is purchasing from the pet store") +public class User { + + @ApiModelProperty(example = "null", value = "") + private Long id = null; + @ApiModelProperty(example = "null", value = "") + private String username = null; + @ApiModelProperty(example = "null", value = "") + private String firstName = null; + @ApiModelProperty(example = "null", value = "") + private String lastName = null; + @ApiModelProperty(example = "null", value = "") + private String email = null; + @ApiModelProperty(example = "null", value = "") + private String password = null; + @ApiModelProperty(example = "null", value = "") + private String phone = null; + @ApiModelProperty(example = "null", value = "User Status") + private Integer userStatus = null; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + /** + * Get username + * @return username + **/ + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + /** + * Get firstName + * @return firstName + **/ + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + /** + * Get lastName + * @return lastName + **/ + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + /** + * Get email + * @return email + **/ + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + /** + * Get password + * @return password + **/ + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + /** + * Get phone + * @return phone + **/ + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + /** + * User Status + * @return userStatus + **/ + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java new file mode 100644 index 00000000000..d9b9345d339 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -0,0 +1,71 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +public class PetApiServiceImpl implements PetApi { + public void addPet(Pet body) { + // TODO: Implement... + + + } + + public void deletePet(Long petId, String apiKey) { + // TODO: Implement... + + + } + + public List findPetsByStatus(List status) { + // TODO: Implement... + + return null; + } + + public List findPetsByTags(List tags) { + // TODO: Implement... + + return null; + } + + public Pet getPetById(Long petId) { + // TODO: Implement... + + return null; + } + + public void updatePet(Pet body) { + // TODO: Implement... + + + } + + public void updatePetWithForm(Long petId, String name, String status) { + // TODO: Implement... + + + } + + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, Attachment fileDetail) { + // TODO: Implement... + + return null; + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java new file mode 100644 index 00000000000..3f791097b6b --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -0,0 +1,46 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import java.util.Map; +import io.swagger.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +public class StoreApiServiceImpl implements StoreApi { + public void deleteOrder(String orderId) { + // TODO: Implement... + + + } + + public Map getInventory() { + // TODO: Implement... + + return null; + } + + public Order getOrderById(Long orderId) { + // TODO: Implement... + + return null; + } + + public Order placeOrder(Order body) { + // TODO: Implement... + + return null; + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java new file mode 100644 index 00000000000..861273cfb7b --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -0,0 +1,70 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import java.util.List; +import io.swagger.model.User; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +public class UserApiServiceImpl implements UserApi { + public void createUser(User body) { + // TODO: Implement... + + + } + + public void createUsersWithArrayInput(List body) { + // TODO: Implement... + + + } + + public void createUsersWithListInput(List body) { + // TODO: Implement... + + + } + + public void deleteUser(String username) { + // TODO: Implement... + + + } + + public User getUserByName(String username) { + // TODO: Implement... + + return null; + } + + public String loginUser(String username, String password) { + // TODO: Implement... + + return null; + } + + public void logoutUser() { + // TODO: Implement... + + + } + + public void updateUser(String username, User body) { + // TODO: Implement... + + + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/webapp/WEB-INF/web.xml b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 00000000000..f10eaf1921b --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,24 @@ + + + + + CXF Non-Spring Jaxrs Servlet + CXFNonSpringJaxrsServlet + org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet + + jaxrs.serviceClasses + io.swagger.api.impl.PetApiServiceImpl,io.swagger.api.impl.StoreApiServiceImpl,io.swagger.api.impl.UserApiServiceImpl + + + jaxrs.providers + com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider + + + + + CXFNonSpringJaxrsServlet + /rest/* + + + diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/io/swagger/api/PetApiTest.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/io/swagger/api/PetApiTest.java new file mode 100644 index 00000000000..bbb67c24390 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/io/swagger/api/PetApiTest.java @@ -0,0 +1,221 @@ +/** + * Swagger Petstore + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * 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 + * + * http://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 io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for PetApi + */ +public class PetApiTest { + + + private PetApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", PetApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() { + Pet body = null; + //api.addPet(body); + + // TODO: test validations + + + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() { + Long petId = null; + String apiKey = null; + //api.deletePet(petId, apiKey); + + // TODO: test validations + + + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() { + List status = null; + //List response = api.findPetsByStatus(status); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() { + List tags = null; + //List response = api.findPetsByTags(tags); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() { + Long petId = null; + //Pet response = api.getPetById(petId); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() { + Pet body = null; + //api.updatePet(body); + + // TODO: test validations + + + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() { + Long petId = null; + String name = null; + String status = null; + //api.updatePetWithForm(petId, name, status); + + // TODO: test validations + + + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() { + Long petId = null; + String additionalMetadata = null; + org.apache.cxf.jaxrs.ext.multipart.Attachment file = null; + //ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + //assertNotNull(response); + // TODO: test validations + + + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/io/swagger/api/StoreApiTest.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/io/swagger/api/StoreApiTest.java new file mode 100644 index 00000000000..af89e255a9f --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/io/swagger/api/StoreApiTest.java @@ -0,0 +1,142 @@ +/** + * Swagger Petstore + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * 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 + * + * http://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 io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for StoreApi + */ +public class StoreApiTest { + + + private StoreApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", StoreApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() { + String orderId = null; + //api.deleteOrder(orderId); + + // TODO: test validations + + + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() { + //Map response = api.getInventory(); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() { + Long orderId = null; + //Order response = api.getOrderById(orderId); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() { + Order body = null; + //Order response = api.placeOrder(body); + //assertNotNull(response); + // TODO: test validations + + + } + +} diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/io/swagger/api/UserApiTest.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/io/swagger/api/UserApiTest.java new file mode 100644 index 00000000000..f789f0fc936 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/test/java/io/swagger/api/UserApiTest.java @@ -0,0 +1,216 @@ +/** + * Swagger Petstore + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * 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 + * + * http://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 io.swagger.api; + +import java.util.List; +import io.swagger.model.User; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for UserApi + */ +public class UserApiTest { + + + private UserApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", UserApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() { + User body = null; + //api.createUser(body); + + // TODO: test validations + + + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() { + List body = null; + //api.createUsersWithArrayInput(body); + + // TODO: test validations + + + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() { + List body = null; + //api.createUsersWithListInput(body); + + // TODO: test validations + + + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() { + String username = null; + //api.deleteUser(username); + + // TODO: test validations + + + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() { + String username = null; + //User response = api.getUserByName(username); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() { + String username = null; + String password = null; + //String response = api.loginUser(username, password); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() { + //api.logoutUser(); + + // TODO: test validations + + + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() { + String username = null; + User body = null; + //api.updateUser(username, body); + + // TODO: test validations + + + } + +} diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeApi.java new file mode 100644 index 00000000000..f75305e19f0 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/FakeApi.java @@ -0,0 +1,46 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import org.joda.time.LocalDate; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.jaxrs.PATCH; +import javax.validation.constraints.*; + +@Path("/") +@Api(value = "/", description = "") +public interface FakeApi { + + @PATCH + @Path("/fake") + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @ApiOperation(value = "To test \"client\" model", tags={ "fake", }) + public Client testClientModel(Client body); + + @POST + @Path("/fake") + @Consumes({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @Produces({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", tags={ "fake", }) + public void testEndpointParameters(@Multipart(value = "number") BigDecimal number, @Multipart(value = "_double") Double _double, @Multipart(value = "patternWithoutDelimiter") String patternWithoutDelimiter, @Multipart(value = "_byte") byte[] _byte, @Multipart(value = "integer", required = false) Integer integer, @Multipart(value = "int32", required = false) Integer int32, @Multipart(value = "int64", required = false) Long int64, @Multipart(value = "_float", required = false) Float _float, @Multipart(value = "string", required = false) String string, @Multipart(value = "binary", required = false) byte[] binary, @Multipart(value = "date", required = false) LocalDate date, @Multipart(value = "dateTime", required = false) javax.xml.datatype.XMLGregorianCalendar dateTime, @Multipart(value = "password", required = false) String password, @Multipart(value = "paramCallback", required = false) String paramCallback); + + @GET + @Path("/fake") + @Consumes({ "*/*" }) + @Produces({ "*/*" }) + @ApiOperation(value = "To test enum parameters", tags={ "fake" }) + public void testEnumParameters(@Multipart(value = "enumFormStringArray", required = false) List enumFormStringArray, @Multipart(value = "enumFormString", required = false) String enumFormString, @HeaderParam("enum_header_string_array") List enumHeaderStringArray, @HeaderParam("enum_header_string") String enumHeaderString, @QueryParam("enum_query_string_array") List enumQueryStringArray, @QueryParam("enum_query_string") String enumQueryString, @QueryParam("enum_query_integer") Integer enumQueryInteger, @Multipart(value = "enumQueryDouble", required = false) Double enumQueryDouble); +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java index 4ef2db0e204..d42bf02c74f 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/PetApi.java @@ -15,6 +15,8 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import io.swagger.jaxrs.PATCH; +import javax.validation.constraints.*; @Path("/") @Api(value = "/", description = "") @@ -37,13 +39,13 @@ public interface PetApi { @Path("/pet/findByStatus") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Finds Pets by status", tags={ "pet", }) - public List findPetsByStatus(@QueryParam("status")List status); + public List findPetsByStatus(@QueryParam("status") @NotNull List status); @GET @Path("/pet/findByTags") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Finds Pets by tags", tags={ "pet", }) - public List findPetsByTags(@QueryParam("tags")List tags); + public List findPetsByTags(@QueryParam("tags") @NotNull List tags); @GET @Path("/pet/{petId}") diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java index e26c47769b4..4a3ffd1020b 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/StoreApi.java @@ -14,6 +14,8 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import io.swagger.jaxrs.PATCH; +import javax.validation.constraints.*; @Path("/") @Api(value = "/", description = "") diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java index a51b1fe0c70..a28cc95b58d 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/api/UserApi.java @@ -14,6 +14,8 @@ import org.apache.cxf.jaxrs.ext.multipart.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; +import io.swagger.jaxrs.PATCH; +import javax.validation.constraints.*; @Path("/") @Api(value = "/", description = "") @@ -53,7 +55,7 @@ public interface UserApi { @Path("/user/login") @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Logs user into the system", tags={ "user", }) - public String loginUser(@QueryParam("username")String username, @QueryParam("password")String password); + public String loginUser(@QueryParam("username") @NotNull String username, @QueryParam("password") @NotNull String password); @GET @Path("/user/logout") diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..556e9e1d61a --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,91 @@ +package io.swagger.model; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class AdditionalPropertiesClass { + + @ApiModelProperty(example = "null", value = "") + private Map mapProperty = new HashMap(); + @ApiModelProperty(example = "null", value = "") + private Map> mapOfMapProperty = new HashMap>(); + + /** + * Get mapProperty + * @return mapProperty + **/ + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..08ed3535947 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Animal.java @@ -0,0 +1,81 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class Animal { + + @ApiModelProperty(example = "null", required = true, value = "") + private String className = null; + @ApiModelProperty(example = "null", value = "") + private String color = "red"; + + /** + * Get className + * @return className + **/ + @NotNull + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get color + * @return color + **/ + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..93ad619c46c --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import io.swagger.model.Animal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class AnimalFarm extends ArrayList { + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..681f477f8e8 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,66 @@ +package io.swagger.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class ArrayOfArrayOfNumberOnly { + + @ApiModelProperty(example = "null", value = "") + private List> arrayArrayNumber = new ArrayList>(); + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..8e06ba9fd53 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,66 @@ +package io.swagger.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class ArrayOfNumberOnly { + + @ApiModelProperty(example = "null", value = "") + private List arrayNumber = new ArrayList(); + + /** + * Get arrayNumber + * @return arrayNumber + **/ + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..bab67b5f1ac --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,116 @@ +package io.swagger.model; + +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class ArrayTest { + + @ApiModelProperty(example = "null", value = "") + private List arrayOfString = new ArrayList(); + @ApiModelProperty(example = "null", value = "") + private List> arrayArrayOfInteger = new ArrayList>(); + @ApiModelProperty(example = "null", value = "") + private List> arrayArrayOfModel = new ArrayList>(); + + /** + * Get arrayOfString + * @return arrayOfString + **/ + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Capitalization.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..9c96e900b7f --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Capitalization.java @@ -0,0 +1,158 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class Capitalization { + + @ApiModelProperty(example = "null", value = "") + private String smallCamel = null; + @ApiModelProperty(example = "null", value = "") + private String capitalCamel = null; + @ApiModelProperty(example = "null", value = "") + private String smallSnake = null; + @ApiModelProperty(example = "null", value = "") + private String capitalSnake = null; + @ApiModelProperty(example = "null", value = "") + private String scAETHFlowPoints = null; + @ApiModelProperty(example = "null", value = "Name of the pet ") + private String ATT_NAME = null; + + /** + * Get smallCamel + * @return smallCamel + **/ + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..12ff2e0743f --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Cat.java @@ -0,0 +1,59 @@ +package io.swagger.model; + +import io.swagger.model.Animal; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class Cat extends Animal { + + @ApiModelProperty(example = "null", value = "") + private Boolean declawed = null; + + /** + * Get declawed + * @return declawed + **/ + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java index 591a6e22a69..c4de6207ff9 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Category.java @@ -1,6 +1,6 @@ package io.swagger.model; -import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -11,7 +11,6 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@ApiModel(description="A category for a pet") public class Category { @ApiModelProperty(example = "null", value = "") @@ -26,9 +25,16 @@ public class Category { public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + + public Category id(Long id) { + this.id = id; + return this; + } + /** * Get name * @return name @@ -36,10 +42,17 @@ public class Category { public String getName() { return name; } + public void setName(String name) { this.name = name; } + public Category name(String name) { + this.name = name; + return this; + } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ClassModel.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..d924d868929 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ClassModel.java @@ -0,0 +1,60 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="Model for testing model with \"_class\" property") +public class ClassModel { + + @ApiModelProperty(example = "null", value = "") + private String propertyClass = null; + + /** + * Get propertyClass + * @return propertyClass + **/ + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..cde45a9e668 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Client.java @@ -0,0 +1,58 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class Client { + + @ApiModelProperty(example = "null", value = "") + private String client = null; + + /** + * Get client + * @return client + **/ + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + public Client client(String client) { + this.client = client; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..79f363fd80e --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Dog.java @@ -0,0 +1,59 @@ +package io.swagger.model; + +import io.swagger.model.Animal; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class Dog extends Animal { + + @ApiModelProperty(example = "null", value = "") + private String breed = null; + + /** + * Get breed + * @return breed + **/ + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..31adcdc2086 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,151 @@ +package io.swagger.model; + +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class EnumArrays { + + +@XmlType(name="JustSymbolEnum") +@XmlEnum(String.class) +public enum JustSymbolEnum { + +@XmlEnumValue(">=") GREATER_THAN_OR_EQUAL_TO(String.valueOf(">=")), @XmlEnumValue("$") DOLLAR(String.valueOf("$")); + + + private String value; + + JustSymbolEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static JustSymbolEnum fromValue(String v) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "") + private JustSymbolEnum justSymbol = null; + +@XmlType(name="ArrayEnumEnum") +@XmlEnum(String.class) +public enum ArrayEnumEnum { + +@XmlEnumValue("fish") FISH(String.valueOf("fish")), @XmlEnumValue("crab") CRAB(String.valueOf("crab")); + + + private String value; + + ArrayEnumEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static ArrayEnumEnum fromValue(String v) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "") + private List arrayEnum = new ArrayList(); + + /** + * Get justSymbol + * @return justSymbol + **/ + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..5f4f359b6d9 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumClass.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..b6e382ed1f6 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/EnumTest.java @@ -0,0 +1,218 @@ +package io.swagger.model; + +import io.swagger.model.OuterEnum; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class EnumTest { + + +@XmlType(name="EnumStringEnum") +@XmlEnum(String.class) +public enum EnumStringEnum { + +@XmlEnumValue("UPPER") UPPER(String.valueOf("UPPER")), @XmlEnumValue("lower") LOWER(String.valueOf("lower")), @XmlEnumValue("") EMPTY(String.valueOf("")); + + + private String value; + + EnumStringEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStringEnum fromValue(String v) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "") + private EnumStringEnum enumString = null; + +@XmlType(name="EnumIntegerEnum") +@XmlEnum(Integer.class) +public enum EnumIntegerEnum { + +@XmlEnumValue("1") NUMBER_1(Integer.valueOf(1)), @XmlEnumValue("-1") NUMBER_MINUS_1(Integer.valueOf(-1)); + + + private Integer value; + + EnumIntegerEnum (Integer v) { + value = v; + } + + public Integer value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumIntegerEnum fromValue(String v) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "") + private EnumIntegerEnum enumInteger = null; + +@XmlType(name="EnumNumberEnum") +@XmlEnum(Double.class) +public enum EnumNumberEnum { + +@XmlEnumValue("1.1") NUMBER_1_DOT_1(Double.valueOf(1.1)), @XmlEnumValue("-1.2") NUMBER_MINUS_1_DOT_2(Double.valueOf(-1.2)); + + + private Double value; + + EnumNumberEnum (Double v) { + value = v; + } + + public Double value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumNumberEnum fromValue(String v) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "") + private EnumNumberEnum enumNumber = null; + @ApiModelProperty(example = "null", value = "") + private OuterEnum outerEnum = null; + + /** + * Get enumString + * @return enumString + **/ + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/FormatTest.java new file mode 100644 index 00000000000..d544cfa112f --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/FormatTest.java @@ -0,0 +1,327 @@ +package io.swagger.model; + +import java.math.BigDecimal; +import java.util.UUID; +import org.joda.time.LocalDate; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class FormatTest { + + @ApiModelProperty(example = "null", value = "") + private Integer integer = null; + @ApiModelProperty(example = "null", value = "") + private Integer int32 = null; + @ApiModelProperty(example = "null", value = "") + private Long int64 = null; + @ApiModelProperty(example = "null", required = true, value = "") + private BigDecimal number = null; + @ApiModelProperty(example = "null", value = "") + private Float _float = null; + @ApiModelProperty(example = "null", value = "") + private Double _double = null; + @ApiModelProperty(example = "null", value = "") + private String string = null; + @ApiModelProperty(example = "null", required = true, value = "") + private byte[] _byte = null; + @ApiModelProperty(example = "null", value = "") + private byte[] binary = null; + @ApiModelProperty(example = "null", required = true, value = "") + private LocalDate date = null; + @ApiModelProperty(example = "null", value = "") + private javax.xml.datatype.XMLGregorianCalendar dateTime = null; + @ApiModelProperty(example = "null", value = "") + private UUID uuid = null; + @ApiModelProperty(example = "null", required = true, value = "") + private String password = null; + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + @Min(10) + @Max(100) + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + @Min(20) + @Max(200) + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @DecimalMin("54.3") + @DecimalMax("987.6") + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @DecimalMin("67.8") + @DecimalMax("123.4") + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get string + * @return string + **/ + @Pattern(regexp="/[a-z]/i") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @NotNull + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get binary + * @return binary + **/ + public byte[] getBinary() { + return binary; + } + + public void setBinary(byte[] binary) { + this.binary = binary; + } + + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get date + * @return date + **/ + @NotNull + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + public javax.xml.datatype.XMLGregorianCalendar getDateTime() { + return dateTime; + } + + public void setDateTime(javax.xml.datatype.XMLGregorianCalendar dateTime) { + this.dateTime = dateTime; + } + + public FormatTest dateTime(javax.xml.datatype.XMLGregorianCalendar dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public FormatTest uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get password + * @return password + **/ + @NotNull + @Size(min=10,max=64) + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..8acb48cf2cb --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,62 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class HasOnlyReadOnly { + + @ApiModelProperty(example = "null", value = "") + private String bar = null; + @ApiModelProperty(example = "null", value = "") + private String foo = null; + + /** + * Get bar + * @return bar + **/ + public String getBar() { + return bar; + } + + + /** + * Get foo + * @return foo + **/ + public String getFoo() { + return foo; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..3c1e80e9d83 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MapTest.java @@ -0,0 +1,124 @@ +package io.swagger.model; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class MapTest { + + @ApiModelProperty(example = "null", value = "") + private Map> mapMapOfString = new HashMap>(); + +@XmlType(name="InnerEnum") +@XmlEnum(String.class) +public enum InnerEnum { + +@XmlEnumValue("UPPER") UPPER(String.valueOf("UPPER")), @XmlEnumValue("lower") LOWER(String.valueOf("lower")); + + + private String value; + + InnerEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static InnerEnum fromValue(String v) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + @ApiModelProperty(example = "null", value = "") + private Map mapOfEnumString = new HashMap(); + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..2dcc59c4803 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,108 @@ +package io.swagger.model; + +import io.swagger.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class MixedPropertiesAndAdditionalPropertiesClass { + + @ApiModelProperty(example = "null", value = "") + private UUID uuid = null; + @ApiModelProperty(example = "null", value = "") + private javax.xml.datatype.XMLGregorianCalendar dateTime = null; + @ApiModelProperty(example = "null", value = "") + private Map map = new HashMap(); + + /** + * Get uuid + * @return uuid + **/ + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + public javax.xml.datatype.XMLGregorianCalendar getDateTime() { + return dateTime; + } + + public void setDateTime(javax.xml.datatype.XMLGregorianCalendar dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(javax.xml.datatype.XMLGregorianCalendar dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get map + * @return map + **/ + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..4a2183a1ca6 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Model200Response.java @@ -0,0 +1,80 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="Model for testing model name starting with number") +public class Model200Response { + + @ApiModelProperty(example = "null", value = "") + private Integer name = null; + @ApiModelProperty(example = "null", value = "") + private String propertyClass = null; + + /** + * Get name + * @return name + **/ + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java index f3c6f56cfc4..e25bfd0dbdf 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -1,6 +1,6 @@ package io.swagger.model; -import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -11,7 +11,6 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@ApiModel(description="Describes the result of uploading an image resource") public class ModelApiResponse { @ApiModelProperty(example = "null", value = "") @@ -28,9 +27,16 @@ public class ModelApiResponse { public Integer getCode() { return code; } + public void setCode(Integer code) { this.code = code; } + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + /** * Get type * @return type @@ -38,9 +44,16 @@ public class ModelApiResponse { public String getType() { return type; } + public void setType(String type) { this.type = type; } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + /** * Get message * @return message @@ -48,10 +61,17 @@ public class ModelApiResponse { public String getMessage() { return message; } + public void setMessage(String message) { this.message = message; } + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..cf9cb2cc74d --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,60 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="Model for testing reserved words") +public class ModelReturn { + + @ApiModelProperty(example = "null", value = "") + private Integer _return = null; + + /** + * Get _return + * @return _return + **/ + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..90deb77334d --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Name.java @@ -0,0 +1,105 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +@ApiModel(description="Model for testing model name same as property name") +public class Name { + + @ApiModelProperty(example = "null", required = true, value = "") + private Integer name = null; + @ApiModelProperty(example = "null", value = "") + private Integer snakeCase = null; + @ApiModelProperty(example = "null", value = "") + private String property = null; + @ApiModelProperty(example = "null", value = "") + private Integer _123Number = null; + + /** + * Get name + * @return name + **/ + @NotNull + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + public Integer getSnakeCase() { + return snakeCase; + } + + + /** + * Get property + * @return property + **/ + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get _123Number + * @return _123Number + **/ + public Integer get123Number() { + return _123Number; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..219cf8612ff --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,59 @@ +package io.swagger.model; + +import java.math.BigDecimal; +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class NumberOnly { + + @ApiModelProperty(example = "null", value = "") + private BigDecimal justNumber = null; + + /** + * Get justNumber + * @return justNumber + **/ + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java index af6f5e0e38e..4a7622e7948 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Order.java @@ -1,6 +1,6 @@ package io.swagger.model; -import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -11,7 +11,6 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@ApiModel(description="An order for a pets from the pet store") public class Order { @ApiModelProperty(example = "null", value = "") @@ -27,7 +26,7 @@ public class Order { @XmlEnum(String.class) public enum StatusEnum { - @XmlEnumValue("placed") PLACED(String.valueOf("placed")), @XmlEnumValue("approved") APPROVED(String.valueOf("approved")), @XmlEnumValue("delivered") DELIVERED(String.valueOf("delivered")); +@XmlEnumValue("placed") PLACED(String.valueOf("placed")), @XmlEnumValue("approved") APPROVED(String.valueOf("approved")), @XmlEnumValue("delivered") DELIVERED(String.valueOf("delivered")); private String value; @@ -67,9 +66,16 @@ public enum StatusEnum { public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + + public Order id(Long id) { + this.id = id; + return this; + } + /** * Get petId * @return petId @@ -77,9 +83,16 @@ public enum StatusEnum { public Long getPetId() { return petId; } + public void setPetId(Long petId) { this.petId = petId; } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + /** * Get quantity * @return quantity @@ -87,9 +100,16 @@ public enum StatusEnum { public Integer getQuantity() { return quantity; } + public void setQuantity(Integer quantity) { this.quantity = quantity; } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + /** * Get shipDate * @return shipDate @@ -97,9 +117,16 @@ public enum StatusEnum { public javax.xml.datatype.XMLGregorianCalendar getShipDate() { return shipDate; } + public void setShipDate(javax.xml.datatype.XMLGregorianCalendar shipDate) { this.shipDate = shipDate; } + + public Order shipDate(javax.xml.datatype.XMLGregorianCalendar shipDate) { + this.shipDate = shipDate; + return this; + } + /** * Order Status * @return status @@ -107,9 +134,16 @@ public enum StatusEnum { public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + /** * Get complete * @return complete @@ -117,10 +151,17 @@ public enum StatusEnum { public Boolean getComplete() { return complete; } + public void setComplete(Boolean complete) { this.complete = complete; } + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..1a2f5bbac54 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java index 0cfc0a30ee0..3046295eeaf 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Pet.java @@ -1,10 +1,10 @@ package io.swagger.model; -import io.swagger.annotations.ApiModel; import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -15,7 +15,6 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@ApiModel(description="A pet for sale in the pet store") public class Pet { @ApiModelProperty(example = "null", value = "") @@ -33,7 +32,7 @@ public class Pet { @XmlEnum(String.class) public enum StatusEnum { - @XmlEnumValue("available") AVAILABLE(String.valueOf("available")), @XmlEnumValue("pending") PENDING(String.valueOf("pending")), @XmlEnumValue("sold") SOLD(String.valueOf("sold")); +@XmlEnumValue("available") AVAILABLE(String.valueOf("available")), @XmlEnumValue("pending") PENDING(String.valueOf("pending")), @XmlEnumValue("sold") SOLD(String.valueOf("sold")); private String value; @@ -71,9 +70,16 @@ public enum StatusEnum { public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + + public Pet id(Long id) { + this.id = id; + return this; + } + /** * Get category * @return category @@ -81,29 +87,57 @@ public enum StatusEnum { public Category getCategory() { return category; } + public void setCategory(Category category) { this.category = category; } + + public Pet category(Category category) { + this.category = category; + return this; + } + /** * Get name * @return name **/ + @NotNull public String getName() { return name; } + public void setName(String name) { this.name = name; } + + public Pet name(String name) { + this.name = name; + return this; + } + /** * Get photoUrls * @return photoUrls **/ + @NotNull public List getPhotoUrls() { return photoUrls; } + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + /** * Get tags * @return tags @@ -111,9 +145,21 @@ public enum StatusEnum { public List getTags() { return tags; } + public void setTags(List tags) { this.tags = tags; } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + /** * pet status in the store * @return status @@ -121,10 +167,17 @@ public enum StatusEnum { public StatusEnum getStatus() { return status; } + public void setStatus(StatusEnum status) { this.status = status; } + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..f870573ac4d --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,70 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class ReadOnlyFirst { + + @ApiModelProperty(example = "null", value = "") + private String bar = null; + @ApiModelProperty(example = "null", value = "") + private String baz = null; + + /** + * Get bar + * @return bar + **/ + public String getBar() { + return bar; + } + + + /** + * Get baz + * @return baz + **/ + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..b3decaa2221 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,58 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + +import io.swagger.annotations.ApiModelProperty; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlType; +import javax.xml.bind.annotation.XmlEnum; +import javax.xml.bind.annotation.XmlEnumValue; + +public class SpecialModelName { + + @ApiModelProperty(example = "null", value = "") + private Long specialPropertyName = null; + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + public Long getSpecialPropertyName() { + return specialPropertyName; + } + + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java index 4eb99ad2fc1..9a2ffa38409 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/Tag.java @@ -1,6 +1,6 @@ package io.swagger.model; -import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -11,7 +11,6 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@ApiModel(description="A tag for a pet") public class Tag { @ApiModelProperty(example = "null", value = "") @@ -26,9 +25,16 @@ public class Tag { public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + + public Tag id(Long id) { + this.id = id; + return this; + } + /** * Get name * @return name @@ -36,10 +42,17 @@ public class Tag { public String getName() { return name; } + public void setName(String name) { this.name = name; } + public Tag name(String name) { + this.name = name; + return this; + } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java index 005d9aa8c74..e25dba5282e 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/io/swagger/model/User.java @@ -1,6 +1,6 @@ package io.swagger.model; -import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; import io.swagger.annotations.ApiModelProperty; import javax.xml.bind.annotation.XmlElement; @@ -11,7 +11,6 @@ import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; -@ApiModel(description="A User who is purchasing from the pet store") public class User { @ApiModelProperty(example = "null", value = "") @@ -38,9 +37,16 @@ public class User { public Long getId() { return id; } + public void setId(Long id) { this.id = id; } + + public User id(Long id) { + this.id = id; + return this; + } + /** * Get username * @return username @@ -48,9 +54,16 @@ public class User { public String getUsername() { return username; } + public void setUsername(String username) { this.username = username; } + + public User username(String username) { + this.username = username; + return this; + } + /** * Get firstName * @return firstName @@ -58,9 +71,16 @@ public class User { public String getFirstName() { return firstName; } + public void setFirstName(String firstName) { this.firstName = firstName; } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + /** * Get lastName * @return lastName @@ -68,9 +88,16 @@ public class User { public String getLastName() { return lastName; } + public void setLastName(String lastName) { this.lastName = lastName; } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + /** * Get email * @return email @@ -78,9 +105,16 @@ public class User { public String getEmail() { return email; } + public void setEmail(String email) { this.email = email; } + + public User email(String email) { + this.email = email; + return this; + } + /** * Get password * @return password @@ -88,9 +122,16 @@ public class User { public String getPassword() { return password; } + public void setPassword(String password) { this.password = password; } + + public User password(String password) { + this.password = password; + return this; + } + /** * Get phone * @return phone @@ -98,9 +139,16 @@ public class User { public String getPhone() { return phone; } + public void setPhone(String phone) { this.phone = phone; } + + public User phone(String phone) { + this.phone = phone; + return this; + } + /** * User Status * @return userStatus @@ -108,10 +156,17 @@ public class User { public Integer getUserStatus() { return userStatus; } + public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java new file mode 100644 index 00000000000..7c01649234e --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -0,0 +1,41 @@ +package io.swagger.api.impl; + +import io.swagger.api.*; +import java.math.BigDecimal; +import io.swagger.model.Client; +import org.joda.time.LocalDate; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import javax.ws.rs.*; +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.model.wadl.Description; +import org.apache.cxf.jaxrs.model.wadl.DocTarget; + +import org.apache.cxf.jaxrs.ext.multipart.*; + +import io.swagger.annotations.Api; + +public class FakeApiServiceImpl implements FakeApi { + public Client testClientModel(Client body) { + // TODO: Implement... + + return null; + } + + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, byte[] binary, LocalDate date, javax.xml.datatype.XMLGregorianCalendar dateTime, String password, String paramCallback) { + // TODO: Implement... + + + } + + public void testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble) { + // TODO: Implement... + + + } + +} + diff --git a/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/FakeApiTest.java b/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/FakeApiTest.java new file mode 100644 index 00000000000..5e8dae654a4 --- /dev/null +++ b/samples/server/petstore/jaxrs-cxf/src/test/java/io/swagger/api/FakeApiTest.java @@ -0,0 +1,146 @@ +/** + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * 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 + * + * http://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 io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import org.joda.time.LocalDate; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import javax.ws.rs.core.Response; +import org.apache.cxf.jaxrs.client.JAXRSClientFactory; +import org.apache.cxf.jaxrs.client.ClientConfiguration; +import org.apache.cxf.jaxrs.client.WebClient; + + +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + + + +/** + * API tests for FakeApi + */ +public class FakeApiTest { + + + private FakeApi api; + + @Before + public void setup() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + List providers = new ArrayList(); + providers.add(provider); + + api = JAXRSClientFactory.create("http://petstore.swagger.io/v2", FakeApi.class, providers); + org.apache.cxf.jaxrs.client.Client client = WebClient.client(api); + + ClientConfiguration config = WebClient.getConfig(client); + } + + + /** + * To test \"client\" model + * + * To test \"client\" model + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testClientModelTest() { + Client body = null; + //Client response = api.testClientModel(body); + //assertNotNull(response); + // TODO: test validations + + + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() { + BigDecimal number = null; + Double _double = null; + String patternWithoutDelimiter = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + String string = null; + byte[] binary = null; + LocalDate date = null; + javax.xml.datatype.XMLGregorianCalendar dateTime = null; + String password = null; + String paramCallback = null; + //api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + + // TODO: test validations + + + } + + /** + * To test enum parameters + * + * To test enum parameters + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEnumParametersTest() { + List enumFormStringArray = null; + String enumFormString = null; + List enumHeaderStringArray = null; + String enumHeaderString = null; + List enumQueryStringArray = null; + String enumQueryString = null; + Integer enumQueryInteger = null; + Double enumQueryDouble = null; + //api.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + + // TODO: test validations + + + } + +} diff --git a/samples/server/petstore/jaxrs-resteasy/default/pom.xml b/samples/server/petstore/jaxrs-resteasy/default/pom.xml index 62e05d6da56..93f4ec76ecb 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/default/pom.xml @@ -143,6 +143,14 @@ + + + javax.validation + validation-api + 1.1.0.Final + provided + + diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java index f8ea20235fb..7586f8cfed8 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/PetApi.java @@ -4,6 +4,9 @@ import io.swagger.model.*; import io.swagger.api.PetApiService; import io.swagger.api.factories.PetApiServiceFactory; +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + import java.io.File; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; @@ -17,6 +20,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; @Path("/pet") @@ -32,14 +36,14 @@ public class PetApi { @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) - public Response addPet( Pet body,@Context SecurityContext securityContext) + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.addPet(body,securityContext); } @@ -48,14 +52,14 @@ public class PetApi { @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) - public Response deletePet( @PathParam("petId") Long petId,@HeaderParam("api_key") String apiKey,@Context SecurityContext securityContext) + public Response deletePet( @PathParam("petId") Long petId,@ApiParam(value = "" )@HeaderParam("api_key") String apiKey,@Context SecurityContext securityContext) throws NotFoundException { return delegate.deletePet(petId,apiKey,securityContext); } @@ -64,16 +68,16 @@ public class PetApi { @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByStatus( @QueryParam("status") List status,@Context SecurityContext securityContext) + public Response findPetsByStatus( @NotNull @QueryParam("status") List status,@Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByStatus(status,securityContext); } @@ -82,16 +86,16 @@ public class PetApi { @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByTags( @QueryParam("tags") List tags,@Context SecurityContext securityContext) + public Response findPetsByTags( @NotNull @QueryParam("tags") List tags,@Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByTags(tags,securityContext); } @@ -100,7 +104,7 @@ public class PetApi { @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { - @io.swagger.annotations.Authorization(value = "api_key") + @io.swagger.annotations.Authorization(value = "api_key") }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), @@ -117,9 +121,9 @@ public class PetApi { @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @@ -128,7 +132,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Void.class), @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) - public Response updatePet( Pet body,@Context SecurityContext securityContext) + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.updatePet(body,securityContext); } @@ -137,14 +141,14 @@ public class PetApi { @Consumes({ "application/x-www-form-urlencoded" }) @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) - public Response updatePetWithForm( @PathParam("petId") Long petId,@FormParam("name") String name,@FormParam("status") String status,@Context SecurityContext securityContext) + public Response updatePetWithForm( @PathParam("petId") Long petId,@ApiParam(value = "Updated name of the pet")@FormParam("name") String name,@ApiParam(value = "Updated status of the pet")@FormParam("status") String status,@Context SecurityContext securityContext) throws NotFoundException { return delegate.updatePetWithForm(petId,name,status,securityContext); } @@ -153,9 +157,9 @@ public class PetApi { @Consumes({ "multipart/form-data" }) @Produces({ "application/json" }) @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java index 8092d4d3dea..f8ef1c59ade 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/StoreApi.java @@ -4,6 +4,9 @@ import io.swagger.model.*; import io.swagger.api.StoreApiService; import io.swagger.api.factories.StoreApiServiceFactory; +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + import java.util.Map; import io.swagger.model.Order; @@ -16,6 +19,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/store") @@ -43,7 +47,7 @@ public class StoreApi { @Produces({ "application/json" }) @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { - @io.swagger.annotations.Authorization(value = "api_key") + @io.swagger.annotations.Authorization(value = "api_key") }, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) @@ -62,7 +66,7 @@ public class StoreApi { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById( @PathParam("orderId") Long orderId,@Context SecurityContext securityContext) + public Response getOrderById( @Min(1) @Max(5) @PathParam("orderId") Long orderId,@Context SecurityContext securityContext) throws NotFoundException { return delegate.getOrderById(orderId,securityContext); } @@ -75,7 +79,7 @@ public class StoreApi { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - public Response placeOrder( Order body,@Context SecurityContext securityContext) + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.placeOrder(body,securityContext); } diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java index 39035746968..5790caaa4b2 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/api/UserApi.java @@ -4,6 +4,9 @@ import io.swagger.model.*; import io.swagger.api.UserApiService; import io.swagger.api.factories.UserApiServiceFactory; +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + import java.util.List; import io.swagger.model.User; @@ -16,6 +19,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/user") @@ -32,7 +36,7 @@ public class UserApi { @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUser( User body,@Context SecurityContext securityContext) + public Response createUser(@ApiParam(value = "Created user object" ,required=true) User body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUser(body,securityContext); } @@ -43,7 +47,7 @@ public class UserApi { @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput( List body,@Context SecurityContext securityContext) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithArrayInput(body,securityContext); } @@ -54,7 +58,7 @@ public class UserApi { @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput( List body,@Context SecurityContext securityContext) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithListInput(body,securityContext); } @@ -95,7 +99,7 @@ public class UserApi { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - public Response loginUser( @QueryParam("username") String username, @QueryParam("password") String password,@Context SecurityContext securityContext) + public Response loginUser( @NotNull @QueryParam("username") String username, @NotNull @QueryParam("password") String password,@Context SecurityContext securityContext) throws NotFoundException { return delegate.loginUser(username,password,securityContext); } @@ -119,7 +123,7 @@ public class UserApi { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) }) - public Response updateUser( @PathParam("username") String username, User body,@Context SecurityContext securityContext) + public Response updateUser( @PathParam("username") String username,@ApiParam(value = "Updated user object" ,required=true) User body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.updateUser(username,body,securityContext); } diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java index a551df116fc..caf0d5f1631 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Category.java @@ -5,7 +5,10 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="A category for a pet") public class Category { @@ -15,6 +18,7 @@ public class Category { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("id") public Long getId() { return id; @@ -26,6 +30,7 @@ public class Category { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("name") public String getName() { return name; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java index c8898f86971..ac14219acb6 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -5,7 +5,10 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="Describes the result of uploading an image resource") public class ModelApiResponse { @@ -16,6 +19,7 @@ public class ModelApiResponse { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("code") public Integer getCode() { return code; @@ -27,6 +31,7 @@ public class ModelApiResponse { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("type") public String getType() { return type; @@ -38,6 +43,7 @@ public class ModelApiResponse { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("message") public String getMessage() { return message; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java index 586d4b195b3..b1870b87340 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Order.java @@ -7,7 +7,10 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import java.util.Date; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="An order for a pets from the pet store") public class Order { @@ -44,6 +47,7 @@ public class Order { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("id") public Long getId() { return id; @@ -55,6 +59,7 @@ public class Order { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("petId") public Long getPetId() { return petId; @@ -66,6 +71,7 @@ public class Order { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("quantity") public Integer getQuantity() { return quantity; @@ -77,6 +83,7 @@ public class Order { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("shipDate") public Date getShipDate() { return shipDate; @@ -89,6 +96,7 @@ public class Order { * Order Status **/ + @ApiModelProperty(example = "null", value = "Order Status") @JsonProperty("status") public StatusEnum getStatus() { return status; @@ -100,6 +108,7 @@ public class Order { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("complete") public Boolean getComplete() { return complete; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java index 685d7ab6ee6..5dbbc692373 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Pet.java @@ -9,7 +9,10 @@ import io.swagger.annotations.ApiModel; import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.List; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="A pet for sale in the pet store") public class Pet { @@ -46,6 +49,7 @@ public class Pet { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("id") public Long getId() { return id; @@ -57,6 +61,7 @@ public class Pet { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("category") public Category getCategory() { return category; @@ -68,7 +73,9 @@ public class Pet { /** **/ + @ApiModelProperty(example = "doggie", required = true, value = "") @JsonProperty("name") + @NotNull public String getName() { return name; } @@ -79,7 +86,9 @@ public class Pet { /** **/ + @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("photoUrls") + @NotNull public List getPhotoUrls() { return photoUrls; } @@ -90,6 +99,7 @@ public class Pet { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("tags") public List getTags() { return tags; @@ -102,6 +112,7 @@ public class Pet { * pet status in the store **/ + @ApiModelProperty(example = "null", value = "pet status in the store") @JsonProperty("status") public StatusEnum getStatus() { return status; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java index 48a6ab94a85..43ea83e43fc 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/Tag.java @@ -5,7 +5,10 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="A tag for a pet") public class Tag { @@ -15,6 +18,7 @@ public class Tag { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("id") public Long getId() { return id; @@ -26,6 +30,7 @@ public class Tag { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("name") public String getName() { return name; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java index e95e76c1b41..f238a851d7c 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/io/swagger/model/User.java @@ -5,7 +5,10 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="A User who is purchasing from the pet store") public class User { @@ -21,6 +24,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("id") public Long getId() { return id; @@ -32,6 +36,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("username") public String getUsername() { return username; @@ -43,6 +48,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("firstName") public String getFirstName() { return firstName; @@ -54,6 +60,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("lastName") public String getLastName() { return lastName; @@ -65,6 +72,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("email") public String getEmail() { return email; @@ -76,6 +84,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("password") public String getPassword() { return password; @@ -87,6 +96,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("phone") public String getPhone() { return phone; @@ -99,6 +109,7 @@ public class User { * User Status **/ + @ApiModelProperty(example = "null", value = "User Status") @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApi.java index f8ea20235fb..7586f8cfed8 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/PetApi.java @@ -4,6 +4,9 @@ import io.swagger.model.*; import io.swagger.api.PetApiService; import io.swagger.api.factories.PetApiServiceFactory; +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + import java.io.File; import io.swagger.model.ModelApiResponse; import io.swagger.model.Pet; @@ -17,6 +20,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput; @Path("/pet") @@ -32,14 +36,14 @@ public class PetApi { @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) - public Response addPet( Pet body,@Context SecurityContext securityContext) + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.addPet(body,securityContext); } @@ -48,14 +52,14 @@ public class PetApi { @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) - public Response deletePet( @PathParam("petId") Long petId,@HeaderParam("api_key") String apiKey,@Context SecurityContext securityContext) + public Response deletePet( @PathParam("petId") Long petId,@ApiParam(value = "" )@HeaderParam("api_key") String apiKey,@Context SecurityContext securityContext) throws NotFoundException { return delegate.deletePet(petId,apiKey,securityContext); } @@ -64,16 +68,16 @@ public class PetApi { @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByStatus( @QueryParam("status") List status,@Context SecurityContext securityContext) + public Response findPetsByStatus( @NotNull @QueryParam("status") List status,@Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByStatus(status,securityContext); } @@ -82,16 +86,16 @@ public class PetApi { @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByTags( @QueryParam("tags") List tags,@Context SecurityContext securityContext) + public Response findPetsByTags( @NotNull @QueryParam("tags") List tags,@Context SecurityContext securityContext) throws NotFoundException { return delegate.findPetsByTags(tags,securityContext); } @@ -100,7 +104,7 @@ public class PetApi { @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { - @io.swagger.annotations.Authorization(value = "api_key") + @io.swagger.annotations.Authorization(value = "api_key") }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), @@ -117,9 +121,9 @@ public class PetApi { @Consumes({ "application/json", "application/xml" }) @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @@ -128,7 +132,7 @@ public class PetApi { @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Void.class), @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) - public Response updatePet( Pet body,@Context SecurityContext securityContext) + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true) Pet body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.updatePet(body,securityContext); } @@ -137,14 +141,14 @@ public class PetApi { @Consumes({ "application/x-www-form-urlencoded" }) @Produces({ "application/xml", "application/json" }) @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) - public Response updatePetWithForm( @PathParam("petId") Long petId,@FormParam("name") String name,@FormParam("status") String status,@Context SecurityContext securityContext) + public Response updatePetWithForm( @PathParam("petId") Long petId,@ApiParam(value = "Updated name of the pet")@FormParam("name") String name,@ApiParam(value = "Updated status of the pet")@FormParam("status") String status,@Context SecurityContext securityContext) throws NotFoundException { return delegate.updatePetWithForm(petId,name,status,securityContext); } @@ -153,9 +157,9 @@ public class PetApi { @Consumes({ "multipart/form-data" }) @Produces({ "application/json" }) @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { - @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @io.swagger.annotations.ApiResponses(value = { diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApi.java index 8092d4d3dea..f8ef1c59ade 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/StoreApi.java @@ -4,6 +4,9 @@ import io.swagger.model.*; import io.swagger.api.StoreApiService; import io.swagger.api.factories.StoreApiServiceFactory; +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + import java.util.Map; import io.swagger.model.Order; @@ -16,6 +19,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/store") @@ -43,7 +47,7 @@ public class StoreApi { @Produces({ "application/json" }) @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { - @io.swagger.annotations.Authorization(value = "api_key") + @io.swagger.annotations.Authorization(value = "api_key") }, tags={ "store", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) @@ -62,7 +66,7 @@ public class StoreApi { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById( @PathParam("orderId") Long orderId,@Context SecurityContext securityContext) + public Response getOrderById( @Min(1) @Max(5) @PathParam("orderId") Long orderId,@Context SecurityContext securityContext) throws NotFoundException { return delegate.getOrderById(orderId,securityContext); } @@ -75,7 +79,7 @@ public class StoreApi { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) - public Response placeOrder( Order body,@Context SecurityContext securityContext) + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true) Order body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.placeOrder(body,securityContext); } diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApi.java index 39035746968..5790caaa4b2 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/api/UserApi.java @@ -4,6 +4,9 @@ import io.swagger.model.*; import io.swagger.api.UserApiService; import io.swagger.api.factories.UserApiServiceFactory; +import io.swagger.annotations.ApiParam; +import io.swagger.jaxrs.*; + import java.util.List; import io.swagger.model.User; @@ -16,6 +19,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/user") @@ -32,7 +36,7 @@ public class UserApi { @io.swagger.annotations.ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUser( User body,@Context SecurityContext securityContext) + public Response createUser(@ApiParam(value = "Created user object" ,required=true) User body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUser(body,securityContext); } @@ -43,7 +47,7 @@ public class UserApi { @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput( List body,@Context SecurityContext securityContext) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithArrayInput(body,securityContext); } @@ -54,7 +58,7 @@ public class UserApi { @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput( List body,@Context SecurityContext securityContext) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithListInput(body,securityContext); } @@ -95,7 +99,7 @@ public class UserApi { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = String.class), @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - public Response loginUser( @QueryParam("username") String username, @QueryParam("password") String password,@Context SecurityContext securityContext) + public Response loginUser( @NotNull @QueryParam("username") String username, @NotNull @QueryParam("password") String password,@Context SecurityContext securityContext) throws NotFoundException { return delegate.loginUser(username,password,securityContext); } @@ -119,7 +123,7 @@ public class UserApi { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) }) - public Response updateUser( @PathParam("username") String username, User body,@Context SecurityContext securityContext) + public Response updateUser( @PathParam("username") String username,@ApiParam(value = "Updated user object" ,required=true) User body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.updateUser(username,body,securityContext); } diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Category.java index a551df116fc..caf0d5f1631 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Category.java @@ -5,7 +5,10 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="A category for a pet") public class Category { @@ -15,6 +18,7 @@ public class Category { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("id") public Long getId() { return id; @@ -26,6 +30,7 @@ public class Category { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("name") public String getName() { return name; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/ModelApiResponse.java index c8898f86971..ac14219acb6 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -5,7 +5,10 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="Describes the result of uploading an image resource") public class ModelApiResponse { @@ -16,6 +19,7 @@ public class ModelApiResponse { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("code") public Integer getCode() { return code; @@ -27,6 +31,7 @@ public class ModelApiResponse { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("type") public String getType() { return type; @@ -38,6 +43,7 @@ public class ModelApiResponse { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("message") public String getMessage() { return message; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Order.java index 2695cc3d6d8..0099184b5ae 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Order.java @@ -7,7 +7,10 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import org.joda.time.DateTime; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="An order for a pets from the pet store") public class Order { @@ -44,6 +47,7 @@ public class Order { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("id") public Long getId() { return id; @@ -55,6 +59,7 @@ public class Order { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("petId") public Long getPetId() { return petId; @@ -66,6 +71,7 @@ public class Order { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("quantity") public Integer getQuantity() { return quantity; @@ -77,6 +83,7 @@ public class Order { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("shipDate") public DateTime getShipDate() { return shipDate; @@ -89,6 +96,7 @@ public class Order { * Order Status **/ + @ApiModelProperty(example = "null", value = "Order Status") @JsonProperty("status") public StatusEnum getStatus() { return status; @@ -100,6 +108,7 @@ public class Order { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("complete") public Boolean getComplete() { return complete; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Pet.java index 685d7ab6ee6..5dbbc692373 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Pet.java @@ -9,7 +9,10 @@ import io.swagger.annotations.ApiModel; import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.List; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="A pet for sale in the pet store") public class Pet { @@ -46,6 +49,7 @@ public class Pet { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("id") public Long getId() { return id; @@ -57,6 +61,7 @@ public class Pet { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("category") public Category getCategory() { return category; @@ -68,7 +73,9 @@ public class Pet { /** **/ + @ApiModelProperty(example = "doggie", required = true, value = "") @JsonProperty("name") + @NotNull public String getName() { return name; } @@ -79,7 +86,9 @@ public class Pet { /** **/ + @ApiModelProperty(example = "null", required = true, value = "") @JsonProperty("photoUrls") + @NotNull public List getPhotoUrls() { return photoUrls; } @@ -90,6 +99,7 @@ public class Pet { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("tags") public List getTags() { return tags; @@ -102,6 +112,7 @@ public class Pet { * pet status in the store **/ + @ApiModelProperty(example = "null", value = "pet status in the store") @JsonProperty("status") public StatusEnum getStatus() { return status; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Tag.java index 48a6ab94a85..43ea83e43fc 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/Tag.java @@ -5,7 +5,10 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="A tag for a pet") public class Tag { @@ -15,6 +18,7 @@ public class Tag { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("id") public Long getId() { return id; @@ -26,6 +30,7 @@ public class Tag { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("name") public String getName() { return name; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/User.java index e95e76c1b41..f238a851d7c 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/io/swagger/model/User.java @@ -5,7 +5,10 @@ import java.util.ArrayList; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; +import io.swagger.annotations.*; +@ApiModel(description="A User who is purchasing from the pet store") public class User { @@ -21,6 +24,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("id") public Long getId() { return id; @@ -32,6 +36,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("username") public String getUsername() { return username; @@ -43,6 +48,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("firstName") public String getFirstName() { return firstName; @@ -54,6 +60,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("lastName") public String getLastName() { return lastName; @@ -65,6 +72,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("email") public String getEmail() { return email; @@ -76,6 +84,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("password") public String getPassword() { return password; @@ -87,6 +96,7 @@ public class User { /** **/ + @ApiModelProperty(example = "null", value = "") @JsonProperty("phone") public String getPhone() { return phone; @@ -99,6 +109,7 @@ public class User { * User Status **/ + @ApiModelProperty(example = "null", value = "User Status") @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; diff --git a/samples/server/petstore/jaxrs-spec/.swagger-codegen-ignore b/samples/server/petstore/jaxrs-spec/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/jaxrs-spec/pom.xml b/samples/server/petstore/jaxrs-spec/pom.xml index c06fcab78d0..0c8ec37669a 100644 --- a/samples/server/petstore/jaxrs-spec/pom.xml +++ b/samples/server/petstore/jaxrs-spec/pom.xml @@ -1,9 +1,9 @@ 4.0.0 - wasdev - autogen-server + io.swagger + swagger-jaxrs-server war - autogen-server + swagger-jaxrs-server 1.0.0 src/main/java @@ -69,6 +69,13 @@ + + + javax.validation + validation-api + 1.1.0.Final + provided + 4.8.1 diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/FakeApi.java new file mode 100644 index 00000000000..f8581b82c1b --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/FakeApi.java @@ -0,0 +1,61 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import org.joda.time.LocalDate; + +import javax.ws.rs.*; +import javax.ws.rs.core.Response; + +import io.swagger.annotations.*; + +import java.util.List; +import javax.validation.constraints.*; + +@Path("/fake") + +@Api(description = "the fake API") + + + + +public class FakeApi { + + @PATCH + + @Consumes({ "application/json" }) + @Produces({ "application/json" }) + @ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + public Response testClientModel(Client body) { + return Response.ok().entity("magic!").build(); + } + + @POST + + @Consumes({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @Produces({ "application/xml; charset=utf-8", "application/json; charset=utf-8" }) + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = void.class, authorizations = { + @Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), + @ApiResponse(code = 404, message = "User not found", response = void.class) }) + public Response testEndpointParameters(@FormParam(value = "number") BigDecimal number,@FormParam(value = "_double") Double _double,@FormParam(value = "patternWithoutDelimiter") String patternWithoutDelimiter,@FormParam(value = "_byte") byte[] _byte,@FormParam(value = "integer") Integer integer,@FormParam(value = "int32") Integer int32,@FormParam(value = "int64") Long int64,@FormParam(value = "_float") Float _float,@FormParam(value = "string") String string,@FormParam(value = "binary") byte[] binary,@FormParam(value = "date") LocalDate date,@FormParam(value = "dateTime") javax.xml.datatype.XMLGregorianCalendar dateTime,@FormParam(value = "password") String password,@FormParam(value = "paramCallback") String paramCallback) { + return Response.ok().entity("magic!").build(); + } + + @GET + + @Consumes({ "*/*" }) + @Produces({ "*/*" }) + @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = void.class, tags={ "fake" }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid request", response = void.class), + @ApiResponse(code = 404, message = "Not found", response = void.class) }) + public Response testEnumParameters(@FormParam(value = "enumFormStringArray") List enumFormStringArray,@FormParam(value = "enumFormString") String enumFormString,@HeaderParam("enum_header_string_array") List enumHeaderStringArray,@HeaderParam("enum_header_string") String enumHeaderString,@QueryParam("enum_query_string_array") List enumQueryStringArray,@QueryParam("enum_query_string") String enumQueryString,@QueryParam("enum_query_integer") Integer enumQueryInteger,@FormParam(value = "enumQueryDouble") Double enumQueryDouble) { + return Response.ok().entity("magic!").build(); + } +} + diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/PetApi.java similarity index 59% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/PetApi.java index bb3beaf9f89..f19581bb7e6 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/PetsApi.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/PetApi.java @@ -1,6 +1,8 @@ -package com.ibm.ws.petstoresample.api; +package io.swagger.api; -import com.ibm.ws.petstoresample.model.Pet; +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; import javax.ws.rs.*; import javax.ws.rs.core.Response; @@ -8,24 +10,25 @@ import javax.ws.rs.core.Response; import io.swagger.annotations.*; import java.util.List; +import javax.validation.constraints.*; -@Path("/pets") +@Path("/pet") -@Api(description = "the pets API") +@Api(description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSSpecServerCodegen", date = "2016-06-06T11:04:02.369-04:00") -public class PetsApi { + +public class PetApi { @POST @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Add a new pet to the store", notes = "", response = void.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @ApiResponses(value = { @@ -37,80 +40,76 @@ public class PetsApi { @DELETE @Path("/{petId}") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Deletes a pet", notes = "", response = void.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value", response = void.class) }) - public Response deletePet(@HeaderParam("api_key") String apiKey,@PathParam("petId") Long petId) { + public Response deletePet(@PathParam("petId") @ApiParam("Pet id to delete") Long petId,@HeaderParam("api_key") String apiKey) { return Response.ok().entity("magic!").build(); } @GET @Path("/findByStatus") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @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 = Pet.class, responseContainer = "List") }) - public Response findPetsByStatus(@QueryParam("status") List status) { + public Response findPetsByStatus(@QueryParam("status") @NotNull List status) { return Response.ok().entity("magic!").build(); } @GET @Path("/findByTags") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @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 tag value", response = Pet.class, responseContainer = "List") }) - public Response findPetsByTags(@QueryParam("tags") List tags) { + public Response findPetsByTags(@QueryParam("tags") @NotNull List tags) { return Response.ok().entity("magic!").build(); } @GET @Path("/{petId}") - @Produces({ "application/json", "application/xml" }) - @ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") - }), + @Produces({ "application/xml", "application/json" }) + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") }, tags={ "pet", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) - public Response getPetById(@PathParam("petId") Long petId) { + public Response getPetById(@PathParam("petId") @ApiParam("ID of pet to return") Long petId) { return Response.ok().entity("magic!").build(); } @PUT @Consumes({ "application/json", "application/xml" }) - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Update an existing pet", notes = "", response = void.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") }) }, tags={ "pet", }) @ApiResponses(value = { @@ -124,16 +123,33 @@ public class PetsApi { @POST @Path("/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = void.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write_pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read_pets", description = "read your pets") + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = void.class) }) + public 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) { + return Response.ok().entity("magic!").build(); + } + + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, 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" }) @ApiResponses(value = { - @ApiResponse(code = 405, message = "Invalid input", response = void.class) }) - public Response updatePetWithForm(@PathParam("petId") String petId,@FormParam(value = "name") String name,@FormParam(value = "status") String status) { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + public Response uploadFile(@PathParam("petId") @ApiParam("ID of pet to update") Long petId,@FormParam(value = "additionalMetadata") String additionalMetadata, @FormParam(value = "file") InputStream fileInputStream, + @FormParam(value = "file") Attachment fileDetail) { return Response.ok().entity("magic!").build(); } } diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/RestApplication.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/RestApplication.java similarity index 81% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/RestApplication.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/RestApplication.java index 9c43b1e80ba..56e801bbf5f 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/RestApplication.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/RestApplication.java @@ -1,4 +1,4 @@ -package com.ibm.ws.petstoresample; +package io.swagger.api; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/StoresApi.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/StoreApi.java similarity index 58% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/StoresApi.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/StoreApi.java index 4f7613eed27..0b0522fad8e 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/StoresApi.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/StoreApi.java @@ -1,6 +1,7 @@ -package com.ibm.ws.petstoresample.api; +package io.swagger.api; -import com.ibm.ws.petstoresample.model.Order; +import java.util.Map; +import io.swagger.model.Order; import javax.ws.rs.*; import javax.ws.rs.core.Response; @@ -8,45 +9,59 @@ import javax.ws.rs.core.Response; import io.swagger.annotations.*; import java.util.List; +import javax.validation.constraints.*; -@Path("/stores") +@Path("/store") -@Api(description = "the stores API") +@Api(description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSSpecServerCodegen", date = "2016-06-06T11:04:02.369-04:00") -public class StoresApi { + +public class StoreApi { @DELETE @Path("/order/{orderId}") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @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", response = void.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid ID supplied", response = void.class), @ApiResponse(code = 404, message = "Order not found", response = void.class) }) - public Response deleteOrder(@PathParam("orderId") String orderId) { + public Response deleteOrder(@PathParam("orderId") @ApiParam("ID of the order that needs to be deleted") String orderId) { + return Response.ok().entity("magic!").build(); + } + + @GET + @Path("/inventory") + + @Produces({ "application/json" }) + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) + public Response getInventory() { return Response.ok().entity("magic!").build(); } @GET @Path("/order/{orderId}") - @Produces({ "application/json", "application/xml" }) + @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", response = Order.class, tags={ "store", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) - public Response getOrderById(@PathParam("orderId") String orderId) { + public Response getOrderById(@PathParam("orderId") @Min(1) @Max(5) @ApiParam("ID of pet that needs to be fetched") Long orderId) { return Response.ok().entity("magic!").build(); } @POST @Path("/order") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Order.class), diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/UsersApi.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/UserApi.java similarity index 75% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/UsersApi.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/UserApi.java index 4bf8701edbf..55a323774b8 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/api/UsersApi.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/api/UserApi.java @@ -1,7 +1,7 @@ -package com.ibm.ws.petstoresample.api; +package io.swagger.api; -import com.ibm.ws.petstoresample.model.User; import java.util.List; +import io.swagger.model.User; import javax.ws.rs.*; import javax.ws.rs.core.Response; @@ -9,20 +9,21 @@ import javax.ws.rs.core.Response; import io.swagger.annotations.*; import java.util.List; +import javax.validation.constraints.*; -@Path("/users") +@Path("/user") -@Api(description = "the users API") +@Api(description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaJAXRSSpecServerCodegen", date = "2016-06-06T11:04:02.369-04:00") -public class UsersApi { + +public class UserApi { @POST - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = void.class) }) @@ -33,7 +34,7 @@ public class UsersApi { @POST @Path("/createWithArray") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = void.class) }) @@ -44,7 +45,7 @@ public class UsersApi { @POST @Path("/createWithList") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Creates list of users with given input array", notes = "", response = void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = void.class) }) @@ -55,44 +56,44 @@ public class UsersApi { @DELETE @Path("/{username}") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid username supplied", response = void.class), @ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response deleteUser(@PathParam("username") String username) { + public Response deleteUser(@PathParam("username") @ApiParam("The name that needs to be deleted") String username) { return Response.ok().entity("magic!").build(); } @GET @Path("/{username}") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = User.class), @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), @ApiResponse(code = 404, message = "User not found", response = User.class) }) - public Response getUserByName(@PathParam("username") String username) { + public Response getUserByName(@PathParam("username") @ApiParam("The name that needs to be fetched. Use user1 for testing. ") String username) { return Response.ok().entity("magic!").build(); } @GET @Path("/login") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) - public Response loginUser(@QueryParam("username") String username,@QueryParam("password") String password) { + public Response loginUser(@QueryParam("username") @NotNull String username,@QueryParam("password") @NotNull String password) { return Response.ok().entity("magic!").build(); } @GET @Path("/logout") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Logs out current logged in user session", notes = "", response = void.class, tags={ "user", }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = void.class) }) @@ -103,12 +104,12 @@ public class UsersApi { @PUT @Path("/{username}") - @Produces({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = void.class, tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid user supplied", response = void.class), @ApiResponse(code = 404, message = "User not found", response = void.class) }) - public Response updateUser(@PathParam("username") String username,User body) { + public Response updateUser(@PathParam("username") @ApiParam("name that need to be deleted") String username,User body) { return Response.ok().entity("magic!").build(); } } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..e30da46f35a --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,90 @@ +package io.swagger.model; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class AdditionalPropertiesClass { + + private Map mapProperty = new HashMap(); + private Map> mapOfMapProperty = new HashMap>(); + + /** + **/ + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Map getMapProperty() { + return mapProperty; + } + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + /** + **/ + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..64d5951369d --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Animal.java @@ -0,0 +1,90 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class Animal { + + private String className = null; + private String color = "red"; + + /** + **/ + public Animal className(String className) { + this.className = className; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @NotNull + public String getClassName() { + return className; + } + public void setClassName(String className) { + this.className = className; + } + + /** + **/ + public Animal color(String color) { + this.color = color; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getColor() { + return color; + } + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(className, animal.className) && + Objects.equals(color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..b7fe2f4cc88 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,53 @@ +package io.swagger.model; + +import io.swagger.model.Animal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class AnimalFarm extends ArrayList { + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AnimalFarm animalFarm = (AnimalFarm) o; + return true; + } + + @Override + public int hashCode() { + return Objects.hash(); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..eca82ce2346 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,71 @@ +package io.swagger.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class ArrayOfArrayOfNumberOnly { + + private List> arrayArrayNumber = new ArrayList>(); + + /** + **/ + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..0781aaa524f --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,71 @@ +package io.swagger.model; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class ArrayOfNumberOnly { + + private List arrayNumber = new ArrayList(); + + /** + **/ + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public List getArrayNumber() { + return arrayNumber; + } + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..ec005634cc3 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,109 @@ +package io.swagger.model; + +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class ArrayTest { + + private List arrayOfString = new ArrayList(); + private List> arrayArrayOfInteger = new ArrayList>(); + private List> arrayArrayOfModel = new ArrayList>(); + + /** + **/ + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public List getArrayOfString() { + return arrayOfString; + } + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + /** + **/ + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + /** + **/ + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(arrayOfString, arrayTest.arrayOfString) && + Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Capitalization.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..1259f458e33 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Capitalization.java @@ -0,0 +1,164 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class Capitalization { + + private String smallCamel = null; + private String capitalCamel = null; + private String smallSnake = null; + private String capitalSnake = null; + private String scAETHFlowPoints = null; + private String ATT_NAME = null; + + /** + **/ + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getSmallCamel() { + return smallCamel; + } + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + /** + **/ + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getCapitalCamel() { + return capitalCamel; + } + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + /** + **/ + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getSmallSnake() { + return smallSnake; + } + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + /** + **/ + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getCapitalSnake() { + return capitalSnake; + } + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + /** + **/ + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + /** + * Name of the pet + **/ + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + + @ApiModelProperty(example = "null", value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(smallCamel, capitalization.smallCamel) && + Objects.equals(capitalCamel, capitalization.capitalCamel) && + Objects.equals(smallSnake, capitalization.smallSnake) && + Objects.equals(capitalSnake, capitalization.capitalSnake) && + Objects.equals(scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..45f8e305503 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Cat.java @@ -0,0 +1,69 @@ +package io.swagger.model; + +import io.swagger.model.Animal; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class Cat extends Animal { + + private Boolean declawed = null; + + /** + **/ + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Boolean getDeclawed() { + return declawed; + } + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(declawed, cat.declawed); + } + + @Override + public int hashCode() { + return Objects.hash(declawed); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Category.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Category.java similarity index 96% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Category.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Category.java index cef2cf7ff95..08ce4b59b3a 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Category.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Category.java @@ -1,6 +1,6 @@ -package com.ibm.ws.petstoresample.model; - +package io.swagger.model; +import javax.validation.constraints.*; import io.swagger.annotations.*; diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ClassModel.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..b185dec45cb --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ClassModel.java @@ -0,0 +1,72 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + + +/** + * Model for testing model with \"_class\" property + **/ +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + + private String propertyClass = null; + + /** + **/ + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..7680ebe1b58 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Client.java @@ -0,0 +1,68 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class Client { + + private String client = null; + + /** + **/ + public Client client(String client) { + this.client = client; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getClient() { + return client; + } + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..e48f4c000ef --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Dog.java @@ -0,0 +1,69 @@ +package io.swagger.model; + +import io.swagger.model.Animal; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class Dog extends Animal { + + private String breed = null; + + /** + **/ + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getBreed() { + return breed; + } + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(breed, dog.breed); + } + + @Override + public int hashCode() { + return Objects.hash(breed); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..7aca1496efe --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,151 @@ +package io.swagger.model; + +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class EnumArrays { + + +public enum JustSymbolEnum { + + GREATER_THAN_OR_EQUAL_TO(String.valueOf(">=")), DOLLAR(String.valueOf("$")); + + + private String value; + + JustSymbolEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static JustSymbolEnum fromValue(String v) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + private JustSymbolEnum justSymbol = null; + +public enum ArrayEnumEnum { + + FISH(String.valueOf("fish")), CRAB(String.valueOf("crab")); + + + private String value; + + ArrayEnumEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static ArrayEnumEnum fromValue(String v) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + private List arrayEnum = new ArrayList(); + + /** + **/ + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + /** + **/ + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public List getArrayEnum() { + return arrayEnum; + } + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(justSymbol, enumArrays.justSymbol) && + Objects.equals(arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..dfbfdfcff30 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumClass.java @@ -0,0 +1,43 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + + diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..bb602ad3b73 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/EnumTest.java @@ -0,0 +1,219 @@ +package io.swagger.model; + +import io.swagger.model.OuterEnum; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class EnumTest { + + +public enum EnumStringEnum { + + UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")), EMPTY(String.valueOf("")); + + + private String value; + + EnumStringEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStringEnum fromValue(String v) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + private EnumStringEnum enumString = null; + +public enum EnumIntegerEnum { + + NUMBER_1(Integer.valueOf(1)), NUMBER_MINUS_1(Integer.valueOf(-1)); + + + private Integer value; + + EnumIntegerEnum (Integer v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumIntegerEnum fromValue(String v) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + private EnumIntegerEnum enumInteger = null; + +public enum EnumNumberEnum { + + NUMBER_1_DOT_1(Double.valueOf(1.1)), NUMBER_MINUS_1_DOT_2(Double.valueOf(-1.2)); + + + private Double value; + + EnumNumberEnum (Double v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumNumberEnum fromValue(String v) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + private EnumNumberEnum enumNumber = null; + private OuterEnum outerEnum = null; + + /** + **/ + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + /** + **/ + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + /** + **/ + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + /** + **/ + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(enumString, enumTest.enumString) && + Objects.equals(enumInteger, enumTest.enumInteger) && + Objects.equals(enumNumber, enumTest.enumNumber) && + Objects.equals(outerEnum, enumTest.outerEnum); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/FormatTest.java new file mode 100644 index 00000000000..b11fec88aab --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/FormatTest.java @@ -0,0 +1,325 @@ +package io.swagger.model; + +import java.math.BigDecimal; +import java.util.UUID; +import org.joda.time.LocalDate; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class FormatTest { + + private Integer integer = null; + private Integer int32 = null; + private Long int64 = null; + private BigDecimal number = null; + private Float _float = null; + private Double _double = null; + private String string = null; + private byte[] _byte = null; + private byte[] binary = null; + private LocalDate date = null; + private javax.xml.datatype.XMLGregorianCalendar dateTime = null; + private UUID uuid = null; + private String password = null; + + /** + * minimum: 10 + * maximum: 100 + **/ + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @Min(10) + @Max(100) + public Integer getInteger() { + return integer; + } + public void setInteger(Integer integer) { + this.integer = integer; + } + + /** + * minimum: 20 + * maximum: 200 + **/ + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @Min(20) + @Max(200) + public Integer getInt32() { + return int32; + } + public void setInt32(Integer int32) { + this.int32 = int32; + } + + /** + **/ + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Long getInt64() { + return int64; + } + public void setInt64(Long int64) { + this.int64 = int64; + } + + /** + * minimum: 32.1 + * maximum: 543.2 + **/ + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") + public BigDecimal getNumber() { + return number; + } + public void setNumber(BigDecimal number) { + this.number = number; + } + + /** + * minimum: 54.3 + * maximum: 987.6 + **/ + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @DecimalMin("54.3") + @DecimalMax("987.6") + public Float getFloat() { + return _float; + } + public void setFloat(Float _float) { + this._float = _float; + } + + /** + * minimum: 67.8 + * maximum: 123.4 + **/ + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @DecimalMin("67.8") + @DecimalMax("123.4") + public Double getDouble() { + return _double; + } + public void setDouble(Double _double) { + this._double = _double; + } + + /** + **/ + public FormatTest string(String string) { + this.string = string; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + @Pattern(regexp="/[a-z]/i") + public String getString() { + return string; + } + public void setString(String string) { + this.string = string; + } + + /** + **/ + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @NotNull + public byte[] getByte() { + return _byte; + } + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + /** + **/ + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public byte[] getBinary() { + return binary; + } + public void setBinary(byte[] binary) { + this.binary = binary; + } + + /** + **/ + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @NotNull + public LocalDate getDate() { + return date; + } + public void setDate(LocalDate date) { + this.date = date; + } + + /** + **/ + public FormatTest dateTime(javax.xml.datatype.XMLGregorianCalendar dateTime) { + this.dateTime = dateTime; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public javax.xml.datatype.XMLGregorianCalendar getDateTime() { + return dateTime; + } + public void setDateTime(javax.xml.datatype.XMLGregorianCalendar dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + public FormatTest uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public UUID getUuid() { + return uuid; + } + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + /** + **/ + public FormatTest password(String password) { + this.password = password; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @NotNull + @Size(min=10,max=64) + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(integer, formatTest.integer) && + Objects.equals(int32, formatTest.int32) && + Objects.equals(int64, formatTest.int64) && + Objects.equals(number, formatTest.number) && + Objects.equals(_float, formatTest._float) && + Objects.equals(_double, formatTest._double) && + Objects.equals(string, formatTest.string) && + Objects.equals(_byte, formatTest._byte) && + Objects.equals(binary, formatTest.binary) && + Objects.equals(date, formatTest.date) && + Objects.equals(dateTime, formatTest.dateTime) && + Objects.equals(uuid, formatTest.uuid) && + Objects.equals(password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..f0bb80cdeb8 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,87 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class HasOnlyReadOnly { + + private String bar = null; + private String foo = null; + + /** + **/ + public HasOnlyReadOnly bar(String bar) { + this.bar = bar; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + public void setBar(String bar) { + this.bar = bar; + } + + /** + **/ + public HasOnlyReadOnly foo(String foo) { + this.foo = foo; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getFoo() { + return foo; + } + public void setFoo(String foo) { + this.foo = foo; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(bar, hasOnlyReadOnly.bar) && + Objects.equals(foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..39e105546fe --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MapTest.java @@ -0,0 +1,121 @@ +package io.swagger.model; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class MapTest { + + private Map> mapMapOfString = new HashMap>(); + +public enum InnerEnum { + + UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")); + + + private String value; + + InnerEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static InnerEnum fromValue(String v) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + private Map mapOfEnumString = new HashMap(); + + /** + **/ + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + /** + **/ + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..6c4654ce3a5 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,111 @@ +package io.swagger.model; + +import io.swagger.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class MixedPropertiesAndAdditionalPropertiesClass { + + private UUID uuid = null; + private javax.xml.datatype.XMLGregorianCalendar dateTime = null; + private Map map = new HashMap(); + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public UUID getUuid() { + return uuid; + } + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass dateTime(javax.xml.datatype.XMLGregorianCalendar dateTime) { + this.dateTime = dateTime; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public javax.xml.datatype.XMLGregorianCalendar getDateTime() { + return dateTime; + } + public void setDateTime(javax.xml.datatype.XMLGregorianCalendar dateTime) { + this.dateTime = dateTime; + } + + /** + **/ + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Map getMap() { + return map; + } + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..2278ea9212d --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Model200Response.java @@ -0,0 +1,91 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + + +/** + * Model for testing model name starting with number + **/ +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + + private Integer name = null; + private String propertyClass = null; + + /** + **/ + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + /** + **/ + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getPropertyClass() { + return propertyClass; + } + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(name, _200Response.name) && + Objects.equals(propertyClass, _200Response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..9e570802581 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,106 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class ModelApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + /** + **/ + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..9c348ada11a --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,72 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + + +/** + * Model for testing reserved words + **/ +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + + private Integer _return = null; + + /** + **/ + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Integer getReturn() { + return _return; + } + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(_return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..dbf1620a75a --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Name.java @@ -0,0 +1,130 @@ +package io.swagger.model; + +import io.swagger.annotations.ApiModel; +import javax.validation.constraints.*; + + +/** + * Model for testing model name same as property name + **/ +import io.swagger.annotations.*; +import java.util.Objects; +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + + private Integer name = null; + private Integer snakeCase = null; + private String property = null; + private Integer _123Number = null; + + /** + **/ + public Name name(Integer name) { + this.name = name; + return this; + } + + + @ApiModelProperty(example = "null", required = true, value = "") + @NotNull + public Integer getName() { + return name; + } + public void setName(Integer name) { + this.name = name; + } + + /** + **/ + public Name snakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Integer getSnakeCase() { + return snakeCase; + } + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + /** + **/ + public Name property(String property) { + this.property = property; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getProperty() { + return property; + } + public void setProperty(String property) { + this.property = property; + } + + /** + **/ + public Name _123Number(Integer _123Number) { + this._123Number = _123Number; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Integer get123Number() { + return _123Number; + } + public void set123Number(Integer _123Number) { + this._123Number = _123Number; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(name, name.name) && + Objects.equals(snakeCase, name.snakeCase) && + Objects.equals(property, name.property) && + Objects.equals(_123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..cfd26e8bbc1 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,69 @@ +package io.swagger.model; + +import java.math.BigDecimal; +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class NumberOnly { + + private BigDecimal justNumber = null; + + /** + **/ + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Order.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Order.java similarity index 79% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Order.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Order.java index ce7995e3437..c9af9b68a99 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Order.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Order.java @@ -1,6 +1,6 @@ -package com.ibm.ws.petstoresample.model; - +package io.swagger.model; +import javax.validation.constraints.*; import io.swagger.annotations.*; @@ -13,8 +13,39 @@ public class Order { private Long petId = null; private Integer quantity = null; private javax.xml.datatype.XMLGregorianCalendar shipDate = null; - private String status = null; - private Boolean complete = null; + +public enum StatusEnum { + + PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + private StatusEnum status = null; + private Boolean complete = false; /** **/ @@ -83,17 +114,17 @@ public class Order { /** * Order Status **/ - public Order status(String status) { + public Order status(StatusEnum status) { this.status = status; return this; } @ApiModelProperty(example = "null", value = "Order Status") - public String getStatus() { + public StatusEnum getStatus() { return status; } - public void setStatus(String status) { + public void setStatus(StatusEnum status) { this.status = status; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..65a4e1183f6 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,43 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + + diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Pet.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Pet.java similarity index 79% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Pet.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Pet.java index 30e81e1c988..dafcad72d14 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Pet.java @@ -1,10 +1,10 @@ -package com.ibm.ws.petstoresample.model; +package io.swagger.model; -import com.ibm.ws.petstoresample.model.Category; -import com.ibm.ws.petstoresample.model.Tag; +import io.swagger.model.Category; +import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; import io.swagger.annotations.*; @@ -18,7 +18,38 @@ public class Pet { private String name = null; private List photoUrls = new ArrayList(); private List tags = new ArrayList(); - private String status = null; + +public enum StatusEnum { + + AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); + + + private String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String v) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(v)) { + return b; + } + } + return null; + } +} + + private StatusEnum status = null; /** **/ @@ -61,6 +92,7 @@ public class Pet { @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull public String getName() { return name; } @@ -77,6 +109,7 @@ public class Pet { @ApiModelProperty(example = "null", required = true, value = "") + @NotNull public List getPhotoUrls() { return photoUrls; } @@ -103,17 +136,17 @@ public class Pet { /** * pet status in the store **/ - public Pet status(String status) { + public Pet status(StatusEnum status) { this.status = status; return this; } @ApiModelProperty(example = "null", value = "pet status in the store") - public String getStatus() { + public StatusEnum getStatus() { return status; } - public void setStatus(String status) { + public void setStatus(StatusEnum status) { this.status = status; } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..cfdba394a3e --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,87 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class ReadOnlyFirst { + + private String bar = null; + private String baz = null; + + /** + **/ + public ReadOnlyFirst bar(String bar) { + this.bar = bar; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getBar() { + return bar; + } + public void setBar(String bar) { + this.bar = bar; + } + + /** + **/ + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public String getBaz() { + return baz; + } + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(bar, readOnlyFirst.bar) && + Objects.equals(baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..9b80b631cc7 --- /dev/null +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,68 @@ +package io.swagger.model; + +import javax.validation.constraints.*; + + +import io.swagger.annotations.*; +import java.util.Objects; + + +public class SpecialModelName { + + private Long specialPropertyName = null; + + /** + **/ + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + + @ApiModelProperty(example = "null", value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Tag.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Tag.java similarity index 96% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Tag.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Tag.java index 351770bd7c5..1debd2a7ecb 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/Tag.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/Tag.java @@ -1,6 +1,6 @@ -package com.ibm.ws.petstoresample.model; - +package io.swagger.model; +import javax.validation.constraints.*; import io.swagger.annotations.*; diff --git a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/User.java b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/User.java similarity index 98% rename from samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/User.java rename to samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/User.java index 22369ba154d..4b2896fa862 100644 --- a/samples/server/petstore/jaxrs-spec/src/main/java/com/ibm/ws/petstoresample/model/User.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/io/swagger/model/User.java @@ -1,6 +1,6 @@ -package com.ibm.ws.petstoresample.model; - +package io.swagger.model; +import javax.validation.constraints.*; import io.swagger.annotations.*; diff --git a/samples/server/petstore/jaxrs-spec/swagger.json b/samples/server/petstore/jaxrs-spec/swagger.json index 4524933cd36..24eecd9e3ae 100644 --- a/samples/server/petstore/jaxrs-spec/swagger.json +++ b/samples/server/petstore/jaxrs-spec/swagger.json @@ -1,12 +1,12 @@ { "swagger" : "2.0", "info" : { - "description" : "This is a sample server Petstore server.\n\n[Learn about Swagger](http://swagger.io) or join the IRC channel `#swagger` on irc.freenode.net.\n\nFor this sample, you can use the api key `special-key` to test the authorization filters\n", + "description" : "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\", "version" : "1.0.0", "title" : "Swagger Petstore", - "termsOfService" : "http://helloreverb.com/terms/", + "termsOfService" : "http://swagger.io/terms/", "contact" : { - "name" : "apiteam@swagger.io" + "email" : "apiteam@swagger.io" }, "license" : { "name" : "Apache 2.0", @@ -15,21 +15,39 @@ }, "host" : "petstore.swagger.io", "basePath" : "/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" + } + } ], "schemes" : [ "http" ], "paths" : { - "/pets" : { + "/pet" : { "post" : { "tags" : [ "pet" ], "summary" : "Add a new pet to the store", "description" : "", "operationId" : "addPet", "consumes" : [ "application/json", "application/xml" ], - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "in" : "body", "name" : "body", "description" : "Pet object that needs to be added to the store", - "required" : false, + "required" : true, "schema" : { "$ref" : "#/definitions/Pet" } @@ -40,7 +58,7 @@ } }, "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] + "petstore_auth" : [ "write:pets", "read:pets" ] } ] }, "put" : { @@ -49,12 +67,12 @@ "description" : "", "operationId" : "updatePet", "consumes" : [ "application/json", "application/xml" ], - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "in" : "body", "name" : "body", "description" : "Pet object that needs to be added to the store", - "required" : false, + "required" : true, "schema" : { "$ref" : "#/definitions/Pet" } @@ -71,27 +89,29 @@ } }, "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] + "petstore_auth" : [ "write:pets", "read:pets" ] } ] } }, - "/pets/findByStatus" : { + "/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/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "status", "in" : "query", "description" : "Status values that need to be considered for filter", - "required" : false, + "required" : true, "type" : "array", "items" : { - "type" : "string" + "type" : "string", + "default" : "available", + "enum" : [ "available", "pending", "sold" ] }, - "collectionFormat" : "multi" + "collectionFormat" : "csv" } ], "responses" : { "200" : { @@ -108,27 +128,27 @@ } }, "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] + "petstore_auth" : [ "write:pets", "read:pets" ] } ] } }, - "/pets/findByTags" : { + "/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/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "tags", "in" : "query", "description" : "Tags to filter by", - "required" : false, + "required" : true, "type" : "array", "items" : { "type" : "string" }, - "collectionFormat" : "multi" + "collectionFormat" : "csv" } ], "responses" : { "200" : { @@ -145,21 +165,21 @@ } }, "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] + "petstore_auth" : [ "write:pets", "read:pets" ] } ] } }, - "/pets/{petId}" : { + "/pet/{petId}" : { "get" : { "tags" : [ "pet" ], "summary" : "Find pet by ID", - "description" : "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", + "description" : "Returns a single pet", "operationId" : "getPetById", - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "petId", "in" : "path", - "description" : "ID of pet that needs to be fetched", + "description" : "ID of pet to return", "required" : true, "type" : "integer", "format" : "int64" @@ -180,8 +200,6 @@ }, "security" : [ { "api_key" : [ ] - }, { - "petstore_auth" : [ "write_pets", "read_pets" ] } ] }, "post" : { @@ -190,24 +208,25 @@ "description" : "", "operationId" : "updatePetWithForm", "consumes" : [ "application/x-www-form-urlencoded" ], - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "petId", "in" : "path", "description" : "ID of pet that needs to be updated", "required" : true, - "type" : "string" + "type" : "integer", + "format" : "int64" }, { "name" : "name", "in" : "formData", "description" : "Updated name of the pet", - "required" : true, + "required" : false, "type" : "string" }, { "name" : "status", "in" : "formData", "description" : "Updated status of the pet", - "required" : true, + "required" : false, "type" : "string" } ], "responses" : { @@ -216,7 +235,7 @@ } }, "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] + "petstore_auth" : [ "write:pets", "read:pets" ] } ] }, "delete" : { @@ -224,12 +243,11 @@ "summary" : "Deletes a pet", "description" : "", "operationId" : "deletePet", - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "api_key", "in" : "header", - "description" : "", - "required" : true, + "required" : false, "type" : "string" }, { "name" : "petId", @@ -245,22 +263,88 @@ } }, "security" : [ { - "petstore_auth" : [ "write_pets", "read_pets" ] + "petstore_auth" : [ "write:pets", "read:pets" ] } ] } }, - "/stores/order" : { + "/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/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "in" : "body", "name" : "body", "description" : "order placed for purchasing the pet", - "required" : false, + "required" : true, "schema" : { "$ref" : "#/definitions/Order" } @@ -278,19 +362,22 @@ } } }, - "/stores/order/{orderId}" : { + "/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/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "orderId", "in" : "path", "description" : "ID of pet that needs to be fetched", "required" : true, - "type" : "string" + "type" : "integer", + "maximum" : 5.0, + "minimum" : 1.0, + "format" : "int64" } ], "responses" : { "200" : { @@ -312,7 +399,7 @@ "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/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "orderId", "in" : "path", @@ -330,18 +417,18 @@ } } }, - "/users" : { + "/user" : { "post" : { "tags" : [ "user" ], "summary" : "Create user", "description" : "This can only be done by the logged in user.", "operationId" : "createUser", - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "in" : "body", "name" : "body", "description" : "Created user object", - "required" : false, + "required" : true, "schema" : { "$ref" : "#/definitions/User" } @@ -353,18 +440,18 @@ } } }, - "/users/createWithArray" : { + "/user/createWithArray" : { "post" : { "tags" : [ "user" ], "summary" : "Creates list of users with given input array", "description" : "", "operationId" : "createUsersWithArrayInput", - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "in" : "body", "name" : "body", "description" : "List of user object", - "required" : false, + "required" : true, "schema" : { "type" : "array", "items" : { @@ -379,18 +466,18 @@ } } }, - "/users/createWithList" : { + "/user/createWithList" : { "post" : { "tags" : [ "user" ], "summary" : "Creates list of users with given input array", "description" : "", "operationId" : "createUsersWithListInput", - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "in" : "body", "name" : "body", "description" : "List of user object", - "required" : false, + "required" : true, "schema" : { "type" : "array", "items" : { @@ -405,24 +492,24 @@ } } }, - "/users/login" : { + "/user/login" : { "get" : { "tags" : [ "user" ], "summary" : "Logs user into the system", "description" : "", "operationId" : "loginUser", - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "username", "in" : "query", "description" : "The user name for login", - "required" : false, + "required" : true, "type" : "string" }, { "name" : "password", "in" : "query", "description" : "The password for login in clear text", - "required" : false, + "required" : true, "type" : "string" } ], "responses" : { @@ -430,6 +517,18 @@ "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" : { @@ -438,13 +537,13 @@ } } }, - "/users/logout" : { + "/user/logout" : { "get" : { "tags" : [ "user" ], "summary" : "Logs out current logged in user session", "description" : "", "operationId" : "logoutUser", - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ ], "responses" : { "default" : { @@ -453,17 +552,17 @@ } } }, - "/users/{username}" : { + "/user/{username}" : { "get" : { "tags" : [ "user" ], "summary" : "Get user by user name", "description" : "", "operationId" : "getUserByName", - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "username", "in" : "path", - "description" : "The name that needs to be fetched. Use user1 for testing.", + "description" : "The name that needs to be fetched. Use user1 for testing. ", "required" : true, "type" : "string" } ], @@ -487,7 +586,7 @@ "summary" : "Updated user", "description" : "This can only be done by the logged in user.", "operationId" : "updateUser", - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "username", "in" : "path", @@ -498,7 +597,7 @@ "in" : "body", "name" : "body", "description" : "Updated user object", - "required" : false, + "required" : true, "schema" : { "$ref" : "#/definitions/User" } @@ -517,7 +616,7 @@ "summary" : "Delete user", "description" : "This can only be done by the logged in user.", "operationId" : "deleteUser", - "produces" : [ "application/json", "application/xml" ], + "produces" : [ "application/xml", "application/json" ], "parameters" : [ { "name" : "username", "in" : "path", @@ -534,6 +633,247 @@ } } } + }, + "/fake" : { + "get" : { + "tags" : [ "fake" ], + "summary" : "To test enum parameters", + "description" : "To test enum parameters", + "operationId" : "testEnumParameters", + "consumes" : [ "*/*" ], + "produces" : [ "*/*" ], + "parameters" : [ { + "name" : "enum_form_string_array", + "in" : "formData", + "description" : "Form parameter enum test (string array)", + "required" : false, + "type" : "array", + "items" : { + "type" : "string", + "default" : "$", + "enum" : [ ">", "$" ] + } + }, { + "name" : "enum_form_string", + "in" : "formData", + "description" : "Form parameter enum test (string)", + "required" : false, + "type" : "string", + "default" : "-efg", + "enum" : [ "_abc", "-efg", "(xyz)" ] + }, { + "name" : "enum_header_string_array", + "in" : "header", + "description" : "Header parameter enum test (string array)", + "required" : false, + "type" : "array", + "items" : { + "type" : "string", + "default" : "$", + "enum" : [ ">", "$" ] + } + }, { + "name" : "enum_header_string", + "in" : "header", + "description" : "Header parameter enum test (string)", + "required" : false, + "type" : "string", + "default" : "-efg", + "enum" : [ "_abc", "-efg", "(xyz)" ] + }, { + "name" : "enum_query_string_array", + "in" : "query", + "description" : "Query parameter enum test (string array)", + "required" : false, + "type" : "array", + "items" : { + "type" : "string", + "default" : "$", + "enum" : [ ">", "$" ] + } + }, { + "name" : "enum_query_string", + "in" : "query", + "description" : "Query parameter enum test (string)", + "required" : false, + "type" : "string", + "default" : "-efg", + "enum" : [ "_abc", "-efg", "(xyz)" ] + }, { + "name" : "enum_query_integer", + "in" : "query", + "description" : "Query parameter enum test (double)", + "required" : false, + "type" : "integer", + "format" : "int32" + }, { + "name" : "enum_query_double", + "in" : "formData", + "description" : "Query parameter enum test (double)", + "required" : false, + "type" : "number", + "format" : "double" + } ], + "responses" : { + "400" : { + "description" : "Invalid request" + }, + "404" : { + "description" : "Not found" + } + } + }, + "post" : { + "tags" : [ "fake" ], + "summary" : "Fake endpoint for testing various parameters\n假端點\n偽のエンドポイント\n가짜 엔드 포인트\n", + "description" : "Fake endpoint for testing various parameters\n假端點\n偽のエンドポイント\n가짜 엔드 포인트\n", + "operationId" : "testEndpointParameters", + "consumes" : [ "application/xml; charset=utf-8", "application/json; charset=utf-8" ], + "produces" : [ "application/xml; charset=utf-8", "application/json; charset=utf-8" ], + "parameters" : [ { + "name" : "integer", + "in" : "formData", + "description" : "None", + "required" : false, + "type" : "integer", + "maximum" : 100.0, + "minimum" : 10.0 + }, { + "name" : "int32", + "in" : "formData", + "description" : "None", + "required" : false, + "type" : "integer", + "maximum" : 200.0, + "minimum" : 20.0, + "format" : "int32" + }, { + "name" : "int64", + "in" : "formData", + "description" : "None", + "required" : false, + "type" : "integer", + "format" : "int64" + }, { + "name" : "number", + "in" : "formData", + "description" : "None", + "required" : true, + "type" : "number", + "maximum" : 543.2, + "minimum" : 32.1 + }, { + "name" : "float", + "in" : "formData", + "description" : "None", + "required" : false, + "type" : "number", + "maximum" : 987.6, + "format" : "float" + }, { + "name" : "double", + "in" : "formData", + "description" : "None", + "required" : true, + "type" : "number", + "maximum" : 123.4, + "minimum" : 67.8, + "format" : "double" + }, { + "name" : "string", + "in" : "formData", + "description" : "None", + "required" : false, + "type" : "string", + "pattern" : "/[a-z]/i" + }, { + "name" : "pattern_without_delimiter", + "in" : "formData", + "description" : "None", + "required" : true, + "type" : "string", + "pattern" : "^[A-Z].*" + }, { + "name" : "byte", + "in" : "formData", + "description" : "None", + "required" : true, + "type" : "string", + "format" : "byte" + }, { + "name" : "binary", + "in" : "formData", + "description" : "None", + "required" : false, + "type" : "string", + "format" : "binary" + }, { + "name" : "date", + "in" : "formData", + "description" : "None", + "required" : false, + "type" : "string", + "format" : "date" + }, { + "name" : "dateTime", + "in" : "formData", + "description" : "None", + "required" : false, + "type" : "string", + "format" : "date-time" + }, { + "name" : "password", + "in" : "formData", + "description" : "None", + "required" : false, + "type" : "string", + "maxLength" : 64, + "minLength" : 10, + "format" : "password" + }, { + "name" : "callback", + "in" : "formData", + "description" : "None", + "required" : false, + "type" : "string" + } ], + "responses" : { + "400" : { + "description" : "Invalid username supplied" + }, + "404" : { + "description" : "User not found" + } + }, + "security" : [ { + "http_basic_test" : [ ] + } ] + }, + "patch" : { + "tags" : [ "fake" ], + "summary" : "To test \"client\" model", + "description" : "To test \"client\" model", + "operationId" : "testClientModel", + "consumes" : [ "application/json" ], + "produces" : [ "application/json" ], + "parameters" : [ { + "in" : "body", + "name" : "body", + "description" : "client model", + "required" : true, + "schema" : { + "$ref" : "#/definitions/Client" + } + } ], + "responses" : { + "200" : { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Client" + } + } + } + } } }, "securityDefinitions" : { @@ -542,10 +882,13 @@ "authorizationUrl" : "http://petstore.swagger.io/api/oauth/dialog", "flow" : "implicit", "scopes" : { - "write_pets" : "modify pets in your account", - "read_pets" : "read your pets" + "write:pets" : "modify pets in your account", + "read:pets" : "read your pets" } }, + "http_basic_test" : { + "type" : "basic" + }, "api_key" : { "type" : "apiKey", "name" : "api_key", @@ -553,13 +896,62 @@ } }, "definitions" : { - "User" : { + "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", + "x-is-unique" : true + }, "username" : { "type" : "string" }, @@ -583,51 +975,9 @@ "format" : "int32", "description" : "User Status" } - } - }, - "Category" : { - "type" : "object", - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "name" : { - "type" : "string" - } - } - }, - "Pet" : { - "type" : "object", - "required" : [ "name", "photoUrls" ], - "properties" : { - "id" : { - "type" : "integer", - "format" : "int64" - }, - "category" : { - "$ref" : "#/definitions/Category" - }, - "name" : { - "type" : "string", - "example" : "doggie" - }, - "photoUrls" : { - "type" : "array", - "items" : { - "type" : "string" - } - }, - "tags" : { - "type" : "array", - "items" : { - "$ref" : "#/definitions/Tag" - } - }, - "status" : { - "type" : "string", - "description" : "pet status in the store" - } + }, + "xml" : { + "name" : "User" } }, "Tag" : { @@ -640,35 +990,493 @@ "name" : { "type" : "string" } + }, + "xml" : { + "name" : "Tag" } }, - "Order" : { + "Pet" : { "type" : "object", + "required" : [ "name", "photoUrls" ], "properties" : { "id" : { "type" : "integer", - "format" : "int64" + "format" : "int64", + "x-is-unique" : true }, - "petId" : { - "type" : "integer", - "format" : "int64" + "category" : { + "$ref" : "#/definitions/Category" }, - "quantity" : { - "type" : "integer", - "format" : "int32" - }, - "shipDate" : { + "name" : { "type" : "string", - "format" : "date-time" + "example" : "doggie" + }, + "photoUrls" : { + "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + }, + "items" : { + "type" : "string" + } + }, + "tags" : { + "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + }, + "items" : { + "$ref" : "#/definitions/Tag" + } }, "status" : { "type" : "string", - "description" : "Order Status" + "description" : "pet status in the store", + "enum" : [ "available", "pending", "sold" ] + } + }, + "xml" : { + "name" : "Pet" + } + }, + "ApiResponse" : { + "type" : "object", + "properties" : { + "code" : { + "type" : "integer", + "format" : "int32" }, - "complete" : { - "type" : "boolean" + "type" : { + "type" : "string" + }, + "message" : { + "type" : "string" } } + }, + "$special[model.name]" : { + "properties" : { + "$special[property.name]" : { + "type" : "integer", + "format" : "int64" + } + }, + "xml" : { + "name" : "$special[model.name]" + } + }, + "Return" : { + "properties" : { + "return" : { + "type" : "integer", + "format" : "int32" + } + }, + "description" : "Model for testing reserved words", + "xml" : { + "name" : "Return" + } + }, + "Name" : { + "required" : [ "name" ], + "properties" : { + "name" : { + "type" : "integer", + "format" : "int32" + }, + "snake_case" : { + "type" : "integer", + "format" : "int32", + "readOnly" : true + }, + "property" : { + "type" : "string" + }, + "123Number" : { + "type" : "integer", + "readOnly" : true + } + }, + "description" : "Model for testing model name same as property name", + "xml" : { + "name" : "Name" + } + }, + "200_response" : { + "properties" : { + "name" : { + "type" : "integer", + "format" : "int32" + }, + "class" : { + "type" : "string" + } + }, + "description" : "Model for testing model name starting with number", + "xml" : { + "name" : "Name" + } + }, + "ClassModel" : { + "properties" : { + "_class" : { + "type" : "string" + } + }, + "description" : "Model for testing model with \"_class\" property" + }, + "Dog" : { + "allOf" : [ { + "$ref" : "#/definitions/Animal" + }, { + "type" : "object", + "properties" : { + "breed" : { + "type" : "string" + } + } + } ] + }, + "Cat" : { + "allOf" : [ { + "$ref" : "#/definitions/Animal" + }, { + "type" : "object", + "properties" : { + "declawed" : { + "type" : "boolean" + } + } + } ] + }, + "Animal" : { + "type" : "object", + "required" : [ "className" ], + "discriminator" : "className", + "properties" : { + "className" : { + "type" : "string" + }, + "color" : { + "type" : "string", + "default" : "red" + } + } + }, + "AnimalFarm" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/Animal" + } + }, + "format_test" : { + "type" : "object", + "required" : [ "byte", "date", "number", "password" ], + "properties" : { + "integer" : { + "type" : "integer", + "minimum" : 10, + "maximum" : 100 + }, + "int32" : { + "type" : "integer", + "format" : "int32", + "minimum" : 20, + "maximum" : 200 + }, + "int64" : { + "type" : "integer", + "format" : "int64" + }, + "number" : { + "type" : "number", + "minimum" : 32.1, + "maximum" : 543.2 + }, + "float" : { + "type" : "number", + "format" : "float", + "minimum" : 54.3, + "maximum" : 987.6 + }, + "double" : { + "type" : "number", + "format" : "double", + "minimum" : 67.8, + "maximum" : 123.4 + }, + "string" : { + "type" : "string", + "pattern" : "/[a-z]/i" + }, + "byte" : { + "type" : "string", + "format" : "byte" + }, + "binary" : { + "type" : "string", + "format" : "binary" + }, + "date" : { + "type" : "string", + "format" : "date" + }, + "dateTime" : { + "type" : "string", + "format" : "date-time" + }, + "uuid" : { + "type" : "string", + "format" : "uuid" + }, + "password" : { + "type" : "string", + "format" : "password", + "minLength" : 10, + "maxLength" : 64 + } + } + }, + "EnumClass" : { + "type" : "string", + "enum" : [ "_abc", "-efg", "(xyz)" ], + "default" : "-efg" + }, + "Enum_Test" : { + "type" : "object", + "properties" : { + "enum_string" : { + "type" : "string", + "enum" : [ "UPPER", "lower", "" ] + }, + "enum_integer" : { + "type" : "integer", + "format" : "int32", + "enum" : [ 1, -1 ] + }, + "enum_number" : { + "type" : "number", + "format" : "double", + "enum" : [ 1.1, -1.2 ] + }, + "outerEnum" : { + "$ref" : "#/definitions/OuterEnum" + } + } + }, + "AdditionalPropertiesClass" : { + "type" : "object", + "properties" : { + "map_property" : { + "type" : "object", + "additionalProperties" : { + "type" : "string" + } + }, + "map_of_map_property" : { + "type" : "object", + "additionalProperties" : { + "type" : "object", + "additionalProperties" : { + "type" : "string" + } + } + } + } + }, + "MixedPropertiesAndAdditionalPropertiesClass" : { + "type" : "object", + "properties" : { + "uuid" : { + "type" : "string", + "format" : "uuid" + }, + "dateTime" : { + "type" : "string", + "format" : "date-time" + }, + "map" : { + "type" : "object", + "additionalProperties" : { + "$ref" : "#/definitions/Animal" + } + } + } + }, + "List" : { + "type" : "object", + "properties" : { + "123-list" : { + "type" : "string" + } + } + }, + "Client" : { + "type" : "object", + "properties" : { + "client" : { + "type" : "string" + } + } + }, + "ReadOnlyFirst" : { + "type" : "object", + "properties" : { + "bar" : { + "type" : "string", + "readOnly" : true + }, + "baz" : { + "type" : "string" + } + } + }, + "hasOnlyReadOnly" : { + "type" : "object", + "properties" : { + "bar" : { + "type" : "string", + "readOnly" : true + }, + "foo" : { + "type" : "string", + "readOnly" : true + } + } + }, + "Capitalization" : { + "type" : "object", + "properties" : { + "smallCamel" : { + "type" : "string" + }, + "CapitalCamel" : { + "type" : "string" + }, + "small_Snake" : { + "type" : "string" + }, + "Capital_Snake" : { + "type" : "string" + }, + "SCA_ETH_Flow_Points" : { + "type" : "string" + }, + "ATT_NAME" : { + "type" : "string", + "description" : "Name of the pet\n" + } + } + }, + "MapTest" : { + "type" : "object", + "properties" : { + "map_map_of_string" : { + "type" : "object", + "additionalProperties" : { + "type" : "object", + "additionalProperties" : { + "type" : "string" + } + } + }, + "map_of_enum_string" : { + "type" : "object", + "additionalProperties" : { + "type" : "string", + "enum" : [ "UPPER", "lower" ] + } + } + } + }, + "ArrayTest" : { + "type" : "object", + "properties" : { + "array_of_string" : { + "type" : "array", + "items" : { + "type" : "string" + } + }, + "array_array_of_integer" : { + "type" : "array", + "items" : { + "type" : "array", + "items" : { + "type" : "integer", + "format" : "int64" + } + } + }, + "array_array_of_model" : { + "type" : "array", + "items" : { + "type" : "array", + "items" : { + "$ref" : "#/definitions/ReadOnlyFirst" + } + } + } + } + }, + "NumberOnly" : { + "type" : "object", + "properties" : { + "JustNumber" : { + "type" : "number" + } + } + }, + "ArrayOfNumberOnly" : { + "type" : "object", + "properties" : { + "ArrayNumber" : { + "type" : "array", + "items" : { + "type" : "number" + } + } + } + }, + "ArrayOfArrayOfNumberOnly" : { + "type" : "object", + "properties" : { + "ArrayArrayNumber" : { + "type" : "array", + "items" : { + "type" : "array", + "items" : { + "type" : "number" + } + } + } + } + }, + "EnumArrays" : { + "type" : "object", + "properties" : { + "just_symbol" : { + "type" : "string", + "enum" : [ ">=", "$" ] + }, + "array_enum" : { + "type" : "array", + "items" : { + "type" : "string", + "enum" : [ "fish", "crab" ] + } + } + } + }, + "OuterEnum" : { + "type" : "string", + "enum" : [ "placed", "approved", "delivered" ] } + }, + "externalDocs" : { + "description" : "Find out more about Swagger", + "url" : "http://swagger.io" } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1/pom.xml b/samples/server/petstore/jaxrs/jersey1/pom.xml index c8dd08376a7..decbbd651d8 100644 --- a/samples/server/petstore/jaxrs/jersey1/pom.xml +++ b/samples/server/petstore/jaxrs/jersey1/pom.xml @@ -158,6 +158,13 @@ + + + javax.validation + validation-api + 1.1.0.Final + provided + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java index 64e951703be..ed62cb80017 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApi.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiParam; import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; +import javax.validation.constraints.*; import java.math.BigDecimal; import io.swagger.model.Client; @@ -38,7 +39,7 @@ public class FakeApi { @Consumes({ "application/json" }) @Produces({ "application/json" }) - @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Client.class) }) public Response testClientModel( @@ -80,7 +81,7 @@ public class FakeApi { @Consumes({ "*/*" }) @Produces({ "*/*" }) - @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "", response = void.class, tags={ "fake" }) + @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = void.class, tags={ "fake" }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Not found", response = void.class) }) @@ -91,7 +92,7 @@ public class FakeApi { @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString, @ApiParam(value = "Query parameter enum test (string array)", allowableValues=">, $") @QueryParam("enum_query_string_array") List enumQueryStringArray, @ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") BigDecimal enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") Integer enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)") @FormParam("enum_query_double") Double enumQueryDouble, @Context SecurityContext securityContext) throws NotFoundException { diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java index dd9726d60fc..0714ed3f02a 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/FakeApiService.java @@ -19,13 +19,13 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public abstract class FakeApiService { public abstract Response testClientModel(Client body,SecurityContext securityContext) throws NotFoundException; public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) throws NotFoundException; - public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,BigDecimal enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) + public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java index 076f6051db0..c7387bd20d7 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApi.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiParam; import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; +import javax.validation.constraints.*; import java.io.File; import io.swagger.model.ModelApiResponse; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java index df33e262880..62be64f485f 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/PetApiService.java @@ -19,16 +19,16 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public abstract class PetApiService { public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByStatus(List status,SecurityContext securityContext) + public abstract Response findPetsByStatus( @NotNull List status,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByTags(List tags,SecurityContext securityContext) + public abstract Response findPetsByTags( @NotNull List tags,SecurityContext securityContext) throws NotFoundException; public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java index 6742c34fe3e..ddfea454199 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApi.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiParam; import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; +import javax.validation.constraints.*; import java.util.Map; import io.swagger.model.Order; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java index c065b6c780c..b5a01e43f3b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/StoreApiService.java @@ -18,14 +18,14 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public abstract class StoreApiService { public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; - public abstract Response getOrderById(Long orderId,SecurityContext securityContext) + public abstract Response getOrderById( @Min(1) @Max(5)Long orderId,SecurityContext securityContext) throws NotFoundException; public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java index ffa97ab4649..f6b03fd77c1 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApi.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiParam; import io.swagger.jaxrs.*; import com.sun.jersey.multipart.FormDataParam; +import javax.validation.constraints.*; import java.util.List; import io.swagger.model.User; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java index a3bcd0da8fd..81d2eebcacf 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/api/UserApiService.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public abstract class UserApiService { public abstract Response createUser(User body,SecurityContext securityContext) @@ -31,7 +31,7 @@ public abstract class UserApiService { throws NotFoundException; public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; - public abstract Response loginUser(String username,String password,SecurityContext securityContext) + public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) throws NotFoundException; public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java index 55d1d0c5e45..d393ff25a39 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -21,6 +21,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.validation.constraints.*; /** * AdditionalPropertiesClass @@ -47,6 +48,7 @@ public class AdditionalPropertiesClass { * Get mapProperty * @return mapProperty **/ + @JsonProperty("map_property") @ApiModelProperty(value = "") public Map getMapProperty() { return mapProperty; @@ -70,6 +72,7 @@ public class AdditionalPropertiesClass { * Get mapOfMapProperty * @return mapOfMapProperty **/ + @JsonProperty("map_of_map_property") @ApiModelProperty(value = "") public Map> getMapOfMapProperty() { return mapOfMapProperty; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java index ae2b64e8c67..1898c8254e0 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Animal.java @@ -16,8 +16,11 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Animal @@ -39,7 +42,9 @@ public class Animal { * Get className * @return className **/ + @JsonProperty("className") @ApiModelProperty(required = true, value = "") + @NotNull public String getClassName() { return className; } @@ -57,6 +62,7 @@ public class Animal { * Get color * @return color **/ + @JsonProperty("color") @ApiModelProperty(value = "") public String getColor() { return color; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java index ed9baa7a24a..be5b217a5c0 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/AnimalFarm.java @@ -17,6 +17,7 @@ import java.util.Objects; import io.swagger.model.Animal; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * AnimalFarm diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 31be0acd0bd..31d552f59f6 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -21,6 +21,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * ArrayOfArrayOfNumberOnly @@ -44,6 +45,7 @@ public class ArrayOfArrayOfNumberOnly { * Get arrayArrayNumber * @return arrayArrayNumber **/ + @JsonProperty("ArrayArrayNumber") @ApiModelProperty(value = "") public List> getArrayArrayNumber() { return arrayArrayNumber; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java index 1923213cce9..79cb5ba97f9 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -21,6 +21,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * ArrayOfNumberOnly @@ -44,6 +45,7 @@ public class ArrayOfNumberOnly { * Get arrayNumber * @return arrayNumber **/ + @JsonProperty("ArrayNumber") @ApiModelProperty(value = "") public List getArrayNumber() { return arrayNumber; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java index ff6ed5937a5..6134222ae94 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ArrayTest.java @@ -21,6 +21,7 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * ArrayTest @@ -50,6 +51,7 @@ public class ArrayTest { * Get arrayOfString * @return arrayOfString **/ + @JsonProperty("array_of_string") @ApiModelProperty(value = "") public List getArrayOfString() { return arrayOfString; @@ -73,6 +75,7 @@ public class ArrayTest { * Get arrayArrayOfInteger * @return arrayArrayOfInteger **/ + @JsonProperty("array_array_of_integer") @ApiModelProperty(value = "") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; @@ -96,6 +99,7 @@ public class ArrayTest { * Get arrayArrayOfModel * @return arrayArrayOfModel **/ + @JsonProperty("array_array_of_model") @ApiModelProperty(value = "") public List> getArrayArrayOfModel() { return arrayArrayOfModel; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Capitalization.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..8e880223f76 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Capitalization.java @@ -0,0 +1,210 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @JsonProperty("smallCamel") + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @JsonProperty("CapitalCamel") + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @JsonProperty("small_Snake") + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @JsonProperty("Capital_Snake") + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @JsonProperty("SCA_ETH_Flow_Points") + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @JsonProperty("ATT_NAME") + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java index 7fbae697738..80b35d13374 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Cat.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Animal; +import javax.validation.constraints.*; /** * Cat @@ -37,6 +38,7 @@ public class Cat extends Animal { * Get declawed * @return declawed **/ + @JsonProperty("declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { return declawed; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java index 62a809814b5..4251da675d1 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Category.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Category @@ -39,6 +40,7 @@ public class Category { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -57,6 +59,7 @@ public class Category { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(value = "") public String getName() { return name; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..81a9cac1a9a --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ClassModel.java @@ -0,0 +1,91 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @JsonProperty("_class") + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java index ad56b48eeb9..e5d0a0ef8d0 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Client.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Client @@ -36,6 +37,7 @@ public class Client { * Get client * @return client **/ + @JsonProperty("client") @ApiModelProperty(value = "") public String getClient() { return client; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java index ca6dc1c3af7..3a70bcc8a23 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Dog.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Animal; +import javax.validation.constraints.*; /** * Dog @@ -37,6 +38,7 @@ public class Dog extends Animal { * Get breed * @return breed **/ + @JsonProperty("breed") @ApiModelProperty(value = "") public String getBreed() { return breed; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java index 55feec29353..40ae1fc9121 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumArrays.java @@ -21,6 +21,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * EnumArrays @@ -104,6 +105,7 @@ public class EnumArrays { * Get justSymbol * @return justSymbol **/ + @JsonProperty("just_symbol") @ApiModelProperty(value = "") public JustSymbolEnum getJustSymbol() { return justSymbol; @@ -127,6 +129,7 @@ public class EnumArrays { * Get arrayEnum * @return arrayEnum **/ + @JsonProperty("array_enum") @ApiModelProperty(value = "") public List getArrayEnum() { return arrayEnum; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java index cc4b2108ee9..1a5899f15d0 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumClass.java @@ -15,6 +15,7 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java index e630d4b24da..abb5128d612 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/EnumTest.java @@ -19,6 +19,8 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; +import javax.validation.constraints.*; /** * EnumTest @@ -31,7 +33,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; @@ -127,6 +131,9 @@ public class EnumTest { @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -136,6 +143,7 @@ public class EnumTest { * Get enumString * @return enumString **/ + @JsonProperty("enum_string") @ApiModelProperty(value = "") public EnumStringEnum getEnumString() { return enumString; @@ -154,6 +162,7 @@ public class EnumTest { * Get enumInteger * @return enumInteger **/ + @JsonProperty("enum_integer") @ApiModelProperty(value = "") public EnumIntegerEnum getEnumInteger() { return enumInteger; @@ -172,6 +181,7 @@ public class EnumTest { * Get enumNumber * @return enumNumber **/ + @JsonProperty("enum_number") @ApiModelProperty(value = "") public EnumNumberEnum getEnumNumber() { return enumNumber; @@ -181,6 +191,25 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @JsonProperty("outerEnum") + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -193,12 +222,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @@ -210,6 +240,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java index 203c4a105d8..eaba5daefe7 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/FormatTest.java @@ -20,6 +20,8 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.Date; +import java.util.UUID; +import javax.validation.constraints.*; /** * FormatTest @@ -60,7 +62,7 @@ public class FormatTest { private Date dateTime = null; @JsonProperty("uuid") - private String uuid = null; + private UUID uuid = null; @JsonProperty("password") private String password = null; @@ -72,11 +74,14 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ + @JsonProperty("integer") @ApiModelProperty(value = "") + @Min(10) + @Max(100) public Integer getInteger() { return integer; } @@ -92,11 +97,14 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ + @JsonProperty("int32") @ApiModelProperty(value = "") + @Min(20) + @Max(200) public Integer getInt32() { return int32; } @@ -114,6 +122,7 @@ public class FormatTest { * Get int64 * @return int64 **/ + @JsonProperty("int64") @ApiModelProperty(value = "") public Long getInt64() { return int64; @@ -134,7 +143,11 @@ public class FormatTest { * maximum: 543.2 * @return number **/ + @JsonProperty("number") @ApiModelProperty(required = true, value = "") + @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -154,7 +167,10 @@ public class FormatTest { * maximum: 987.6 * @return _float **/ + @JsonProperty("float") @ApiModelProperty(value = "") + @DecimalMin("54.3") + @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -174,7 +190,10 @@ public class FormatTest { * maximum: 123.4 * @return _double **/ + @JsonProperty("double") @ApiModelProperty(value = "") + @DecimalMin("67.8") + @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -192,7 +211,9 @@ public class FormatTest { * Get string * @return string **/ + @JsonProperty("string") @ApiModelProperty(value = "") + @Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -210,7 +231,9 @@ public class FormatTest { * Get _byte * @return _byte **/ + @JsonProperty("byte") @ApiModelProperty(required = true, value = "") + @NotNull public byte[] getByte() { return _byte; } @@ -228,6 +251,7 @@ public class FormatTest { * Get binary * @return binary **/ + @JsonProperty("binary") @ApiModelProperty(value = "") public byte[] getBinary() { return binary; @@ -246,7 +270,9 @@ public class FormatTest { * Get date * @return date **/ + @JsonProperty("date") @ApiModelProperty(required = true, value = "") + @NotNull public Date getDate() { return date; } @@ -264,6 +290,7 @@ public class FormatTest { * Get dateTime * @return dateTime **/ + @JsonProperty("dateTime") @ApiModelProperty(value = "") public Date getDateTime() { return dateTime; @@ -273,7 +300,7 @@ public class FormatTest { this.dateTime = dateTime; } - public FormatTest uuid(String uuid) { + public FormatTest uuid(UUID uuid) { this.uuid = uuid; return this; } @@ -282,12 +309,13 @@ public class FormatTest { * Get uuid * @return uuid **/ + @JsonProperty("uuid") @ApiModelProperty(value = "") - public String getUuid() { + public UUID getUuid() { return uuid; } - public void setUuid(String uuid) { + public void setUuid(UUID uuid) { this.uuid = uuid; } @@ -300,7 +328,10 @@ public class FormatTest { * Get password * @return password **/ + @JsonProperty("password") @ApiModelProperty(required = true, value = "") + @NotNull + @Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java index 73611bc43e0..ad387b8d1ef 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * HasOnlyReadOnly @@ -34,6 +35,7 @@ public class HasOnlyReadOnly { * Get bar * @return bar **/ + @JsonProperty("bar") @ApiModelProperty(value = "") public String getBar() { return bar; @@ -43,6 +45,7 @@ public class HasOnlyReadOnly { * Get foo * @return foo **/ + @JsonProperty("foo") @ApiModelProperty(value = "") public String getFoo() { return foo; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java index 58037229c3e..8dd41c15575 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MapTest.java @@ -22,6 +22,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.validation.constraints.*; /** * MapTest @@ -79,6 +80,7 @@ public class MapTest { * Get mapMapOfString * @return mapMapOfString **/ + @JsonProperty("map_map_of_string") @ApiModelProperty(value = "") public Map> getMapMapOfString() { return mapMapOfString; @@ -102,6 +104,7 @@ public class MapTest { * Get mapOfEnumString * @return mapOfEnumString **/ + @JsonProperty("map_of_enum_string") @ApiModelProperty(value = "") public Map getMapOfEnumString() { return mapOfEnumString; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index d9c75346f4d..16c430d3242 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -23,6 +23,8 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.UUID; +import javax.validation.constraints.*; /** * MixedPropertiesAndAdditionalPropertiesClass @@ -30,7 +32,7 @@ import java.util.Map; public class MixedPropertiesAndAdditionalPropertiesClass { @JsonProperty("uuid") - private String uuid = null; + private UUID uuid = null; @JsonProperty("dateTime") private Date dateTime = null; @@ -38,7 +40,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @JsonProperty("map") private Map map = new HashMap(); - public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { this.uuid = uuid; return this; } @@ -47,12 +49,13 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get uuid * @return uuid **/ + @JsonProperty("uuid") @ApiModelProperty(value = "") - public String getUuid() { + public UUID getUuid() { return uuid; } - public void setUuid(String uuid) { + public void setUuid(UUID uuid) { this.uuid = uuid; } @@ -65,6 +68,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get dateTime * @return dateTime **/ + @JsonProperty("dateTime") @ApiModelProperty(value = "") public Date getDateTime() { return dateTime; @@ -88,6 +92,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get map * @return map **/ + @JsonProperty("map") @ApiModelProperty(value = "") public Map getMap() { return map; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java index 78c6e9c7e93..ecab5e15c3c 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Model200Response.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Model for testing model name starting with number @@ -40,6 +41,7 @@ public class Model200Response { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(value = "") public Integer getName() { return name; @@ -58,6 +60,7 @@ public class Model200Response { * Get propertyClass * @return propertyClass **/ + @JsonProperty("class") @ApiModelProperty(value = "") public String getPropertyClass() { return propertyClass; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java index c80ea613b76..e4e80f26be6 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * ModelApiResponse @@ -42,6 +43,7 @@ public class ModelApiResponse { * Get code * @return code **/ + @JsonProperty("code") @ApiModelProperty(value = "") public Integer getCode() { return code; @@ -60,6 +62,7 @@ public class ModelApiResponse { * Get type * @return type **/ + @JsonProperty("type") @ApiModelProperty(value = "") public String getType() { return type; @@ -78,6 +81,7 @@ public class ModelApiResponse { * Get message * @return message **/ + @JsonProperty("message") @ApiModelProperty(value = "") public String getMessage() { return message; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java index 7907a3fd186..a3420db6ed5 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ModelReturn.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Model for testing reserved words @@ -37,6 +38,7 @@ public class ModelReturn { * Get _return * @return _return **/ + @JsonProperty("return") @ApiModelProperty(value = "") public Integer getReturn() { return _return; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java index b9ffac6e40d..c48051e1b8e 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Name.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Model for testing model name same as property name @@ -46,7 +47,9 @@ public class Name { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(required = true, value = "") + @NotNull public Integer getName() { return name; } @@ -59,6 +62,7 @@ public class Name { * Get snakeCase * @return snakeCase **/ + @JsonProperty("snake_case") @ApiModelProperty(value = "") public Integer getSnakeCase() { return snakeCase; @@ -73,6 +77,7 @@ public class Name { * Get property * @return property **/ + @JsonProperty("property") @ApiModelProperty(value = "") public String getProperty() { return property; @@ -86,6 +91,7 @@ public class Name { * Get _123Number * @return _123Number **/ + @JsonProperty("123Number") @ApiModelProperty(value = "") public Integer get123Number() { return _123Number; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java index a3333adbce0..3cf4872ff5b 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/NumberOnly.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; +import javax.validation.constraints.*; /** * NumberOnly @@ -37,6 +38,7 @@ public class NumberOnly { * Get justNumber * @return justNumber **/ + @JsonProperty("JustNumber") @ApiModelProperty(value = "") public BigDecimal getJustNumber() { return justNumber; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java index 11e8c7fd70c..c3acd75afb5 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Order.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; +import javax.validation.constraints.*; /** * Order @@ -86,6 +87,7 @@ public class Order { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -104,6 +106,7 @@ public class Order { * Get petId * @return petId **/ + @JsonProperty("petId") @ApiModelProperty(value = "") public Long getPetId() { return petId; @@ -122,6 +125,7 @@ public class Order { * Get quantity * @return quantity **/ + @JsonProperty("quantity") @ApiModelProperty(value = "") public Integer getQuantity() { return quantity; @@ -140,6 +144,7 @@ public class Order { * Get shipDate * @return shipDate **/ + @JsonProperty("shipDate") @ApiModelProperty(value = "") public Date getShipDate() { return shipDate; @@ -158,6 +163,7 @@ public class Order { * Order Status * @return status **/ + @JsonProperty("status") @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { return status; @@ -176,6 +182,7 @@ public class Order { * Get complete * @return complete **/ + @JsonProperty("complete") @ApiModelProperty(value = "") public Boolean getComplete() { return complete; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..6740674b07c --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,54 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java index e7e94cc89a8..2b1c91b3d02 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Pet.java @@ -23,6 +23,7 @@ import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * Pet @@ -89,6 +90,7 @@ public class Pet { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -107,6 +109,7 @@ public class Pet { * Get category * @return category **/ + @JsonProperty("category") @ApiModelProperty(value = "") public Category getCategory() { return category; @@ -125,7 +128,9 @@ public class Pet { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull public String getName() { return name; } @@ -148,7 +153,9 @@ public class Pet { * Get photoUrls * @return photoUrls **/ + @JsonProperty("photoUrls") @ApiModelProperty(required = true, value = "") + @NotNull public List getPhotoUrls() { return photoUrls; } @@ -171,6 +178,7 @@ public class Pet { * Get tags * @return tags **/ + @JsonProperty("tags") @ApiModelProperty(value = "") public List getTags() { return tags; @@ -189,6 +197,7 @@ public class Pet { * pet status in the store * @return status **/ + @JsonProperty("status") @ApiModelProperty(value = "pet status in the store") public StatusEnum getStatus() { return status; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java index 8ce60288125..1adefcf3fa0 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * ReadOnlyFirst @@ -34,6 +35,7 @@ public class ReadOnlyFirst { * Get bar * @return bar **/ + @JsonProperty("bar") @ApiModelProperty(value = "") public String getBar() { return bar; @@ -48,6 +50,7 @@ public class ReadOnlyFirst { * Get baz * @return baz **/ + @JsonProperty("baz") @ApiModelProperty(value = "") public String getBaz() { return baz; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java index a32ef45986a..48cbf2ace1c 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/SpecialModelName.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * SpecialModelName @@ -36,6 +37,7 @@ public class SpecialModelName { * Get specialPropertyName * @return specialPropertyName **/ + @JsonProperty("$special[property.name]") @ApiModelProperty(value = "") public Long getSpecialPropertyName() { return specialPropertyName; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java index 4d1d23d8b92..84b113fb924 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/Tag.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Tag @@ -39,6 +40,7 @@ public class Tag { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -57,6 +59,7 @@ public class Tag { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(value = "") public String getName() { return name; diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java index 779377d4578..493297f101f 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/io/swagger/model/User.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * User @@ -57,6 +58,7 @@ public class User { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -75,6 +77,7 @@ public class User { * Get username * @return username **/ + @JsonProperty("username") @ApiModelProperty(value = "") public String getUsername() { return username; @@ -93,6 +96,7 @@ public class User { * Get firstName * @return firstName **/ + @JsonProperty("firstName") @ApiModelProperty(value = "") public String getFirstName() { return firstName; @@ -111,6 +115,7 @@ public class User { * Get lastName * @return lastName **/ + @JsonProperty("lastName") @ApiModelProperty(value = "") public String getLastName() { return lastName; @@ -129,6 +134,7 @@ public class User { * Get email * @return email **/ + @JsonProperty("email") @ApiModelProperty(value = "") public String getEmail() { return email; @@ -147,6 +153,7 @@ public class User { * Get password * @return password **/ + @JsonProperty("password") @ApiModelProperty(value = "") public String getPassword() { return password; @@ -165,6 +172,7 @@ public class User { * Get phone * @return phone **/ + @JsonProperty("phone") @ApiModelProperty(value = "") public String getPhone() { return phone; @@ -183,6 +191,7 @@ public class User { * User Status * @return userStatus **/ + @JsonProperty("userStatus") @ApiModelProperty(value = "User Status") public Integer getUserStatus() { return userStatus; diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java index a5d85fa89e8..1ef64321d6a 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -19,7 +19,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public class FakeApiServiceImpl extends FakeApiService { @Override @@ -35,7 +35,7 @@ public class FakeApiServiceImpl extends FakeApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) + public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index d775f8dc4a0..4ca20a47727 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -19,7 +19,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public class PetApiServiceImpl extends PetApiService { @Override @@ -35,13 +35,13 @@ public class PetApiServiceImpl extends PetApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response findPetsByStatus(List status, SecurityContext securityContext) + public Response findPetsByStatus( @NotNull List status, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response findPetsByTags(List tags, SecurityContext securityContext) + public Response findPetsByTags( @NotNull List tags, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 2b00aa8fad0..96194fb16b8 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public class StoreApiServiceImpl extends StoreApiService { @Override @@ -34,7 +34,7 @@ public class StoreApiServiceImpl extends StoreApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response getOrderById(Long orderId, SecurityContext securityContext) + public Response getOrderById( @Min(1) @Max(5)Long orderId, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index f8cf78613d9..ca562ed389c 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey1/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -18,7 +18,7 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public class UserApiServiceImpl extends UserApiService { @Override @@ -52,7 +52,7 @@ public class UserApiServiceImpl extends UserApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response loginUser(String username, String password, SecurityContext securityContext) + public Response loginUser( @NotNull String username, @NotNull String password, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs/jersey2/pom.xml b/samples/server/petstore/jaxrs/jersey2/pom.xml index 5f3f512a42d..18310a4ec6a 100644 --- a/samples/server/petstore/jaxrs/jersey2/pom.xml +++ b/samples/server/petstore/jaxrs/jersey2/pom.xml @@ -5,6 +5,15 @@ jar swagger-jaxrs-server 1.0.0 + + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + src/main/java @@ -131,6 +140,14 @@ 2.2 + + + + javax.validation + validation-api + 1.1.0.Final + provided + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java index a1e2db5e58a..16854fbaf4d 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApi.java @@ -23,6 +23,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/fake") @@ -36,7 +37,7 @@ public class FakeApi { @Consumes({ "application/json" }) @Produces({ "application/json" }) - @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "", response = Client.class, tags={ "fake", }) + @io.swagger.annotations.ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Client.class) }) public Response testClientModel(@ApiParam(value = "client model" ,required=true) Client body @@ -77,7 +78,7 @@ public class FakeApi { @Consumes({ "*/*" }) @Produces({ "*/*" }) - @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "", response = void.class, tags={ "fake", }) + @io.swagger.annotations.ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = void.class, tags={ "fake", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = void.class), @@ -88,7 +89,7 @@ public class FakeApi { ,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString ,@ApiParam(value = "Query parameter enum test (string array)", allowableValues=">, $") @QueryParam("enum_query_string_array") List enumQueryStringArray ,@ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString -,@ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") BigDecimal enumQueryInteger +,@ApiParam(value = "Query parameter enum test (double)") @QueryParam("enum_query_integer") Integer enumQueryInteger ,@ApiParam(value = "Query parameter enum test (double)") @FormParam("enum_query_double") Double enumQueryDouble ,@Context SecurityContext securityContext) throws NotFoundException { diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java index 0109f9edc57..aaff35dbdd9 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/FakeApiService.java @@ -16,10 +16,10 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public abstract class FakeApiService { public abstract Response testClientModel(Client body,SecurityContext securityContext) throws NotFoundException; public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,byte[] binary,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) throws NotFoundException; - public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,BigDecimal enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) throws NotFoundException; + public abstract Response testEnumParameters(List enumFormStringArray,String enumFormString,List enumHeaderStringArray,String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger,Double enumQueryDouble,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java index 7f6905ce223..6e5089e40d5 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApi.java @@ -23,6 +23,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/pet") diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java index 76026a64c8b..31566759c5f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/PetApiService.java @@ -16,13 +16,13 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public abstract class PetApiService { public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; public abstract Response deletePet(Long petId,String apiKey,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByStatus(List status,SecurityContext securityContext) throws NotFoundException; - public abstract Response findPetsByTags(List tags,SecurityContext securityContext) throws NotFoundException; + public abstract Response findPetsByStatus( @NotNull List status,SecurityContext securityContext) throws NotFoundException; + public abstract Response findPetsByTags( @NotNull List tags,SecurityContext securityContext) throws NotFoundException; public abstract Response getPetById(Long petId,SecurityContext securityContext) throws NotFoundException; public abstract Response updatePet(Pet body,SecurityContext securityContext) throws NotFoundException; public abstract Response updatePetWithForm(Long petId,String name,String status,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java index 6c4c40b97cc..894b3f33898 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApi.java @@ -22,6 +22,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/store") diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java index 5ef766d6aa7..911c70033c4 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/StoreApiService.java @@ -15,11 +15,11 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public abstract class StoreApiService { public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; public abstract Response getInventory(SecurityContext securityContext) throws NotFoundException; - public abstract Response getOrderById(Long orderId,SecurityContext securityContext) throws NotFoundException; + public abstract Response getOrderById( @Min(1) @Max(5)Long orderId,SecurityContext securityContext) throws NotFoundException; public abstract Response placeOrder(Order body,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java index 50b17bcd568..50d97a56825 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApi.java @@ -22,6 +22,7 @@ import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.*; +import javax.validation.constraints.*; @Path("/user") diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java index e0e65657bed..8bbee3394d5 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/api/UserApiService.java @@ -15,7 +15,7 @@ import java.io.InputStream; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public abstract class UserApiService { public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; @@ -23,7 +23,7 @@ public abstract class UserApiService { public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; - public abstract Response loginUser(String username,String password,SecurityContext securityContext) throws NotFoundException; + public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) throws NotFoundException; public abstract Response logoutUser(SecurityContext securityContext) throws NotFoundException; public abstract Response updateUser(String username,User body,SecurityContext securityContext) throws NotFoundException; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java index 55d1d0c5e45..d393ff25a39 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AdditionalPropertiesClass.java @@ -21,6 +21,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.validation.constraints.*; /** * AdditionalPropertiesClass @@ -47,6 +48,7 @@ public class AdditionalPropertiesClass { * Get mapProperty * @return mapProperty **/ + @JsonProperty("map_property") @ApiModelProperty(value = "") public Map getMapProperty() { return mapProperty; @@ -70,6 +72,7 @@ public class AdditionalPropertiesClass { * Get mapOfMapProperty * @return mapOfMapProperty **/ + @JsonProperty("map_of_map_property") @ApiModelProperty(value = "") public Map> getMapOfMapProperty() { return mapOfMapProperty; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java index ae2b64e8c67..1898c8254e0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Animal.java @@ -16,8 +16,11 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Animal @@ -39,7 +42,9 @@ public class Animal { * Get className * @return className **/ + @JsonProperty("className") @ApiModelProperty(required = true, value = "") + @NotNull public String getClassName() { return className; } @@ -57,6 +62,7 @@ public class Animal { * Get color * @return color **/ + @JsonProperty("color") @ApiModelProperty(value = "") public String getColor() { return color; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java index ed9baa7a24a..be5b217a5c0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/AnimalFarm.java @@ -17,6 +17,7 @@ import java.util.Objects; import io.swagger.model.Animal; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * AnimalFarm diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 31be0acd0bd..31d552f59f6 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -21,6 +21,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * ArrayOfArrayOfNumberOnly @@ -44,6 +45,7 @@ public class ArrayOfArrayOfNumberOnly { * Get arrayArrayNumber * @return arrayArrayNumber **/ + @JsonProperty("ArrayArrayNumber") @ApiModelProperty(value = "") public List> getArrayArrayNumber() { return arrayArrayNumber; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java index 1923213cce9..79cb5ba97f9 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayOfNumberOnly.java @@ -21,6 +21,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * ArrayOfNumberOnly @@ -44,6 +45,7 @@ public class ArrayOfNumberOnly { * Get arrayNumber * @return arrayNumber **/ + @JsonProperty("ArrayNumber") @ApiModelProperty(value = "") public List getArrayNumber() { return arrayNumber; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java index ff6ed5937a5..6134222ae94 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ArrayTest.java @@ -21,6 +21,7 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * ArrayTest @@ -50,6 +51,7 @@ public class ArrayTest { * Get arrayOfString * @return arrayOfString **/ + @JsonProperty("array_of_string") @ApiModelProperty(value = "") public List getArrayOfString() { return arrayOfString; @@ -73,6 +75,7 @@ public class ArrayTest { * Get arrayArrayOfInteger * @return arrayArrayOfInteger **/ + @JsonProperty("array_array_of_integer") @ApiModelProperty(value = "") public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; @@ -96,6 +99,7 @@ public class ArrayTest { * Get arrayArrayOfModel * @return arrayArrayOfModel **/ + @JsonProperty("array_array_of_model") @ApiModelProperty(value = "") public List> getArrayArrayOfModel() { return arrayArrayOfModel; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Capitalization.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..8e880223f76 --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Capitalization.java @@ -0,0 +1,210 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @JsonProperty("smallCamel") + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @JsonProperty("CapitalCamel") + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @JsonProperty("small_Snake") + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @JsonProperty("Capital_Snake") + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @JsonProperty("SCA_ETH_Flow_Points") + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @JsonProperty("ATT_NAME") + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java index 7fbae697738..80b35d13374 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Cat.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Animal; +import javax.validation.constraints.*; /** * Cat @@ -37,6 +38,7 @@ public class Cat extends Animal { * Get declawed * @return declawed **/ + @JsonProperty("declawed") @ApiModelProperty(value = "") public Boolean getDeclawed() { return declawed; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java index 62a809814b5..4251da675d1 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Category.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Category @@ -39,6 +40,7 @@ public class Category { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -57,6 +59,7 @@ public class Category { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(value = "") public String getName() { return name; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..81a9cac1a9a --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ClassModel.java @@ -0,0 +1,91 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @JsonProperty("_class") + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java index ad56b48eeb9..e5d0a0ef8d0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Client.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Client @@ -36,6 +37,7 @@ public class Client { * Get client * @return client **/ + @JsonProperty("client") @ApiModelProperty(value = "") public String getClient() { return client; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java index ca6dc1c3af7..3a70bcc8a23 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Dog.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Animal; +import javax.validation.constraints.*; /** * Dog @@ -37,6 +38,7 @@ public class Dog extends Animal { * Get breed * @return breed **/ + @JsonProperty("breed") @ApiModelProperty(value = "") public String getBreed() { return breed; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java index 55feec29353..40ae1fc9121 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumArrays.java @@ -21,6 +21,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * EnumArrays @@ -104,6 +105,7 @@ public class EnumArrays { * Get justSymbol * @return justSymbol **/ + @JsonProperty("just_symbol") @ApiModelProperty(value = "") public JustSymbolEnum getJustSymbol() { return justSymbol; @@ -127,6 +129,7 @@ public class EnumArrays { * Get arrayEnum * @return arrayEnum **/ + @JsonProperty("array_enum") @ApiModelProperty(value = "") public List getArrayEnum() { return arrayEnum; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java index cc4b2108ee9..1a5899f15d0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumClass.java @@ -15,6 +15,7 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java index e630d4b24da..abb5128d612 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/EnumTest.java @@ -19,6 +19,8 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; +import javax.validation.constraints.*; /** * EnumTest @@ -31,7 +33,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; @@ -127,6 +131,9 @@ public class EnumTest { @JsonProperty("enum_number") private EnumNumberEnum enumNumber = null; + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + public EnumTest enumString(EnumStringEnum enumString) { this.enumString = enumString; return this; @@ -136,6 +143,7 @@ public class EnumTest { * Get enumString * @return enumString **/ + @JsonProperty("enum_string") @ApiModelProperty(value = "") public EnumStringEnum getEnumString() { return enumString; @@ -154,6 +162,7 @@ public class EnumTest { * Get enumInteger * @return enumInteger **/ + @JsonProperty("enum_integer") @ApiModelProperty(value = "") public EnumIntegerEnum getEnumInteger() { return enumInteger; @@ -172,6 +181,7 @@ public class EnumTest { * Get enumNumber * @return enumNumber **/ + @JsonProperty("enum_number") @ApiModelProperty(value = "") public EnumNumberEnum getEnumNumber() { return enumNumber; @@ -181,6 +191,25 @@ public class EnumTest { this.enumNumber = enumNumber; } + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @JsonProperty("outerEnum") + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + @Override public boolean equals(java.lang.Object o) { @@ -193,12 +222,13 @@ public class EnumTest { EnumTest enumTest = (EnumTest) o; return Objects.equals(this.enumString, enumTest.enumString) && Objects.equals(this.enumInteger, enumTest.enumInteger) && - Objects.equals(this.enumNumber, enumTest.enumNumber); + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override public int hashCode() { - return Objects.hash(enumString, enumInteger, enumNumber); + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); } @@ -210,6 +240,7 @@ public class EnumTest { sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java index 203c4a105d8..eaba5daefe7 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/FormatTest.java @@ -20,6 +20,8 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.Date; +import java.util.UUID; +import javax.validation.constraints.*; /** * FormatTest @@ -60,7 +62,7 @@ public class FormatTest { private Date dateTime = null; @JsonProperty("uuid") - private String uuid = null; + private UUID uuid = null; @JsonProperty("password") private String password = null; @@ -72,11 +74,14 @@ public class FormatTest { /** * Get integer - * minimum: 10.0 - * maximum: 100.0 + * minimum: 10 + * maximum: 100 * @return integer **/ + @JsonProperty("integer") @ApiModelProperty(value = "") + @Min(10) + @Max(100) public Integer getInteger() { return integer; } @@ -92,11 +97,14 @@ public class FormatTest { /** * Get int32 - * minimum: 20.0 - * maximum: 200.0 + * minimum: 20 + * maximum: 200 * @return int32 **/ + @JsonProperty("int32") @ApiModelProperty(value = "") + @Min(20) + @Max(200) public Integer getInt32() { return int32; } @@ -114,6 +122,7 @@ public class FormatTest { * Get int64 * @return int64 **/ + @JsonProperty("int64") @ApiModelProperty(value = "") public Long getInt64() { return int64; @@ -134,7 +143,11 @@ public class FormatTest { * maximum: 543.2 * @return number **/ + @JsonProperty("number") @ApiModelProperty(required = true, value = "") + @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -154,7 +167,10 @@ public class FormatTest { * maximum: 987.6 * @return _float **/ + @JsonProperty("float") @ApiModelProperty(value = "") + @DecimalMin("54.3") + @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -174,7 +190,10 @@ public class FormatTest { * maximum: 123.4 * @return _double **/ + @JsonProperty("double") @ApiModelProperty(value = "") + @DecimalMin("67.8") + @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -192,7 +211,9 @@ public class FormatTest { * Get string * @return string **/ + @JsonProperty("string") @ApiModelProperty(value = "") + @Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -210,7 +231,9 @@ public class FormatTest { * Get _byte * @return _byte **/ + @JsonProperty("byte") @ApiModelProperty(required = true, value = "") + @NotNull public byte[] getByte() { return _byte; } @@ -228,6 +251,7 @@ public class FormatTest { * Get binary * @return binary **/ + @JsonProperty("binary") @ApiModelProperty(value = "") public byte[] getBinary() { return binary; @@ -246,7 +270,9 @@ public class FormatTest { * Get date * @return date **/ + @JsonProperty("date") @ApiModelProperty(required = true, value = "") + @NotNull public Date getDate() { return date; } @@ -264,6 +290,7 @@ public class FormatTest { * Get dateTime * @return dateTime **/ + @JsonProperty("dateTime") @ApiModelProperty(value = "") public Date getDateTime() { return dateTime; @@ -273,7 +300,7 @@ public class FormatTest { this.dateTime = dateTime; } - public FormatTest uuid(String uuid) { + public FormatTest uuid(UUID uuid) { this.uuid = uuid; return this; } @@ -282,12 +309,13 @@ public class FormatTest { * Get uuid * @return uuid **/ + @JsonProperty("uuid") @ApiModelProperty(value = "") - public String getUuid() { + public UUID getUuid() { return uuid; } - public void setUuid(String uuid) { + public void setUuid(UUID uuid) { this.uuid = uuid; } @@ -300,7 +328,10 @@ public class FormatTest { * Get password * @return password **/ + @JsonProperty("password") @ApiModelProperty(required = true, value = "") + @NotNull + @Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java index 73611bc43e0..ad387b8d1ef 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/HasOnlyReadOnly.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * HasOnlyReadOnly @@ -34,6 +35,7 @@ public class HasOnlyReadOnly { * Get bar * @return bar **/ + @JsonProperty("bar") @ApiModelProperty(value = "") public String getBar() { return bar; @@ -43,6 +45,7 @@ public class HasOnlyReadOnly { * Get foo * @return foo **/ + @JsonProperty("foo") @ApiModelProperty(value = "") public String getFoo() { return foo; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java index 58037229c3e..8dd41c15575 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MapTest.java @@ -22,6 +22,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.validation.constraints.*; /** * MapTest @@ -79,6 +80,7 @@ public class MapTest { * Get mapMapOfString * @return mapMapOfString **/ + @JsonProperty("map_map_of_string") @ApiModelProperty(value = "") public Map> getMapMapOfString() { return mapMapOfString; @@ -102,6 +104,7 @@ public class MapTest { * Get mapOfEnumString * @return mapOfEnumString **/ + @JsonProperty("map_of_enum_string") @ApiModelProperty(value = "") public Map getMapOfEnumString() { return mapOfEnumString; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index d9c75346f4d..16c430d3242 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -23,6 +23,8 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.UUID; +import javax.validation.constraints.*; /** * MixedPropertiesAndAdditionalPropertiesClass @@ -30,7 +32,7 @@ import java.util.Map; public class MixedPropertiesAndAdditionalPropertiesClass { @JsonProperty("uuid") - private String uuid = null; + private UUID uuid = null; @JsonProperty("dateTime") private Date dateTime = null; @@ -38,7 +40,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @JsonProperty("map") private Map map = new HashMap(); - public MixedPropertiesAndAdditionalPropertiesClass uuid(String uuid) { + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { this.uuid = uuid; return this; } @@ -47,12 +49,13 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get uuid * @return uuid **/ + @JsonProperty("uuid") @ApiModelProperty(value = "") - public String getUuid() { + public UUID getUuid() { return uuid; } - public void setUuid(String uuid) { + public void setUuid(UUID uuid) { this.uuid = uuid; } @@ -65,6 +68,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get dateTime * @return dateTime **/ + @JsonProperty("dateTime") @ApiModelProperty(value = "") public Date getDateTime() { return dateTime; @@ -88,6 +92,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { * Get map * @return map **/ + @JsonProperty("map") @ApiModelProperty(value = "") public Map getMap() { return map; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java index 78c6e9c7e93..ecab5e15c3c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Model200Response.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Model for testing model name starting with number @@ -40,6 +41,7 @@ public class Model200Response { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(value = "") public Integer getName() { return name; @@ -58,6 +60,7 @@ public class Model200Response { * Get propertyClass * @return propertyClass **/ + @JsonProperty("class") @ApiModelProperty(value = "") public String getPropertyClass() { return propertyClass; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java index c80ea613b76..e4e80f26be6 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelApiResponse.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * ModelApiResponse @@ -42,6 +43,7 @@ public class ModelApiResponse { * Get code * @return code **/ + @JsonProperty("code") @ApiModelProperty(value = "") public Integer getCode() { return code; @@ -60,6 +62,7 @@ public class ModelApiResponse { * Get type * @return type **/ + @JsonProperty("type") @ApiModelProperty(value = "") public String getType() { return type; @@ -78,6 +81,7 @@ public class ModelApiResponse { * Get message * @return message **/ + @JsonProperty("message") @ApiModelProperty(value = "") public String getMessage() { return message; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java index 7907a3fd186..a3420db6ed5 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ModelReturn.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Model for testing reserved words @@ -37,6 +38,7 @@ public class ModelReturn { * Get _return * @return _return **/ + @JsonProperty("return") @ApiModelProperty(value = "") public Integer getReturn() { return _return; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java index b9ffac6e40d..c48051e1b8e 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Name.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Model for testing model name same as property name @@ -46,7 +47,9 @@ public class Name { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(required = true, value = "") + @NotNull public Integer getName() { return name; } @@ -59,6 +62,7 @@ public class Name { * Get snakeCase * @return snakeCase **/ + @JsonProperty("snake_case") @ApiModelProperty(value = "") public Integer getSnakeCase() { return snakeCase; @@ -73,6 +77,7 @@ public class Name { * Get property * @return property **/ + @JsonProperty("property") @ApiModelProperty(value = "") public String getProperty() { return property; @@ -86,6 +91,7 @@ public class Name { * Get _123Number * @return _123Number **/ + @JsonProperty("123Number") @ApiModelProperty(value = "") public Integer get123Number() { return _123Number; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java index a3333adbce0..3cf4872ff5b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/NumberOnly.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; +import javax.validation.constraints.*; /** * NumberOnly @@ -37,6 +38,7 @@ public class NumberOnly { * Get justNumber * @return justNumber **/ + @JsonProperty("JustNumber") @ApiModelProperty(value = "") public BigDecimal getJustNumber() { return justNumber; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java index 11e8c7fd70c..c3acd75afb5 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Order.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; +import javax.validation.constraints.*; /** * Order @@ -86,6 +87,7 @@ public class Order { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -104,6 +106,7 @@ public class Order { * Get petId * @return petId **/ + @JsonProperty("petId") @ApiModelProperty(value = "") public Long getPetId() { return petId; @@ -122,6 +125,7 @@ public class Order { * Get quantity * @return quantity **/ + @JsonProperty("quantity") @ApiModelProperty(value = "") public Integer getQuantity() { return quantity; @@ -140,6 +144,7 @@ public class Order { * Get shipDate * @return shipDate **/ + @JsonProperty("shipDate") @ApiModelProperty(value = "") public Date getShipDate() { return shipDate; @@ -158,6 +163,7 @@ public class Order { * Order Status * @return status **/ + @JsonProperty("status") @ApiModelProperty(value = "Order Status") public StatusEnum getStatus() { return status; @@ -176,6 +182,7 @@ public class Order { * Get complete * @return complete **/ + @JsonProperty("complete") @ApiModelProperty(value = "") public Boolean getComplete() { return complete; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..6740674b07c --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,54 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; + +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java index e7e94cc89a8..2b1c91b3d02 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Pet.java @@ -23,6 +23,7 @@ import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; +import javax.validation.constraints.*; /** * Pet @@ -89,6 +90,7 @@ public class Pet { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -107,6 +109,7 @@ public class Pet { * Get category * @return category **/ + @JsonProperty("category") @ApiModelProperty(value = "") public Category getCategory() { return category; @@ -125,7 +128,9 @@ public class Pet { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull public String getName() { return name; } @@ -148,7 +153,9 @@ public class Pet { * Get photoUrls * @return photoUrls **/ + @JsonProperty("photoUrls") @ApiModelProperty(required = true, value = "") + @NotNull public List getPhotoUrls() { return photoUrls; } @@ -171,6 +178,7 @@ public class Pet { * Get tags * @return tags **/ + @JsonProperty("tags") @ApiModelProperty(value = "") public List getTags() { return tags; @@ -189,6 +197,7 @@ public class Pet { * pet status in the store * @return status **/ + @JsonProperty("status") @ApiModelProperty(value = "pet status in the store") public StatusEnum getStatus() { return status; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java index 8ce60288125..1adefcf3fa0 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/ReadOnlyFirst.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * ReadOnlyFirst @@ -34,6 +35,7 @@ public class ReadOnlyFirst { * Get bar * @return bar **/ + @JsonProperty("bar") @ApiModelProperty(value = "") public String getBar() { return bar; @@ -48,6 +50,7 @@ public class ReadOnlyFirst { * Get baz * @return baz **/ + @JsonProperty("baz") @ApiModelProperty(value = "") public String getBaz() { return baz; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java index a32ef45986a..48cbf2ace1c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/SpecialModelName.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * SpecialModelName @@ -36,6 +37,7 @@ public class SpecialModelName { * Get specialPropertyName * @return specialPropertyName **/ + @JsonProperty("$special[property.name]") @ApiModelProperty(value = "") public Long getSpecialPropertyName() { return specialPropertyName; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java index 4d1d23d8b92..84b113fb924 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/Tag.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * Tag @@ -39,6 +40,7 @@ public class Tag { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -57,6 +59,7 @@ public class Tag { * Get name * @return name **/ + @JsonProperty("name") @ApiModelProperty(value = "") public String getName() { return name; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java index 779377d4578..493297f101f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/io/swagger/model/User.java @@ -18,6 +18,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; /** * User @@ -57,6 +58,7 @@ public class User { * Get id * @return id **/ + @JsonProperty("id") @ApiModelProperty(value = "") public Long getId() { return id; @@ -75,6 +77,7 @@ public class User { * Get username * @return username **/ + @JsonProperty("username") @ApiModelProperty(value = "") public String getUsername() { return username; @@ -93,6 +96,7 @@ public class User { * Get firstName * @return firstName **/ + @JsonProperty("firstName") @ApiModelProperty(value = "") public String getFirstName() { return firstName; @@ -111,6 +115,7 @@ public class User { * Get lastName * @return lastName **/ + @JsonProperty("lastName") @ApiModelProperty(value = "") public String getLastName() { return lastName; @@ -129,6 +134,7 @@ public class User { * Get email * @return email **/ + @JsonProperty("email") @ApiModelProperty(value = "") public String getEmail() { return email; @@ -147,6 +153,7 @@ public class User { * Get password * @return password **/ + @JsonProperty("password") @ApiModelProperty(value = "") public String getPassword() { return password; @@ -165,6 +172,7 @@ public class User { * Get phone * @return phone **/ + @JsonProperty("phone") @ApiModelProperty(value = "") public String getPhone() { return phone; @@ -183,6 +191,7 @@ public class User { * User Status * @return userStatus **/ + @JsonProperty("userStatus") @ApiModelProperty(value = "User Status") public Integer getUserStatus() { return userStatus; diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java index fffbd9435b1..11b046e7c94 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/FakeApiServiceImpl.java @@ -16,7 +16,7 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public class FakeApiServiceImpl extends FakeApiService { @Override @@ -30,7 +30,7 @@ public class FakeApiServiceImpl extends FakeApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, BigDecimal enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) throws NotFoundException { + public Response testEnumParameters(List enumFormStringArray, String enumFormString, List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java index 856243a387e..be3e7e167e7 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/PetApiServiceImpl.java @@ -16,7 +16,7 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public class PetApiServiceImpl extends PetApiService { @Override @@ -30,12 +30,12 @@ public class PetApiServiceImpl extends PetApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response findPetsByStatus(List status, SecurityContext securityContext) throws NotFoundException { + public Response findPetsByStatus( @NotNull List status, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response findPetsByTags(List tags, SecurityContext securityContext) throws NotFoundException { + public Response findPetsByTags( @NotNull List tags, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java index 85e14b0bbe5..f8fd4cec86b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/StoreApiServiceImpl.java @@ -15,7 +15,7 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public class StoreApiServiceImpl extends StoreApiService { @Override @@ -29,7 +29,7 @@ public class StoreApiServiceImpl extends StoreApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response getOrderById(Long orderId, SecurityContext securityContext) throws NotFoundException { + public Response getOrderById( @Min(1) @Max(5)Long orderId, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java index 0d59ad51c5a..5853e33168d 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/io/swagger/api/impl/UserApiServiceImpl.java @@ -15,7 +15,7 @@ import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; - +import javax.validation.constraints.*; public class UserApiServiceImpl extends UserApiService { @Override @@ -44,7 +44,7 @@ public class UserApiServiceImpl extends UserApiService { return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response loginUser(String username, String password, SecurityContext securityContext) throws NotFoundException { + public Response loginUser( @NotNull String username, @NotNull String password, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/test/java/io/swagger/model/CapitalizationTest.java b/samples/server/petstore/jaxrs/jersey2/src/test/java/io/swagger/model/CapitalizationTest.java new file mode 100644 index 00000000000..179b064248f --- /dev/null +++ b/samples/server/petstore/jaxrs/jersey2/src/test/java/io/swagger/model/CapitalizationTest.java @@ -0,0 +1,69 @@ +package io.swagger.model; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * Tests JSON representation of + */ +public class CapitalizationTest { + + private static final String SMALL_CAMEL = "smallCamel"; + private static final String SMALL_SNAKE = "small_Snake"; + private static final String CAPITAL_CAMEL = "CapitalCamel"; + private static final String CAPITAL_SNAKE = "Capital_Snake"; + + private static final String SCA_ETH_FLOW_POINTS = "SCA_ETH_Flow_Points"; + private static final String ATT_NAME = "ATT_NAME"; + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static final Set EXPECTED + = new HashSet<>(Arrays.asList(SMALL_CAMEL, + SMALL_SNAKE, + CAPITAL_CAMEL, + CAPITAL_SNAKE, + SCA_ETH_FLOW_POINTS, + ATT_NAME)); + + private Capitalization sut; + + + @Before + public void setUp() { + sut = new Capitalization(); + sut.smallCamel(SMALL_CAMEL); + sut.smallSnake(SMALL_SNAKE); + sut.capitalCamel(CAPITAL_CAMEL); + sut.capitalSnake(CAPITAL_SNAKE); + sut.setScAETHFlowPoints(SCA_ETH_FLOW_POINTS); + sut.setATTNAME(ATT_NAME); + } + + @Test + public void test() throws JsonProcessingException { + + JsonNode json = MAPPER.valueToTree(sut); + + Set fields = new HashSet<>(); + Iterator it = json.fieldNames(); + while (it.hasNext()) { + fields.add(it.next()); + } + + assertThat(fields, is(equalTo(EXPECTED))); + } + +} diff --git a/samples/server/petstore/nancyfx/IO.Swagger.sln b/samples/server/petstore/nancyfx/IO.Swagger.sln index 09301395de7..38fb0ef476a 100644 --- a/samples/server/petstore/nancyfx/IO.Swagger.sln +++ b/samples/server/petstore/nancyfx/IO.Swagger.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{3B55ED13-A471-44B1-A8D5-C158723C0A0C}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IO.Swagger", "src\IO.Swagger\IO.Swagger.csproj", "{9A5C2190-C960-4808-93CB-8721C1022F9B}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -10,10 +10,10 @@ Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution -{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU -{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Debug|Any CPU.Build.0 = Debug|Any CPU -{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Release|Any CPU.ActiveCfg = Release|Any CPU -{3B55ED13-A471-44B1-A8D5-C158723C0A0C}.Release|Any CPU.Build.0 = Release|Any CPU +{9A5C2190-C960-4808-93CB-8721C1022F9B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU +{9A5C2190-C960-4808-93CB-8721C1022F9B}.Debug|Any CPU.Build.0 = Debug|Any CPU +{9A5C2190-C960-4808-93CB-8721C1022F9B}.Release|Any CPU.ActiveCfg = Release|Any CPU +{9A5C2190-C960-4808-93CB-8721C1022F9B}.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 diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj index a103786b912..8bccfa94485 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/IO.Swagger.csproj @@ -3,7 +3,7 @@ Debug AnyCPU - {3B55ED13-A471-44B1-A8D5-C158723C0A0C} + {9A5C2190-C960-4808-93CB-8721C1022F9B} Library Properties IO.Swagger.v2 @@ -31,8 +31,8 @@ bin\Release\IO.Swagger.XML - - ..\..\packages\Nancy.1.4.1\lib\net40\Nancy.dll + + ..\..\packages\Nancy.1.4.3\lib\net40\Nancy.dll True diff --git a/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config b/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config index 2575d1b4d77..e3401566e5d 100644 --- a/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config +++ b/samples/server/petstore/nancyfx/src/IO.Swagger/packages.config @@ -1,6 +1,6 @@ - + diff --git a/samples/server/petstore/nodejs/api/swagger.yaml b/samples/server/petstore/nodejs/api/swagger.yaml index 0710bccc06f..64049d2fdcc 100644 --- a/samples/server/petstore/nodejs/api/swagger.yaml +++ b/samples/server/petstore/nodejs/api/swagger.yaml @@ -356,8 +356,8 @@ paths: description: "ID of pet that needs to be fetched" required: true type: "integer" - maximum: 5 - minimum: 1 + maximum: 5.0 + minimum: 1.0 format: "int64" responses: 200: @@ -385,7 +385,6 @@ paths: description: "ID of the order that needs to be deleted" required: true type: "string" - minimum: 1 responses: 400: description: "Invalid ID supplied" diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala index 7c6d352ae5d..2353b35ff76 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala @@ -63,7 +63,7 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("petId").description(""), headerParam[String]("apiKey").description("").optional) ) - delete("/pet/:petId",operation(deletePetOperation)) { + delete("/pet/{petId}",operation(deletePetOperation)) { val petId = params.getOrElse("petId", halt(400)) @@ -131,7 +131,7 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("petId").description("")) ) - get("/pet/:petId",operation(getPetByIdOperation)) { + get("/pet/{petId}",operation(getPetByIdOperation)) { val petId = params.getOrElse("petId", halt(400)) @@ -161,7 +161,7 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("petId").description(""), formParam[String]("name").description("").optional, formParam[String]("status").description("").optional) ) - post("/pet/:petId",operation(updatePetWithFormOperation)) { + post("/pet/{petId}",operation(updatePetWithFormOperation)) { val petId = params.getOrElse("petId", halt(400)) @@ -186,7 +186,7 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("petId").description(""), formParam[String]("additionalMetadata").description("").optional, formParam[File]("file").description("").optional) ) - post("/pet/:petId/uploadImage",operation(uploadFileOperation)) { + post("/pet/{petId}/uploadImage",operation(uploadFileOperation)) { val petId = params.getOrElse("petId", halt(400)) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala index 58af1ba24f5..44e41f4d1e8 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala @@ -46,7 +46,7 @@ class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[String]("orderId").description("")) ) - delete("/store/order/:orderId",operation(deleteOrderOperation)) { + delete("/store/order/{orderId}",operation(deleteOrderOperation)) { val orderId = params.getOrElse("orderId", halt(400)) @@ -71,7 +71,7 @@ class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("orderId").description("")) ) - get("/store/order/:orderId",operation(getOrderByIdOperation)) { + get("/store/order/{orderId}",operation(getOrderByIdOperation)) { val orderId = params.getOrElse("orderId", halt(400)) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala index 8dfcc672c26..8b8630675b1 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala @@ -93,7 +93,6 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet delete("/user/:username",operation(deleteUserOperation)) { - val username = params.getOrElse("username", halt(400)) println("username: " + username) @@ -108,7 +107,6 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet get("/user/:username",operation(getUserByNameOperation)) { - val username = params.getOrElse("username", halt(400)) println("username: " + username) @@ -153,7 +151,6 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet put("/user/:username",operation(updateUserOperation)) { - val username = params.getOrElse("username", halt(400)) println("username: " + username) diff --git a/samples/server/petstore/spring-mvc-j8-async/pom.xml b/samples/server/petstore/spring-mvc-j8-async/pom.xml index 0440e5c1603..73502d0c277 100644 --- a/samples/server/petstore/spring-mvc-j8-async/pom.xml +++ b/samples/server/petstore/spring-mvc-j8-async/pom.xml @@ -123,6 +123,13 @@ servlet-api ${servlet-api-version} + + + javax.validation + validation-api + 1.1.0.Final + provided + 1.8 diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java index 0e6a9276c38..9590001aab3 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApi.java @@ -19,7 +19,7 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.concurrent.CompletableFuture; - +import javax.validation.constraints.*; @Api(value = "fake", description = "the fake API") public interface FakeApi { @@ -78,9 +78,9 @@ public interface FakeApi { @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java index 31729a28177..bcba1b5fdde 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeApiController.java @@ -2,9 +2,11 @@ package io.swagger.api; import org.springframework.stereotype.Controller; - +import javax.validation.constraints.*; @Controller public class FakeApiController implements FakeApi { + + } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApi.java index 8e4d72203ac..4f862816879 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApi.java @@ -16,7 +16,7 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.concurrent.CompletableFuture; - +import javax.validation.constraints.*; @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApiController.java index ee1bbc96b5b..805a0024bb0 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/FakeClassnameTestApiController.java @@ -2,9 +2,11 @@ package io.swagger.api; import org.springframework.stereotype.Controller; - +import javax.validation.constraints.*; @Controller public class FakeClassnameTestApiController implements FakeClassnameTestApi { + + } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java index 3727f1898c7..fd5b2c93f82 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApi.java @@ -18,7 +18,7 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.concurrent.CompletableFuture; - +import javax.validation.constraints.*; @Api(value = "pet", description = "the pet API") public interface PetApi { @@ -71,7 +71,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture>> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { + default CompletableFuture>> findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity>(HttpStatus.OK)); } @@ -89,7 +89,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture>> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + default CompletableFuture>> findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity>(HttpStatus.OK)); } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java index 68d93c1b173..13c57a67635 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/PetApiController.java @@ -2,9 +2,11 @@ package io.swagger.api; import org.springframework.stereotype.Controller; - +import javax.validation.constraints.*; @Controller public class PetApiController implements PetApi { + + } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java index a1afe015a29..b99481c2aff 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApi.java @@ -17,7 +17,7 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.concurrent.CompletableFuture; - +import javax.validation.constraints.*; @Api(value = "store", description = "the store API") public interface StoreApi { @@ -57,7 +57,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture> getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + default CompletableFuture> getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java index 470516e48f0..408cb9e7ae5 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/StoreApiController.java @@ -2,9 +2,11 @@ package io.swagger.api; import org.springframework.stereotype.Controller; - +import javax.validation.constraints.*; @Controller public class StoreApiController implements StoreApi { + + } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java index 919e67d2cab..2b539a21966 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApi.java @@ -17,7 +17,7 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.concurrent.CompletableFuture; - +import javax.validation.constraints.*; @Api(value = "user", description = "the user API") public interface UserApi { @@ -92,8 +92,8 @@ public interface UserApi { @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - default CompletableFuture> loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + default CompletableFuture> loginUser( @NotNull @ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { // do some magic! return CompletableFuture.completedFuture(new ResponseEntity(HttpStatus.OK)); } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java index 7ecb3ed8e0b..4f13d0d9ba3 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/api/UserApiController.java @@ -2,9 +2,11 @@ package io.swagger.api; import org.springframework.stereotype.Controller; - +import javax.validation.constraints.*; @Controller public class UserApiController implements UserApi { + + } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AdditionalPropertiesClass.java index f74f7d3d882..81535e041fa 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; - +import javax.validation.constraints.*; /** * AdditionalPropertiesClass */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java index 60aaf82231f..a218f0b5542 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Animal.java @@ -7,10 +7,15 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Animal */ +@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"), +}) public class Animal { @JsonProperty("className") @@ -29,6 +34,7 @@ public class Animal { * @return className **/ @ApiModelProperty(required = true, value = "") + @NotNull public String getClassName() { return className; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AnimalFarm.java index c2b0084d9cd..33dc04699af 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/AnimalFarm.java @@ -4,7 +4,7 @@ import java.util.Objects; import io.swagger.model.Animal; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * AnimalFarm */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 803eb69e16a..3be691e4d95 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * ArrayOfArrayOfNumberOnly */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfNumberOnly.java index bebc2470927..12196897345 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * ArrayOfNumberOnly */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayTest.java index 19464a99acd..a26a1600287 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ArrayTest.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * ArrayTest */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Capitalization.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..d7ad5642ccf --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Capitalization.java @@ -0,0 +1,189 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Cat.java index 95bea570923..747e5dc0c7e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Cat.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Animal; - +import javax.validation.constraints.*; /** * Cat */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java index ba1ecfdb2b8..9629da6500e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Category.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Category */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ClassModel.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..d69acffefa8 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ClassModel.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Client.java index fcb2b0a8340..f9cec5a225e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Client.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Client.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Client */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Dog.java index f8072688756..9057e840fc3 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Dog.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Animal; - +import javax.validation.constraints.*; /** * Dog */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumArrays.java index 959b35e6b13..97ab6f6410e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumArrays.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * EnumArrays */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumClass.java index d8ac42c4872..cdfc0933c3e 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumClass.java @@ -2,7 +2,7 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; - +import javax.validation.constraints.*; import com.fasterxml.jackson.annotation.JsonCreator; /** diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java index 66e7c1ffe5a..9f2a0275a6a 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/EnumTest.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.OuterEnum; - +import javax.validation.constraints.*; /** * EnumTest */ @@ -19,7 +19,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java index dffef2ea6da..fc491c68d6b 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/FormatTest.java @@ -9,7 +9,7 @@ import java.math.BigDecimal; import java.time.LocalDate; import java.time.OffsetDateTime; import java.util.UUID; - +import javax.validation.constraints.*; /** * FormatTest */ @@ -66,6 +66,8 @@ public class FormatTest { * @return integer **/ @ApiModelProperty(value = "") + @Min(10) + @Max(100) public Integer getInteger() { return integer; } @@ -86,6 +88,8 @@ public class FormatTest { * @return int32 **/ @ApiModelProperty(value = "") + @Min(20) + @Max(200) public Integer getInt32() { return int32; } @@ -124,6 +128,9 @@ public class FormatTest { * @return number **/ @ApiModelProperty(required = true, value = "") + @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -144,6 +151,8 @@ public class FormatTest { * @return _float **/ @ApiModelProperty(value = "") + @DecimalMin("54.3") + @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -164,6 +173,8 @@ public class FormatTest { * @return _double **/ @ApiModelProperty(value = "") + @DecimalMin("67.8") + @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -182,6 +193,7 @@ public class FormatTest { * @return string **/ @ApiModelProperty(value = "") + @Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -200,6 +212,7 @@ public class FormatTest { * @return _byte **/ @ApiModelProperty(required = true, value = "") + @NotNull public byte[] getByte() { return _byte; } @@ -236,6 +249,7 @@ public class FormatTest { * @return date **/ @ApiModelProperty(required = true, value = "") + @NotNull public LocalDate getDate() { return date; } @@ -290,6 +304,8 @@ public class FormatTest { * @return password **/ @ApiModelProperty(required = true, value = "") + @NotNull + @Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java index 55817f8dd14..a26492e4912 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * HasOnlyReadOnly */ @@ -26,7 +26,7 @@ public class HasOnlyReadOnly { * Get bar * @return bar **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public String getBar() { return bar; } @@ -44,7 +44,7 @@ public class HasOnlyReadOnly { * Get foo * @return foo **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public String getFoo() { return foo; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MapTest.java index 9ef30a045d0..9a0566a8dd1 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MapTest.java @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; - +import javax.validation.constraints.*; /** * MapTest */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index 560634e11d4..31f364f2497 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -11,7 +11,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; - +import javax.validation.constraints.*; /** * MixedPropertiesAndAdditionalPropertiesClass */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Model200Response.java index 09ad4d0d60e..4d47f6c03c9 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Model200Response.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Model for testing model name starting with number */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java index 82f447004ee..36da9b20d9d 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelApiResponse.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * ModelApiResponse */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelReturn.java index 884a45c598e..7ffc24a0144 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ModelReturn.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Model for testing reserved words */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java index aa31ac8d79a..953199166ff 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Name.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Model for testing model name same as property name */ @@ -34,6 +34,7 @@ public class Name { * @return name **/ @ApiModelProperty(required = true, value = "") + @NotNull public Integer getName() { return name; } @@ -51,7 +52,7 @@ public class Name { * Get snakeCase * @return snakeCase **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public Integer getSnakeCase() { return snakeCase; } @@ -87,7 +88,7 @@ public class Name { * Get _123Number * @return _123Number **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public Integer get123Number() { return _123Number; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/NumberOnly.java index 9424f7a4b5e..e6dbf3139e2 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/NumberOnly.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - +import javax.validation.constraints.*; /** * NumberOnly */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java index cee3ae6d708..d65ed713151 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.time.OffsetDateTime; - +import javax.validation.constraints.*; /** * Order */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..5f0075e4457 --- /dev/null +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java index 823d25e05a0..9adc708de71 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Pet.java @@ -10,7 +10,7 @@ import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * Pet */ @@ -113,6 +113,7 @@ public class Pet { * @return name **/ @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull public String getName() { return name; } @@ -136,6 +137,7 @@ public class Pet { * @return photoUrls **/ @ApiModelProperty(required = true, value = "") + @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java index 76d529c087a..47700659fd2 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * ReadOnlyFirst */ @@ -26,7 +26,7 @@ public class ReadOnlyFirst { * Get bar * @return bar **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public String getBar() { return bar; } diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/SpecialModelName.java index 2cdc99de90e..880d70599b0 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/SpecialModelName.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * SpecialModelName */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java index 846812a5031..298085317a4 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/Tag.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Tag */ diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java index 52c5fff826e..8e40f7e0594 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/io/swagger/model/User.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * User */ diff --git a/samples/server/petstore/spring-mvc/pom.xml b/samples/server/petstore/spring-mvc/pom.xml index 83595e59384..6830c25fa7b 100644 --- a/samples/server/petstore/spring-mvc/pom.xml +++ b/samples/server/petstore/spring-mvc/pom.xml @@ -123,6 +123,13 @@ servlet-api ${servlet-api-version} + + + javax.validation + validation-api + 1.1.0.Final + provided + 1.7 diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java index 867335a3fb6..2feb92b12e5 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApi.java @@ -17,7 +17,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "fake", description = "the fake API") public interface FakeApi { @@ -70,9 +70,9 @@ public interface FakeApi { @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java index 70fb75199b2..c984ea73b68 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeApiController.java @@ -19,11 +19,13 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Controller public class FakeApiController implements FakeApi { + + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -51,9 +53,9 @@ public class FakeApiController implements FakeApi { @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApi.java index 628380949f8..bf962faa6fd 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApi.java @@ -14,7 +14,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApiController.java index 8b527aa9a9d..60a2b4d44ce 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/FakeClassnameTestApiController.java @@ -16,11 +16,13 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Controller public class FakeClassnameTestApiController implements FakeClassnameTestApi { + + public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index 7d48cfb31c9..dcd4a0f8b8c 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -16,7 +16,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "pet", description = "the pet API") public interface PetApi { @@ -63,7 +63,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); + ResponseEntity> findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -78,7 +78,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + ResponseEntity> findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java index edf1abc3ead..847b24e1a80 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApiController.java @@ -18,11 +18,13 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Controller public class PetApiController implements PetApi { + + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -34,12 +36,12 @@ public class PetApiController implements PetApi { return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { + public ResponseEntity> findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { // do some magic! return new ResponseEntity>(HttpStatus.OK); } - public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + public ResponseEntity> findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { // do some magic! return new ResponseEntity>(HttpStatus.OK); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index f5526de9862..47c2c561ff1 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -15,7 +15,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "store", description = "the store API") public interface StoreApi { @@ -49,7 +49,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java index bd582ae1a94..97a1b7e5129 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApiController.java @@ -17,11 +17,13 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Controller public class StoreApiController implements StoreApi { + + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -32,7 +34,7 @@ public class StoreApiController implements StoreApi { return new ResponseEntity>(HttpStatus.OK); } - public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + public ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { // do some magic! return new ResponseEntity(HttpStatus.OK); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index c31b5a143ee..2d15d4b071a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -15,7 +15,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "user", description = "the user API") public interface UserApi { @@ -75,8 +75,8 @@ public interface UserApi { @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + ResponseEntity loginUser( @NotNull @ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java index f9f6fbd25a4..c321750e95e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApiController.java @@ -17,11 +17,13 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Controller public class UserApiController implements UserApi { + + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -47,8 +49,8 @@ public class UserApiController implements UserApi { return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + public ResponseEntity loginUser( @NotNull @ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { // do some magic! return new ResponseEntity(HttpStatus.OK); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AdditionalPropertiesClass.java index f74f7d3d882..81535e041fa 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; - +import javax.validation.constraints.*; /** * AdditionalPropertiesClass */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java index 60aaf82231f..a218f0b5542 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Animal.java @@ -7,10 +7,15 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Animal */ +@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"), +}) public class Animal { @JsonProperty("className") @@ -29,6 +34,7 @@ public class Animal { * @return className **/ @ApiModelProperty(required = true, value = "") + @NotNull public String getClassName() { return className; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AnimalFarm.java index c2b0084d9cd..33dc04699af 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/AnimalFarm.java @@ -4,7 +4,7 @@ import java.util.Objects; import io.swagger.model.Animal; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * AnimalFarm */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 803eb69e16a..3be691e4d95 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * ArrayOfArrayOfNumberOnly */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfNumberOnly.java index bebc2470927..12196897345 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * ArrayOfNumberOnly */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayTest.java index 19464a99acd..a26a1600287 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ArrayTest.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * ArrayTest */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Capitalization.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..d7ad5642ccf --- /dev/null +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Capitalization.java @@ -0,0 +1,189 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Cat.java index 95bea570923..747e5dc0c7e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Cat.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Animal; - +import javax.validation.constraints.*; /** * Cat */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java index ba1ecfdb2b8..9629da6500e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Category */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ClassModel.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ClassModel.java index 16c743e4f32..d69acffefa8 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ClassModel.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ClassModel.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Model for testing model with \"_class\" property */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Client.java index fcb2b0a8340..f9cec5a225e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Client.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Client.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Client */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Dog.java index f8072688756..9057e840fc3 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Dog.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Animal; - +import javax.validation.constraints.*; /** * Dog */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumArrays.java index 959b35e6b13..97ab6f6410e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumArrays.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * EnumArrays */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumClass.java index d8ac42c4872..cdfc0933c3e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumClass.java @@ -2,7 +2,7 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; - +import javax.validation.constraints.*; import com.fasterxml.jackson.annotation.JsonCreator; /** diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java index 66e7c1ffe5a..9f2a0275a6a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/EnumTest.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.OuterEnum; - +import javax.validation.constraints.*; /** * EnumTest */ @@ -19,7 +19,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java index 9d0aac9f73a..342ebe05be6 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/FormatTest.java @@ -9,7 +9,7 @@ import java.math.BigDecimal; import java.util.UUID; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; - +import javax.validation.constraints.*; /** * FormatTest */ @@ -66,6 +66,8 @@ public class FormatTest { * @return integer **/ @ApiModelProperty(value = "") + @Min(10) + @Max(100) public Integer getInteger() { return integer; } @@ -86,6 +88,8 @@ public class FormatTest { * @return int32 **/ @ApiModelProperty(value = "") + @Min(20) + @Max(200) public Integer getInt32() { return int32; } @@ -124,6 +128,9 @@ public class FormatTest { * @return number **/ @ApiModelProperty(required = true, value = "") + @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -144,6 +151,8 @@ public class FormatTest { * @return _float **/ @ApiModelProperty(value = "") + @DecimalMin("54.3") + @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -164,6 +173,8 @@ public class FormatTest { * @return _double **/ @ApiModelProperty(value = "") + @DecimalMin("67.8") + @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -182,6 +193,7 @@ public class FormatTest { * @return string **/ @ApiModelProperty(value = "") + @Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -200,6 +212,7 @@ public class FormatTest { * @return _byte **/ @ApiModelProperty(required = true, value = "") + @NotNull public byte[] getByte() { return _byte; } @@ -236,6 +249,7 @@ public class FormatTest { * @return date **/ @ApiModelProperty(required = true, value = "") + @NotNull public LocalDate getDate() { return date; } @@ -290,6 +304,8 @@ public class FormatTest { * @return password **/ @ApiModelProperty(required = true, value = "") + @NotNull + @Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java index 55817f8dd14..a26492e4912 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * HasOnlyReadOnly */ @@ -26,7 +26,7 @@ public class HasOnlyReadOnly { * Get bar * @return bar **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public String getBar() { return bar; } @@ -44,7 +44,7 @@ public class HasOnlyReadOnly { * Get foo * @return foo **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public String getFoo() { return foo; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MapTest.java index 9ef30a045d0..9a0566a8dd1 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MapTest.java @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; - +import javax.validation.constraints.*; /** * MapTest */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index 507b3c5e662..19eb9f2b139 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -11,7 +11,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; import org.threeten.bp.OffsetDateTime; - +import javax.validation.constraints.*; /** * MixedPropertiesAndAdditionalPropertiesClass */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Model200Response.java index 09ad4d0d60e..4d47f6c03c9 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Model200Response.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Model for testing model name starting with number */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java index 82f447004ee..36da9b20d9d 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelApiResponse.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * ModelApiResponse */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelReturn.java index 884a45c598e..7ffc24a0144 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ModelReturn.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Model for testing reserved words */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java index aa31ac8d79a..953199166ff 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Name.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Model for testing model name same as property name */ @@ -34,6 +34,7 @@ public class Name { * @return name **/ @ApiModelProperty(required = true, value = "") + @NotNull public Integer getName() { return name; } @@ -51,7 +52,7 @@ public class Name { * Get snakeCase * @return snakeCase **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public Integer getSnakeCase() { return snakeCase; } @@ -87,7 +88,7 @@ public class Name { * Get _123Number * @return _123Number **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public Integer get123Number() { return _123Number; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/NumberOnly.java index 9424f7a4b5e..e6dbf3139e2 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/NumberOnly.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - +import javax.validation.constraints.*; /** * NumberOnly */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java index b63c620c987..c5381d2fa7e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.threeten.bp.OffsetDateTime; - +import javax.validation.constraints.*; /** * Order */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/OuterEnum.java index 0abc3d063b5..5f0075e4457 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/OuterEnum.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/OuterEnum.java @@ -2,7 +2,7 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; - +import javax.validation.constraints.*; import com.fasterxml.jackson.annotation.JsonCreator; /** diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java index 823d25e05a0..9adc708de71 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java @@ -10,7 +10,7 @@ import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * Pet */ @@ -113,6 +113,7 @@ public class Pet { * @return name **/ @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull public String getName() { return name; } @@ -136,6 +137,7 @@ public class Pet { * @return photoUrls **/ @ApiModelProperty(required = true, value = "") + @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java index 76d529c087a..47700659fd2 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * ReadOnlyFirst */ @@ -26,7 +26,7 @@ public class ReadOnlyFirst { * Get bar * @return bar **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public String getBar() { return bar; } diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/SpecialModelName.java index 2cdc99de90e..880d70599b0 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/SpecialModelName.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * SpecialModelName */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java index 846812a5031..298085317a4 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Tag */ diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java index 52c5fff826e..8e40f7e0594 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * User */ diff --git a/samples/server/petstore/springboot-delegate-j8/.swagger-codegen-ignore b/samples/server/petstore/springboot-delegate-j8/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/springboot-delegate-j8/README.md b/samples/server/petstore/springboot-delegate-j8/README.md new file mode 100644 index 00000000000..a2e8a9f7b84 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/README.md @@ -0,0 +1,18 @@ +# Swagger generated server + +Spring Boot Server + + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate a server stub. +This is an example of building a swagger-enabled server in Java using the SpringBoot framework. + +The underlying library integrating swagger to SpringBoot is [springfox](https://github.com/springfox/springfox) + +Start your server as an simple java application + +You can view the api documentation in swagger-ui by pointing to +http://localhost:8080/ + +Change default port value in application.properties \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate-j8/pom.xml b/samples/server/petstore/springboot-delegate-j8/pom.xml new file mode 100644 index 00000000000..c893d2290b0 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/pom.xml @@ -0,0 +1,69 @@ + + 4.0.0 + io.swagger + swagger-spring + jar + swagger-spring + 1.0.0 + + 1.8 + ${java.version} + ${java.version} + 2.5.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.5.RELEASE + + + src/main/java + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + io.springfox + springfox-swagger2 + ${springfox-version} + + + io.springfox + springfox-swagger-ui + ${springfox-version} + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + + javax.validation + validation-api + 1.1.0.Final + provided + + + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/RFC3339DateFormat.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/RFC3339DateFormat.java new file mode 100644 index 00000000000..0c3d276d2d4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/RFC3339DateFormat.java @@ -0,0 +1,20 @@ +package io.swagger; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/Swagger2SpringBoot.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/Swagger2SpringBoot.java new file mode 100644 index 00000000000..c06fbae3c7a --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/Swagger2SpringBoot.java @@ -0,0 +1,36 @@ +package io.swagger; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableSwagger2 +@ComponentScan(basePackages = "io.swagger") +public class Swagger2SpringBoot implements CommandLineRunner { + + @Override + public void run(String... arg0) throws Exception { + if (arg0.length > 0 && arg0[0].equals("exitcode")) { + throw new ExitException(); + } + } + + public static void main(String[] args) throws Exception { + new SpringApplication(Swagger2SpringBoot.class).run(args); + } + + class ExitException extends RuntimeException implements ExitCodeGenerator { + private static final long serialVersionUID = 1L; + + @Override + public int getExitCode() { + return 10; + } + + } +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiException.java new file mode 100644 index 00000000000..7fa61c50d24 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiOriginFilter.java new file mode 100644 index 00000000000..f0f62dc7206 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -0,0 +1,27 @@ +package io.swagger.api; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + + +public class ApiOriginFilter implements javax.servlet.Filter { + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiResponseMessage.java new file mode 100644 index 00000000000..f03840f8e06 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -0,0 +1,69 @@ +package io.swagger.api; + +import javax.xml.bind.annotation.XmlTransient; + + +@javax.xml.bind.annotation.XmlRootElement +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApi.java new file mode 100644 index 00000000000..cbdd93952b8 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApi.java @@ -0,0 +1,88 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.time.LocalDate; +import java.time.OffsetDateTime; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import javax.validation.constraints.*; + +@Api(value = "fake", description = "the fake API") +public interface FakeApi { + + @ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + @RequestMapping(value = "/fake", + produces = { "application/json" }, + consumes = { "application/json" }, + method = RequestMethod.PATCH) + default ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, authorizations = { + @Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/fake", + produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, + consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, + method = RequestMethod.POST) + default ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true ) @RequestPart(value="number", required=true) BigDecimal number, + @ApiParam(value = "None", required=true ) @RequestPart(value="_double", required=true) Double _double, + @ApiParam(value = "None", required=true ) @RequestPart(value="patternWithoutDelimiter", required=true) String patternWithoutDelimiter, + @ApiParam(value = "None", required=true ) @RequestPart(value="_byte", required=true) byte[] _byte, + @ApiParam(value = "None" ) @RequestPart(value="integer", required=false) Integer integer, + @ApiParam(value = "None" ) @RequestPart(value="int32", required=false) Integer int32, + @ApiParam(value = "None" ) @RequestPart(value="int64", required=false) Long int64, + @ApiParam(value = "None" ) @RequestPart(value="_float", required=false) Float _float, + @ApiParam(value = "None" ) @RequestPart(value="string", required=false) String string, + @ApiParam(value = "None" ) @RequestPart(value="binary", required=false) byte[] binary, + @ApiParam(value = "None" ) @RequestPart(value="date", required=false) LocalDate date, + @ApiParam(value = "None" ) @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, + @ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password, + @ApiParam(value = "None" ) @RequestPart(value="paramCallback", required=false) String paramCallback) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = Void.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid request", response = Void.class), + @ApiResponse(code = 404, message = "Not found", response = Void.class) }) + @RequestMapping(value = "/fake", + produces = { "*/*" }, + consumes = { "*/*" }, + method = RequestMethod.GET) + default ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray, + @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, + @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, + @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiController.java new file mode 100644 index 00000000000..6e162ee2183 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiController.java @@ -0,0 +1,69 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.time.LocalDate; +import java.time.OffsetDateTime; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import javax.validation.constraints.*; + +@Controller +public class FakeApiController implements FakeApi { + private final FakeApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + FakeApiController(FakeApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { + // do some magic! + return delegate.testClientModel(body); + } + + public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true ) @RequestPart(value="number", required=true) BigDecimal number, + @ApiParam(value = "None", required=true ) @RequestPart(value="_double", required=true) Double _double, + @ApiParam(value = "None", required=true ) @RequestPart(value="patternWithoutDelimiter", required=true) String patternWithoutDelimiter, + @ApiParam(value = "None", required=true ) @RequestPart(value="_byte", required=true) byte[] _byte, + @ApiParam(value = "None" ) @RequestPart(value="integer", required=false) Integer integer, + @ApiParam(value = "None" ) @RequestPart(value="int32", required=false) Integer int32, + @ApiParam(value = "None" ) @RequestPart(value="int64", required=false) Long int64, + @ApiParam(value = "None" ) @RequestPart(value="_float", required=false) Float _float, + @ApiParam(value = "None" ) @RequestPart(value="string", required=false) String string, + @ApiParam(value = "None" ) @RequestPart(value="binary", required=false) byte[] binary, + @ApiParam(value = "None" ) @RequestPart(value="date", required=false) LocalDate date, + @ApiParam(value = "None" ) @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, + @ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password, + @ApiParam(value = "None" ) @RequestPart(value="paramCallback", required=false) String paramCallback) { + // do some magic! + return delegate.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray, + @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, + @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, + @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { + // do some magic! + return delegate.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiDelegate.java new file mode 100644 index 00000000000..96d5e63a372 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/FakeApiDelegate.java @@ -0,0 +1,67 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import java.time.LocalDate; +import java.time.OffsetDateTime; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link FakeApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link FakeApiController}. + */ + +public interface FakeApiDelegate { + + /** + * @see FakeApi#testClientModel + */ + default ResponseEntity testClientModel(Client body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see FakeApi#testEndpointParameters + */ + default ResponseEntity testEndpointParameters(BigDecimal number, + Double _double, + String patternWithoutDelimiter, + byte[] _byte, + Integer integer, + Integer int32, + Long int64, + Float _float, + String string, + byte[] binary, + LocalDate date, + OffsetDateTime dateTime, + String password, + String paramCallback) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see FakeApi#testEnumParameters + */ + default ResponseEntity testEnumParameters(List enumFormStringArray, + String enumFormString, + List enumHeaderStringArray, + String enumHeaderString, + List enumQueryStringArray, + String enumQueryString, + Integer enumQueryInteger, + Double enumQueryDouble) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/NotFoundException.java new file mode 100644 index 00000000000..295109d7fc4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/NotFoundException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..7ffb559205b --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApi.java @@ -0,0 +1,172 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import javax.validation.constraints.*; + +@Api(value = "pet", description = "the pet API") +public interface PetApi { + + @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, 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", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" }, + method = RequestMethod.POST) + default ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, 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", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + default ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", 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", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByStatus", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity> findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", 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", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByTags", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity> findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Authorization(value = "api_key") + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, 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", }) + @ApiResponses(value = { + @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) }) + @RequestMapping(value = "/pet", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" }, + method = RequestMethod.PUT) + default ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, 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", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + consumes = { "application/x-www-form-urlencoded" }, + method = RequestMethod.POST) + default ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, 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", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + @RequestMapping(value = "/pet/{petId}/uploadImage", + produces = { "application/json" }, + consumes = { "multipart/form-data" }, + method = RequestMethod.POST) + default ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiController.java new file mode 100644 index 00000000000..03c23df7b47 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiController.java @@ -0,0 +1,78 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import javax.validation.constraints.*; + +@Controller +public class PetApiController implements PetApi { + private final PetApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + PetApiController(PetApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return delegate.addPet(body); + } + + public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + // do some magic! + return delegate.deletePet(petId, apiKey); + } + + public ResponseEntity> findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { + // do some magic! + return delegate.findPetsByStatus(status); + } + + public ResponseEntity> findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + // do some magic! + return delegate.findPetsByTags(tags); + } + + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId) { + // do some magic! + return delegate.getPetById(petId); + } + + public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return delegate.updatePet(body); + } + + public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) { + // do some magic! + return delegate.updatePetWithForm(petId, name, status); + } + + public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) { + // do some magic! + return delegate.uploadFile(petId, additionalMetadata, file); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiDelegate.java new file mode 100644 index 00000000000..7f89dfdabb4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/PetApiDelegate.java @@ -0,0 +1,91 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link PetApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link PetApiController}. + */ + +public interface PetApiDelegate { + + /** + * @see PetApi#addPet + */ + default ResponseEntity addPet(Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see PetApi#deletePet + */ + default ResponseEntity deletePet(Long petId, + String apiKey) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see PetApi#findPetsByStatus + */ + default ResponseEntity> findPetsByStatus(List status) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + /** + * @see PetApi#findPetsByTags + */ + default ResponseEntity> findPetsByTags(List tags) { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + /** + * @see PetApi#getPetById + */ + default ResponseEntity getPetById(Long petId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see PetApi#updatePet + */ + default ResponseEntity updatePet(Pet body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see PetApi#updatePetWithForm + */ + default ResponseEntity updatePetWithForm(Long petId, + String name, + String status) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see PetApi#uploadFile + */ + default ResponseEntity uploadFile(Long petId, + String additionalMetadata, + MultipartFile file) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..2c1ad770b52 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApi.java @@ -0,0 +1,77 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import javax.validation.constraints.*; + +@Api(value = "store", description = "the store API") +public interface StoreApi { + + @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", response = Void.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + default ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) + @RequestMapping(value = "/store/inventory", + produces = { "application/json" }, + method = RequestMethod.GET) + default ResponseEntity> getInventory() { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + @RequestMapping(value = "/store/order", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + default ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiController.java new file mode 100644 index 00000000000..050a9d7de74 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiController.java @@ -0,0 +1,52 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import javax.validation.constraints.*; + +@Controller +public class StoreApiController implements StoreApi { + private final StoreApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + StoreApiController(StoreApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { + // do some magic! + return delegate.deleteOrder(orderId); + } + + public ResponseEntity> getInventory() { + // do some magic! + return delegate.getInventory(); + } + + public ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + // do some magic! + return delegate.getOrderById(orderId); + } + + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body) { + // do some magic! + return delegate.placeOrder(body); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiDelegate.java new file mode 100644 index 00000000000..17a4dfc2a9d --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/StoreApiDelegate.java @@ -0,0 +1,53 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link StoreApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link StoreApiController}. + */ + +public interface StoreApiDelegate { + + /** + * @see StoreApi#deleteOrder + */ + default ResponseEntity deleteOrder(String orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see StoreApi#getInventory + */ + default ResponseEntity> getInventory() { + // do some magic! + return new ResponseEntity>(HttpStatus.OK); + } + + /** + * @see StoreApi#getOrderById + */ + default ResponseEntity getOrderById(Long orderId) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see StoreApi#placeOrder + */ + default ResponseEntity placeOrder(Order body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..384f944c78f --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApi.java @@ -0,0 +1,126 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import javax.validation.constraints.*; + +@Api(value = "user", description = "the user API") +public interface UserApi { + + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + default ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithArray", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + default ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithList", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + default ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + default ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @ApiResponse(code = 404, message = "User not found", response = User.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + @RequestMapping(value = "/user/login", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity loginUser( @NotNull @ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/logout", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + default ResponseEntity logoutUser() { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.PUT) + default ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiController.java new file mode 100644 index 00000000000..785e28f4509 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiController.java @@ -0,0 +1,74 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import javax.validation.constraints.*; + +@Controller +public class UserApiController implements UserApi { + private final UserApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + UserApiController(UserApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { + // do some magic! + return delegate.createUser(body); + } + + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return delegate.createUsersWithArrayInput(body); + } + + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return delegate.createUsersWithListInput(body); + } + + public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) { + // do some magic! + return delegate.deleteUser(username); + } + + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) { + // do some magic! + return delegate.getUserByName(username); + } + + public ResponseEntity loginUser( @NotNull @ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + // do some magic! + return delegate.loginUser(username, password); + } + + public ResponseEntity logoutUser() { + // do some magic! + return delegate.logoutUser(); + } + + public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body) { + // do some magic! + return delegate.updateUser(username, body); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiDelegate.java new file mode 100644 index 00000000000..435efd58a8e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/api/UserApiDelegate.java @@ -0,0 +1,87 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link UserApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link UserApiController}. + */ + +public interface UserApiDelegate { + + /** + * @see UserApi#createUser + */ + default ResponseEntity createUser(User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#createUsersWithArrayInput + */ + default ResponseEntity createUsersWithArrayInput(List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#createUsersWithListInput + */ + default ResponseEntity createUsersWithListInput(List body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#deleteUser + */ + default ResponseEntity deleteUser(String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#getUserByName + */ + default ResponseEntity getUserByName(String username) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#loginUser + */ + default ResponseEntity loginUser(String username, + String password) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#logoutUser + */ + default ResponseEntity logoutUser() { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + + /** + * @see UserApi#updateUser + */ + default ResponseEntity updateUser(String username, + User body) { + // do some magic! + return new ResponseEntity(HttpStatus.OK); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/HomeController.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/HomeController.java new file mode 100644 index 00000000000..d195523c1d3 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/HomeController.java @@ -0,0 +1,16 @@ +package io.swagger.configuration; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Home redirection to swagger api documentation + */ +@Controller +public class HomeController { + @RequestMapping(value = "/") + public String index() { + System.out.println("swagger-ui.html"); + return "redirect:swagger-ui.html"; + } +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java new file mode 100644 index 00000000000..962607f9340 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java @@ -0,0 +1,40 @@ +package io.swagger.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + + +@Configuration +public class SwaggerDocumentationConfig { + + ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Swagger Petstore") + .description("This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\") + .license("Apache 2.0") + .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") + .termsOfServiceUrl("") + .version("1.0.0") + .contact(new Contact("","", "apiteam@swagger.io")) + .build(); + } + + @Bean + public Docket customImplementation(){ + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("io.swagger.api")) + .build() + .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class) + .apiInfo(apiInfo()); + } + +} diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..81535e041fa --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,110 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..a218f0b5542 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Animal.java @@ -0,0 +1,105 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Animal + */ +@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"), +}) + +public class Animal { + @JsonProperty("className") + private String className = null; + + @JsonProperty("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..33dc04699af --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,50 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.model.Animal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..3be691e4d95 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..12196897345 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..a26a1600287 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,138 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Capitalization.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..d7ad5642ccf --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Capitalization.java @@ -0,0 +1,189 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..747e5dc0c7e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Cat.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import javax.validation.constraints.*; +/** + * Cat + */ + +public class Cat extends Animal { + @JsonProperty("declawed") + private Boolean declawed = null; + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..9629da6500e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Category.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Category + */ + +public class Category { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ClassModel.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..d69acffefa8 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ClassModel.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..f9cec5a225e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Client.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Client + */ + +public class Client { + @JsonProperty("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(value = "") + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..9057e840fc3 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Dog.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import javax.validation.constraints.*; +/** + * Dog + */ + +public class Dog extends Animal { + @JsonProperty("breed") + private String breed = null; + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(value = "") + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..97ab6f6410e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,167 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * EnumArrays + */ + +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(value = "") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(value = "") + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..cdfc0933c3e --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumClass.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..9f2a0275a6a --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/EnumTest.java @@ -0,0 +1,240 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; +import javax.validation.constraints.*; +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_number") + private EnumNumberEnum enumNumber = null; + + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/FormatTest.java new file mode 100644 index 00000000000..fc491c68d6b --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/FormatTest.java @@ -0,0 +1,380 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.UUID; +import javax.validation.constraints.*; +/** + * FormatTest + */ + +public class FormatTest { + @JsonProperty("integer") + private Integer integer = null; + + @JsonProperty("int32") + private Integer int32 = null; + + @JsonProperty("int64") + private Long int64 = null; + + @JsonProperty("number") + private BigDecimal number = null; + + @JsonProperty("float") + private Float _float = null; + + @JsonProperty("double") + private Double _double = null; + + @JsonProperty("string") + private String string = null; + + @JsonProperty("byte") + private byte[] _byte = null; + + @JsonProperty("binary") + private byte[] binary = null; + + @JsonProperty("date") + private LocalDate date = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("uuid") + private UUID uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + @ApiModelProperty(value = "") + @Min(10) + @Max(100) + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + @ApiModelProperty(value = "") + @Min(20) + @Max(200) + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(value = "") + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @ApiModelProperty(value = "") + @DecimalMin("54.3") + @DecimalMax("987.6") + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @ApiModelProperty(value = "") + @DecimalMin("67.8") + @DecimalMax("123.4") + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(value = "") + @Pattern(regexp="/[a-z]/i") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(value = "") + public byte[] getBinary() { + return binary; + } + + public void setBinary(byte[] binary) { + this.binary = binary; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + @Size(min=10,max=64) + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..a26492e4912 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + public HasOnlyReadOnly bar(String bar) { + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(readOnly = true, value = "") + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + public HasOnlyReadOnly foo(String foo) { + this.foo = foo; + return this; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(readOnly = true, value = "") + public String getFoo() { + return foo; + } + + public void setFoo(String foo) { + this.foo = foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..9a0566a8dd1 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MapTest.java @@ -0,0 +1,142 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; +/** + * MapTest + */ + +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..31f364f2497 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,131 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import javax.validation.constraints.*; +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private UUID uuid = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..4d47f6c03c9 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Model200Response.java @@ -0,0 +1,98 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("class") + private String propertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.propertyClass, _200Response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..36da9b20d9d --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,120 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * ModelApiResponse + */ + +public class ModelApiResponse { + @JsonProperty("code") + private Integer code = null; + + @JsonProperty("type") + private String type = null; + + @JsonProperty("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..7ffc24a0144 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + @JsonProperty("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..953199166ff --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Name.java @@ -0,0 +1,145 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("snake_case") + private Integer snakeCase = null; + + @JsonProperty("property") + private String property = null; + + @JsonProperty("123Number") + private Integer _123Number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Name snakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + return this; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(readOnly = true, value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + public Name _123Number(Integer _123Number) { + this._123Number = _123Number; + return this; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(readOnly = true, value = "") + public Integer get123Number() { + return _123Number; + } + + public void set123Number(Integer _123Number) { + this._123Number = _123Number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..e6dbf3139e2 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import javax.validation.constraints.*; +/** + * NumberOnly + */ + +public class NumberOnly { + @JsonProperty("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..d65ed713151 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Order.java @@ -0,0 +1,224 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.time.OffsetDateTime; +import javax.validation.constraints.*; +/** + * Order + */ + +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private OffsetDateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getShipDate() { + return shipDate; + } + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..5f0075e4457 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..9adc708de71 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Pet.java @@ -0,0 +1,239 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * Pet + */ + +public class Pet { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("category") + private Category category = null; + + @JsonProperty("name") + private String name = null; + + @JsonProperty("photoUrls") + private List photoUrls = new ArrayList(); + + @JsonProperty("tags") + private List tags = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..47700659fd2 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("baz") + private String baz = null; + + public ReadOnlyFirst bar(String bar) { + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(readOnly = true, value = "") + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..880d70599b0 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * SpecialModelName + */ + +public class SpecialModelName { + @JsonProperty("$special[property.name]") + private Long specialPropertyName = null; + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..298085317a4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/Tag.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Tag + */ + +public class Tag { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/User.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/User.java new file mode 100644 index 00000000000..8e40f7e0594 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/io/swagger/model/User.java @@ -0,0 +1,235 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * User + */ + +public class User { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("username") + private String username = null; + + @JsonProperty("firstName") + private String firstName = null; + + @JsonProperty("lastName") + private String lastName = null; + + @JsonProperty("email") + private String email = null; + + @JsonProperty("password") + private String password = null; + + @JsonProperty("phone") + private String phone = null; + + @JsonProperty("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/resources/application.properties b/samples/server/petstore/springboot-delegate-j8/src/main/resources/application.properties new file mode 100644 index 00000000000..a2ef8627027 --- /dev/null +++ b/samples/server/petstore/springboot-delegate-j8/src/main/resources/application.properties @@ -0,0 +1,5 @@ +springfox.documentation.swagger.v2.path=/api-docs +server.contextPath=/v2 +server.port=8080 +spring.jackson.date-format=io.swagger.RFC3339DateFormat +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/.swagger-codegen-ignore b/samples/server/petstore/springboot-delegate/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/springboot-delegate/README.md b/samples/server/petstore/springboot-delegate/README.md new file mode 100644 index 00000000000..a2e8a9f7b84 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/README.md @@ -0,0 +1,18 @@ +# Swagger generated server + +Spring Boot Server + + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. +By using the [OpenAPI-Spec](https://github.com/swagger-api/swagger-core), you can easily generate a server stub. +This is an example of building a swagger-enabled server in Java using the SpringBoot framework. + +The underlying library integrating swagger to SpringBoot is [springfox](https://github.com/springfox/springfox) + +Start your server as an simple java application + +You can view the api documentation in swagger-ui by pointing to +http://localhost:8080/ + +Change default port value in application.properties \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/pom.xml b/samples/server/petstore/springboot-delegate/pom.xml new file mode 100644 index 00000000000..c9e1e77e74b --- /dev/null +++ b/samples/server/petstore/springboot-delegate/pom.xml @@ -0,0 +1,70 @@ + + 4.0.0 + io.swagger + swagger-spring + jar + swagger-spring + 1.0.0 + + 1.7 + ${java.version} + ${java.version} + 2.5.0 + + + org.springframework.boot + spring-boot-starter-parent + 1.3.5.RELEASE + + + src/main/java + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-tomcat + provided + + + + io.springfox + springfox-swagger2 + ${springfox-version} + + + io.springfox + springfox-swagger-ui + ${springfox-version} + + + + com.github.joschi.jackson + jackson-datatype-threetenbp + 2.6.4 + + + + javax.validation + validation-api + 1.1.0.Final + provided + + + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/RFC3339DateFormat.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/RFC3339DateFormat.java new file mode 100644 index 00000000000..0c3d276d2d4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/RFC3339DateFormat.java @@ -0,0 +1,20 @@ +package io.swagger; + +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; + +import java.text.FieldPosition; +import java.util.Date; + + +public class RFC3339DateFormat extends ISO8601DateFormat { + + // Same as ISO8601DateFormat but serializing milliseconds. + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + String value = ISO8601Utils.format(date, true); + toAppendTo.append(value); + return toAppendTo; + } + +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/Swagger2SpringBoot.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/Swagger2SpringBoot.java new file mode 100644 index 00000000000..c06fbae3c7a --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/Swagger2SpringBoot.java @@ -0,0 +1,36 @@ +package io.swagger; + +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.ExitCodeGenerator; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.ComponentScan; + +import springfox.documentation.swagger2.annotations.EnableSwagger2; + +@SpringBootApplication +@EnableSwagger2 +@ComponentScan(basePackages = "io.swagger") +public class Swagger2SpringBoot implements CommandLineRunner { + + @Override + public void run(String... arg0) throws Exception { + if (arg0.length > 0 && arg0[0].equals("exitcode")) { + throw new ExitException(); + } + } + + public static void main(String[] args) throws Exception { + new SpringApplication(Swagger2SpringBoot.class).run(args); + } + + class ExitException extends RuntimeException implements ExitCodeGenerator { + private static final long serialVersionUID = 1L; + + @Override + public int getExitCode() { + return 10; + } + + } +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiException.java new file mode 100644 index 00000000000..7fa61c50d24 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiOriginFilter.java new file mode 100644 index 00000000000..f0f62dc7206 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -0,0 +1,27 @@ +package io.swagger.api; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + + +public class ApiOriginFilter implements javax.servlet.Filter { + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } +} \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiResponseMessage.java new file mode 100644 index 00000000000..f03840f8e06 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -0,0 +1,69 @@ +package io.swagger.api; + +import javax.xml.bind.annotation.XmlTransient; + + +@javax.xml.bind.annotation.XmlRootElement +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApi.java new file mode 100644 index 00000000000..2feb92b12e5 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApi.java @@ -0,0 +1,78 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import javax.validation.constraints.*; + +@Api(value = "fake", description = "the fake API") +public interface FakeApi { + + @ApiOperation(value = "To test \"client\" model", notes = "To test \"client\" model", response = Client.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) + @RequestMapping(value = "/fake", + produces = { "application/json" }, + consumes = { "application/json" }, + method = RequestMethod.PATCH) + ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body); + + + @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ", response = Void.class, authorizations = { + @Authorization(value = "http_basic_test") + }, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/fake", + produces = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, + consumes = { "application/xml; charset=utf-8", "application/json; charset=utf-8" }, + method = RequestMethod.POST) + ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true ) @RequestPart(value="number", required=true) BigDecimal number, + @ApiParam(value = "None", required=true ) @RequestPart(value="_double", required=true) Double _double, + @ApiParam(value = "None", required=true ) @RequestPart(value="patternWithoutDelimiter", required=true) String patternWithoutDelimiter, + @ApiParam(value = "None", required=true ) @RequestPart(value="_byte", required=true) byte[] _byte, + @ApiParam(value = "None" ) @RequestPart(value="integer", required=false) Integer integer, + @ApiParam(value = "None" ) @RequestPart(value="int32", required=false) Integer int32, + @ApiParam(value = "None" ) @RequestPart(value="int64", required=false) Long int64, + @ApiParam(value = "None" ) @RequestPart(value="_float", required=false) Float _float, + @ApiParam(value = "None" ) @RequestPart(value="string", required=false) String string, + @ApiParam(value = "None" ) @RequestPart(value="binary", required=false) byte[] binary, + @ApiParam(value = "None" ) @RequestPart(value="date", required=false) LocalDate date, + @ApiParam(value = "None" ) @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, + @ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password, + @ApiParam(value = "None" ) @RequestPart(value="paramCallback", required=false) String paramCallback); + + + @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", response = Void.class, tags={ "fake", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid request", response = Void.class), + @ApiResponse(code = 404, message = "Not found", response = Void.class) }) + @RequestMapping(value = "/fake", + produces = { "*/*" }, + consumes = { "*/*" }, + method = RequestMethod.GET) + ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray, + @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, + @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, + @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiController.java new file mode 100644 index 00000000000..1162a0ba093 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiController.java @@ -0,0 +1,69 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import javax.validation.constraints.*; + +@Controller +public class FakeApiController implements FakeApi { + private final FakeApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + FakeApiController(FakeApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { + // do some magic! + return delegate.testClientModel(body); + } + + public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true ) @RequestPart(value="number", required=true) BigDecimal number, + @ApiParam(value = "None", required=true ) @RequestPart(value="_double", required=true) Double _double, + @ApiParam(value = "None", required=true ) @RequestPart(value="patternWithoutDelimiter", required=true) String patternWithoutDelimiter, + @ApiParam(value = "None", required=true ) @RequestPart(value="_byte", required=true) byte[] _byte, + @ApiParam(value = "None" ) @RequestPart(value="integer", required=false) Integer integer, + @ApiParam(value = "None" ) @RequestPart(value="int32", required=false) Integer int32, + @ApiParam(value = "None" ) @RequestPart(value="int64", required=false) Long int64, + @ApiParam(value = "None" ) @RequestPart(value="_float", required=false) Float _float, + @ApiParam(value = "None" ) @RequestPart(value="string", required=false) String string, + @ApiParam(value = "None" ) @RequestPart(value="binary", required=false) byte[] binary, + @ApiParam(value = "None" ) @RequestPart(value="date", required=false) LocalDate date, + @ApiParam(value = "None" ) @RequestPart(value="dateTime", required=false) OffsetDateTime dateTime, + @ApiParam(value = "None" ) @RequestPart(value="password", required=false) String password, + @ApiParam(value = "None" ) @RequestPart(value="paramCallback", required=false) String paramCallback) { + // do some magic! + return delegate.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + public ResponseEntity testEnumParameters(@ApiParam(value = "Form parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestPart(value="enumFormStringArray", required=false) List enumFormStringArray, + @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, + @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, + @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { + // do some magic! + return delegate.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + } + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiDelegate.java new file mode 100644 index 00000000000..af20d27b4a1 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/FakeApiDelegate.java @@ -0,0 +1,57 @@ +package io.swagger.api; + +import java.math.BigDecimal; +import io.swagger.model.Client; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link FakeApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link FakeApiController}. + */ + +public interface FakeApiDelegate { + + /** + * @see FakeApi#testClientModel + */ + ResponseEntity testClientModel(Client body); + + /** + * @see FakeApi#testEndpointParameters + */ + ResponseEntity testEndpointParameters(BigDecimal number, + Double _double, + String patternWithoutDelimiter, + byte[] _byte, + Integer integer, + Integer int32, + Long int64, + Float _float, + String string, + byte[] binary, + LocalDate date, + OffsetDateTime dateTime, + String password, + String paramCallback); + + /** + * @see FakeApi#testEnumParameters + */ + ResponseEntity testEnumParameters(List enumFormStringArray, + String enumFormString, + List enumHeaderStringArray, + String enumHeaderString, + List enumQueryStringArray, + String enumQueryString, + Integer enumQueryInteger, + Double enumQueryDouble); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/NotFoundException.java new file mode 100644 index 00000000000..295109d7fc4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/NotFoundException.java @@ -0,0 +1,10 @@ +package io.swagger.api; + + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApi.java new file mode 100644 index 00000000000..dcd4a0f8b8c --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApi.java @@ -0,0 +1,147 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import javax.validation.constraints.*; + +@Api(value = "pet", description = "the pet API") +public interface PetApi { + + @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, 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", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" }, + method = RequestMethod.POST) + ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + + + @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, 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", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + + + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", 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", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByStatus", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity> findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); + + + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", 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", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) + @RequestMapping(value = "/pet/findByTags", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity> findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + + + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { + @Authorization(value = "api_key") + }, tags={ "pet", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Pet.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId); + + + @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, 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", }) + @ApiResponses(value = { + @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) }) + @RequestMapping(value = "/pet", + produces = { "application/xml", "application/json" }, + consumes = { "application/json", "application/xml" }, + method = RequestMethod.PUT) + ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body); + + + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, 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", }) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) + @RequestMapping(value = "/pet/{petId}", + produces = { "application/xml", "application/json" }, + consumes = { "application/x-www-form-urlencoded" }, + method = RequestMethod.POST) + ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status); + + + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, 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", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) + @RequestMapping(value = "/pet/{petId}/uploadImage", + produces = { "application/json" }, + consumes = { "multipart/form-data" }, + method = RequestMethod.POST) + ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiController.java new file mode 100644 index 00000000000..03c23df7b47 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiController.java @@ -0,0 +1,78 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import javax.validation.constraints.*; + +@Controller +public class PetApiController implements PetApi { + private final PetApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + PetApiController(PetApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return delegate.addPet(body); + } + + public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + // do some magic! + return delegate.deletePet(petId, apiKey); + } + + public ResponseEntity> findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { + // do some magic! + return delegate.findPetsByStatus(status); + } + + public ResponseEntity> findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + // do some magic! + return delegate.findPetsByTags(tags); + } + + public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId) { + // do some magic! + return delegate.getPetById(petId); + } + + public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { + // do some magic! + return delegate.updatePet(body); + } + + public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, + @ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) { + // do some magic! + return delegate.updatePetWithForm(petId, name, status); + } + + public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile file) { + // do some magic! + return delegate.uploadFile(petId, additionalMetadata, file); + } + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiDelegate.java new file mode 100644 index 00000000000..f028b3c2e77 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/PetApiDelegate.java @@ -0,0 +1,66 @@ +package io.swagger.api; + +import java.io.File; +import io.swagger.model.ModelApiResponse; +import io.swagger.model.Pet; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link PetApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link PetApiController}. + */ + +public interface PetApiDelegate { + + /** + * @see PetApi#addPet + */ + ResponseEntity addPet(Pet body); + + /** + * @see PetApi#deletePet + */ + ResponseEntity deletePet(Long petId, + String apiKey); + + /** + * @see PetApi#findPetsByStatus + */ + ResponseEntity> findPetsByStatus(List status); + + /** + * @see PetApi#findPetsByTags + */ + ResponseEntity> findPetsByTags(List tags); + + /** + * @see PetApi#getPetById + */ + ResponseEntity getPetById(Long petId); + + /** + * @see PetApi#updatePet + */ + ResponseEntity updatePet(Pet body); + + /** + * @see PetApi#updatePetWithForm + */ + ResponseEntity updatePetWithForm(Long petId, + String name, + String status); + + /** + * @see PetApi#uploadFile + */ + ResponseEntity uploadFile(Long petId, + String additionalMetadata, + MultipartFile file); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApi.java new file mode 100644 index 00000000000..47c2c561ff1 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApi.java @@ -0,0 +1,64 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import javax.validation.constraints.*; + +@Api(value = "store", description = "the store API") +public interface StoreApi { + + @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", response = Void.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), + @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId); + + + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) + @RequestMapping(value = "/store/inventory", + produces = { "application/json" }, + method = RequestMethod.GET) + ResponseEntity> getInventory(); + + + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) + @RequestMapping(value = "/store/order/{orderId}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + + + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Order.class), + @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) + @RequestMapping(value = "/store/order", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiController.java new file mode 100644 index 00000000000..050a9d7de74 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiController.java @@ -0,0 +1,52 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import javax.validation.constraints.*; + +@Controller +public class StoreApiController implements StoreApi { + private final StoreApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + StoreApiController(StoreApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { + // do some magic! + return delegate.deleteOrder(orderId); + } + + public ResponseEntity> getInventory() { + // do some magic! + return delegate.getInventory(); + } + + public ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + // do some magic! + return delegate.getOrderById(orderId); + } + + public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body) { + // do some magic! + return delegate.placeOrder(body); + } + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiDelegate.java new file mode 100644 index 00000000000..ddf2901926a --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/StoreApiDelegate.java @@ -0,0 +1,40 @@ +package io.swagger.api; + +import java.util.Map; +import io.swagger.model.Order; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link StoreApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link StoreApiController}. + */ + +public interface StoreApiDelegate { + + /** + * @see StoreApi#deleteOrder + */ + ResponseEntity deleteOrder(String orderId); + + /** + * @see StoreApi#getInventory + */ + ResponseEntity> getInventory(); + + /** + * @see StoreApi#getOrderById + */ + ResponseEntity getOrderById(Long orderId); + + /** + * @see StoreApi#placeOrder + */ + ResponseEntity placeOrder(Order body); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApi.java new file mode 100644 index 00000000000..2d15d4b071a --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApi.java @@ -0,0 +1,101 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import javax.validation.constraints.*; + +@Api(value = "user", description = "the user API") +public interface UserApi { + + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithArray", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + + + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/createWithList", + produces = { "application/xml", "application/json" }, + method = RequestMethod.POST) + ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body); + + + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.DELETE) + ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username); + + + @ApiOperation(value = "Get user by user name", notes = "", response = User.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = User.class), + @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + @ApiResponse(code = 404, message = "User not found", response = User.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username); + + + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = String.class), + @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) + @RequestMapping(value = "/user/login", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity loginUser( @NotNull @ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + + + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @RequestMapping(value = "/user/logout", + produces = { "application/xml", "application/json" }, + method = RequestMethod.GET) + ResponseEntity logoutUser(); + + + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class, tags={ "user", }) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), + @ApiResponse(code = 404, message = "User not found", response = Void.class) }) + @RequestMapping(value = "/user/{username}", + produces = { "application/xml", "application/json" }, + method = RequestMethod.PUT) + ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiController.java new file mode 100644 index 00000000000..785e28f4509 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiController.java @@ -0,0 +1,74 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RequestPart; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +import javax.validation.constraints.*; + +@Controller +public class UserApiController implements UserApi { + private final UserApiDelegate delegate; + + @org.springframework.beans.factory.annotation.Autowired + UserApiController(UserApiDelegate delegate) { + this.delegate = delegate; + } + + + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { + // do some magic! + return delegate.createUser(body); + } + + public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return delegate.createUsersWithArrayInput(body); + } + + public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body) { + // do some magic! + return delegate.createUsersWithListInput(body); + } + + public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) { + // do some magic! + return delegate.deleteUser(username); + } + + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) { + // do some magic! + return delegate.getUserByName(username); + } + + public ResponseEntity loginUser( @NotNull @ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + // do some magic! + return delegate.loginUser(username, password); + } + + public ResponseEntity logoutUser() { + // do some magic! + return delegate.logoutUser(); + } + + public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, + @ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body) { + // do some magic! + return delegate.updateUser(username, body); + } + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiDelegate.java new file mode 100644 index 00000000000..7c2e86e1a95 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/api/UserApiDelegate.java @@ -0,0 +1,62 @@ +package io.swagger.api; + +import java.util.List; +import io.swagger.model.User; + +import io.swagger.annotations.*; +import org.springframework.http.ResponseEntity; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +/** + * A delegate to be called by the {@link UserApiController}}. + * Should be implemented as a controller but without the {@link org.springframework.stereotype.Controller} annotation. + * Instead, use spring to autowire this class into the {@link UserApiController}. + */ + +public interface UserApiDelegate { + + /** + * @see UserApi#createUser + */ + ResponseEntity createUser(User body); + + /** + * @see UserApi#createUsersWithArrayInput + */ + ResponseEntity createUsersWithArrayInput(List body); + + /** + * @see UserApi#createUsersWithListInput + */ + ResponseEntity createUsersWithListInput(List body); + + /** + * @see UserApi#deleteUser + */ + ResponseEntity deleteUser(String username); + + /** + * @see UserApi#getUserByName + */ + ResponseEntity getUserByName(String username); + + /** + * @see UserApi#loginUser + */ + ResponseEntity loginUser(String username, + String password); + + /** + * @see UserApi#logoutUser + */ + ResponseEntity logoutUser(); + + /** + * @see UserApi#updateUser + */ + ResponseEntity updateUser(String username, + User body); + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/HomeController.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/HomeController.java new file mode 100644 index 00000000000..d195523c1d3 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/HomeController.java @@ -0,0 +1,16 @@ +package io.swagger.configuration; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +/** + * Home redirection to swagger api documentation + */ +@Controller +public class HomeController { + @RequestMapping(value = "/") + public String index() { + System.out.println("swagger-ui.html"); + return "redirect:swagger-ui.html"; + } +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java new file mode 100644 index 00000000000..6a7e8c14be1 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java @@ -0,0 +1,40 @@ +package io.swagger.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.service.Contact; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; + + +@Configuration +public class SwaggerDocumentationConfig { + + ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Swagger Petstore") + .description("This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\") + .license("Apache 2.0") + .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") + .termsOfServiceUrl("") + .version("1.0.0") + .contact(new Contact("","", "apiteam@swagger.io")) + .build(); + } + + @Bean + public Docket customImplementation(){ + return new Docket(DocumentationType.SWAGGER_2) + .select() + .apis(RequestHandlerSelectors.basePackage("io.swagger.api")) + .build() + .directModelSubstitute(org.threeten.bp.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(org.threeten.bp.OffsetDateTime.class, java.util.Date.class) + .apiInfo(apiInfo()); + } + +} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..81535e041fa --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -0,0 +1,110 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; +/** + * AdditionalPropertiesClass + */ + +public class AdditionalPropertiesClass { + @JsonProperty("map_property") + private Map mapProperty = new HashMap(); + + @JsonProperty("map_of_map_property") + private Map> mapOfMapProperty = new HashMap>(); + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @ApiModelProperty(value = "") + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @ApiModelProperty(value = "") + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Animal.java new file mode 100644 index 00000000000..a218f0b5542 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Animal.java @@ -0,0 +1,105 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonSubTypes; +import com.fasterxml.jackson.annotation.JsonTypeInfo; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Animal + */ +@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"), +}) + +public class Animal { + @JsonProperty("className") + private String className = null; + + @JsonProperty("color") + private String color = "red"; + + public Animal className(String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public Animal color(String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @ApiModelProperty(value = "") + public String getColor() { + return color; + } + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AnimalFarm.java new file mode 100644 index 00000000000..33dc04699af --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/AnimalFarm.java @@ -0,0 +1,50 @@ +package io.swagger.model; + +import java.util.Objects; +import io.swagger.model.Animal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * AnimalFarm + */ + +public class AnimalFarm extends ArrayList { + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return true; + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnimalFarm {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..3be691e4d95 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * ArrayOfArrayOfNumberOnly + */ + +public class ArrayOfArrayOfNumberOnly { + @JsonProperty("ArrayArrayNumber") + private List> arrayArrayNumber = new ArrayList>(); + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..12196897345 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -0,0 +1,82 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * ArrayOfNumberOnly + */ + +public class ArrayOfNumberOnly { + @JsonProperty("ArrayNumber") + private List arrayNumber = new ArrayList(); + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @ApiModelProperty(value = "") + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayTest.java new file mode 100644 index 00000000000..a26a1600287 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ArrayTest.java @@ -0,0 +1,138 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.ReadOnlyFirst; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * ArrayTest + */ + +public class ArrayTest { + @JsonProperty("array_of_string") + private List arrayOfString = new ArrayList(); + + @JsonProperty("array_array_of_integer") + private List> arrayArrayOfInteger = new ArrayList>(); + + @JsonProperty("array_array_of_model") + private List> arrayArrayOfModel = new ArrayList>(); + + public ArrayTest arrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @ApiModelProperty(value = "") + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @ApiModelProperty(value = "") + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Capitalization.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..d7ad5642ccf --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Capitalization.java @@ -0,0 +1,189 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Cat.java new file mode 100644 index 00000000000..747e5dc0c7e --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Cat.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import javax.validation.constraints.*; +/** + * Cat + */ + +public class Cat extends Animal { + @JsonProperty("declawed") + private Boolean declawed = null; + + public Cat declawed(Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @ApiModelProperty(value = "") + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Category.java new file mode 100644 index 00000000000..9629da6500e --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Category.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Category + */ + +public class Category { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ClassModel.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ClassModel.java new file mode 100644 index 00000000000..d69acffefa8 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ClassModel.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") + +public class ClassModel { + @JsonProperty("_class") + private String propertyClass = null; + + public ClassModel propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Client.java new file mode 100644 index 00000000000..f9cec5a225e --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Client.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Client + */ + +public class Client { + @JsonProperty("client") + private String client = null; + + public Client client(String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @ApiModelProperty(value = "") + public String getClient() { + return client; + } + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Dog.java new file mode 100644 index 00000000000..9057e840fc3 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Dog.java @@ -0,0 +1,76 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import javax.validation.constraints.*; +/** + * Dog + */ + +public class Dog extends Animal { + @JsonProperty("breed") + private String breed = null; + + public Dog breed(String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @ApiModelProperty(value = "") + public String getBreed() { + return breed; + } + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumArrays.java new file mode 100644 index 00000000000..97ab6f6410e --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumArrays.java @@ -0,0 +1,167 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * EnumArrays + */ + +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static JustSymbolEnum fromValue(String text) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("just_symbol") + private JustSymbolEnum justSymbol = null; + + /** + * Gets or Sets arrayEnum + */ + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayEnumEnum fromValue(String text) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("array_enum") + private List arrayEnum = new ArrayList(); + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @ApiModelProperty(value = "") + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + public EnumArrays arrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @ApiModelProperty(value = "") + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumClass.java new file mode 100644 index 00000000000..cdfc0933c3e --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumClass.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets EnumClass + */ +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumClass fromValue(String text) { + for (EnumClass b : EnumClass.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumTest.java new file mode 100644 index 00000000000..9f2a0275a6a --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/EnumTest.java @@ -0,0 +1,240 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.OuterEnum; +import javax.validation.constraints.*; +/** + * EnumTest + */ + +public class EnumTest { + /** + * Gets or Sets enumString + */ + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumStringEnum fromValue(String text) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_string") + private EnumStringEnum enumString = null; + + /** + * Gets or Sets enumInteger + */ + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumIntegerEnum fromValue(String text) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_integer") + private EnumIntegerEnum enumInteger = null; + + /** + * Gets or Sets enumNumber + */ + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static EnumNumberEnum fromValue(String text) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("enum_number") + private EnumNumberEnum enumNumber = null; + + @JsonProperty("outerEnum") + private OuterEnum outerEnum = null; + + public EnumTest enumString(EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @ApiModelProperty(value = "") + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @ApiModelProperty(value = "") + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @ApiModelProperty(value = "") + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + public EnumTest outerEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @ApiModelProperty(value = "") + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumInteger, enumNumber, outerEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/FormatTest.java new file mode 100644 index 00000000000..342ebe05be6 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/FormatTest.java @@ -0,0 +1,380 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import java.util.UUID; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import javax.validation.constraints.*; +/** + * FormatTest + */ + +public class FormatTest { + @JsonProperty("integer") + private Integer integer = null; + + @JsonProperty("int32") + private Integer int32 = null; + + @JsonProperty("int64") + private Long int64 = null; + + @JsonProperty("number") + private BigDecimal number = null; + + @JsonProperty("float") + private Float _float = null; + + @JsonProperty("double") + private Double _double = null; + + @JsonProperty("string") + private String string = null; + + @JsonProperty("byte") + private byte[] _byte = null; + + @JsonProperty("binary") + private byte[] binary = null; + + @JsonProperty("date") + private LocalDate date = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("uuid") + private UUID uuid = null; + + @JsonProperty("password") + private String password = null; + + public FormatTest integer(Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + @ApiModelProperty(value = "") + @Min(10) + @Max(100) + public Integer getInteger() { + return integer; + } + + public void setInteger(Integer integer) { + this.integer = integer; + } + + public FormatTest int32(Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + @ApiModelProperty(value = "") + @Min(20) + @Max(200) + public Integer getInt32() { + return int32; + } + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + public FormatTest int64(Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @ApiModelProperty(value = "") + public Long getInt64() { + return int64; + } + + public void setInt64(Long int64) { + this.int64 = int64; + } + + public FormatTest number(BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") + public BigDecimal getNumber() { + return number; + } + + public void setNumber(BigDecimal number) { + this.number = number; + } + + public FormatTest _float(Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @ApiModelProperty(value = "") + @DecimalMin("54.3") + @DecimalMax("987.6") + public Float getFloat() { + return _float; + } + + public void setFloat(Float _float) { + this._float = _float; + } + + public FormatTest _double(Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @ApiModelProperty(value = "") + @DecimalMin("67.8") + @DecimalMax("123.4") + public Double getDouble() { + return _double; + } + + public void setDouble(Double _double) { + this._double = _double; + } + + public FormatTest string(String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @ApiModelProperty(value = "") + @Pattern(regexp="/[a-z]/i") + public String getString() { + return string; + } + + public void setString(String string) { + this.string = string; + } + + public FormatTest _byte(byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public byte[] getByte() { + return _byte; + } + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + public FormatTest binary(byte[] binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @ApiModelProperty(value = "") + public byte[] getBinary() { + return binary; + } + + public void setBinary(byte[] binary) { + this.binary = binary; + } + + public FormatTest date(LocalDate date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public LocalDate getDate() { + return date; + } + + public void setDate(LocalDate date) { + this.date = date; + } + + public FormatTest dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public FormatTest uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public FormatTest password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + @Size(min=10,max=64) + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..a26492e4912 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * HasOnlyReadOnly + */ + +public class HasOnlyReadOnly { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("foo") + private String foo = null; + + public HasOnlyReadOnly bar(String bar) { + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(readOnly = true, value = "") + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + public HasOnlyReadOnly foo(String foo) { + this.foo = foo; + return this; + } + + /** + * Get foo + * @return foo + **/ + @ApiModelProperty(readOnly = true, value = "") + public String getFoo() { + return foo; + } + + public void setFoo(String foo) { + this.foo = foo; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MapTest.java new file mode 100644 index 00000000000..9a0566a8dd1 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MapTest.java @@ -0,0 +1,142 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.validation.constraints.*; +/** + * MapTest + */ + +public class MapTest { + @JsonProperty("map_map_of_string") + private Map> mapMapOfString = new HashMap>(); + + /** + * Gets or Sets inner + */ + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static InnerEnum fromValue(String text) { + for (InnerEnum b : InnerEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("map_of_enum_string") + private Map mapOfEnumString = new HashMap(); + + public MapTest mapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @ApiModelProperty(value = "") + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + public MapTest mapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @ApiModelProperty(value = "") + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..19eb9f2b139 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,131 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Animal; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.threeten.bp.OffsetDateTime; +import javax.validation.constraints.*; +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ + +public class MixedPropertiesAndAdditionalPropertiesClass { + @JsonProperty("uuid") + private UUID uuid = null; + + @JsonProperty("dateTime") + private OffsetDateTime dateTime = null; + + @JsonProperty("map") + private Map map = new HashMap(); + + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @ApiModelProperty(value = "") + public UUID getUuid() { + return uuid; + } + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @ApiModelProperty(value = "") + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Model200Response.java new file mode 100644 index 00000000000..4d47f6c03c9 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Model200Response.java @@ -0,0 +1,98 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") + +public class Model200Response { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("class") + private String propertyClass = null; + + public Model200Response name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Model200Response propertyClass(String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @ApiModelProperty(value = "") + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200Response = (Model200Response) o; + return Objects.equals(this.name, _200Response.name) && + Objects.equals(this.propertyClass, _200Response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..36da9b20d9d --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,120 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * ModelApiResponse + */ + +public class ModelApiResponse { + @JsonProperty("code") + private Integer code = null; + + @JsonProperty("type") + private String type = null; + + @JsonProperty("message") + private String message = null; + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @ApiModelProperty(value = "") + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelReturn.java new file mode 100644 index 00000000000..7ffc24a0144 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ModelReturn.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") + +public class ModelReturn { + @JsonProperty("return") + private Integer _return = null; + + public ModelReturn _return(Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @ApiModelProperty(value = "") + public Integer getReturn() { + return _return; + } + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Name.java new file mode 100644 index 00000000000..953199166ff --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Name.java @@ -0,0 +1,145 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") + +public class Name { + @JsonProperty("name") + private Integer name = null; + + @JsonProperty("snake_case") + private Integer snakeCase = null; + + @JsonProperty("property") + private String property = null; + + @JsonProperty("123Number") + private Integer _123Number = null; + + public Name name(Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public Integer getName() { + return name; + } + + public void setName(Integer name) { + this.name = name; + } + + public Name snakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + return this; + } + + /** + * Get snakeCase + * @return snakeCase + **/ + @ApiModelProperty(readOnly = true, value = "") + public Integer getSnakeCase() { + return snakeCase; + } + + public void setSnakeCase(Integer snakeCase) { + this.snakeCase = snakeCase; + } + + public Name property(String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @ApiModelProperty(value = "") + public String getProperty() { + return property; + } + + public void setProperty(String property) { + this.property = property; + } + + public Name _123Number(Integer _123Number) { + this._123Number = _123Number; + return this; + } + + /** + * Get _123Number + * @return _123Number + **/ + @ApiModelProperty(readOnly = true, value = "") + public Integer get123Number() { + return _123Number; + } + + public void set123Number(Integer _123Number) { + this._123Number = _123Number; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123Number, name._123Number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123Number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123Number: ").append(toIndentedString(_123Number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/NumberOnly.java new file mode 100644 index 00000000000..e6dbf3139e2 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/NumberOnly.java @@ -0,0 +1,75 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import javax.validation.constraints.*; +/** + * NumberOnly + */ + +public class NumberOnly { + @JsonProperty("JustNumber") + private BigDecimal justNumber = null; + + public NumberOnly justNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @ApiModelProperty(value = "") + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Order.java new file mode 100644 index 00000000000..c5381d2fa7e --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Order.java @@ -0,0 +1,224 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import org.threeten.bp.OffsetDateTime; +import javax.validation.constraints.*; +/** + * Order + */ + +public class Order { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("petId") + private Long petId = null; + + @JsonProperty("quantity") + private Integer quantity = null; + + @JsonProperty("shipDate") + private OffsetDateTime shipDate = null; + + /** + * Order Status + */ + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + @JsonProperty("complete") + private Boolean complete = false; + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order shipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @ApiModelProperty(value = "") + public OffsetDateTime getShipDate() { + return shipDate; + } + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/OuterEnum.java new file mode 100644 index 00000000000..5f0075e4457 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/OuterEnum.java @@ -0,0 +1,41 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonValue; +import javax.validation.constraints.*; +import com.fasterxml.jackson.annotation.JsonCreator; + +/** + * Gets or Sets OuterEnum + */ +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OuterEnum fromValue(String text) { + for (OuterEnum b : OuterEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Pet.java new file mode 100644 index 00000000000..9adc708de71 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Pet.java @@ -0,0 +1,239 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.ArrayList; +import java.util.List; +import javax.validation.constraints.*; +/** + * Pet + */ + +public class Pet { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("category") + private Category category = null; + + @JsonProperty("name") + private String name = null; + + @JsonProperty("photoUrls") + private List photoUrls = new ArrayList(); + + @JsonProperty("tags") + private List tags = new ArrayList(); + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + @JsonValue + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String text) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(text)) { + return b; + } + } + return null; + } + } + + @JsonProperty("status") + private StatusEnum status = null; + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @ApiModelProperty(required = true, value = "") + @NotNull + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + + public void setTags(List tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..47700659fd2 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * ReadOnlyFirst + */ + +public class ReadOnlyFirst { + @JsonProperty("bar") + private String bar = null; + + @JsonProperty("baz") + private String baz = null; + + public ReadOnlyFirst bar(String bar) { + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + **/ + @ApiModelProperty(readOnly = true, value = "") + public String getBar() { + return bar; + } + + public void setBar(String bar) { + this.bar = bar; + } + + public ReadOnlyFirst baz(String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @ApiModelProperty(value = "") + public String getBaz() { + return baz; + } + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/SpecialModelName.java new file mode 100644 index 00000000000..880d70599b0 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/SpecialModelName.java @@ -0,0 +1,74 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * SpecialModelName + */ + +public class SpecialModelName { + @JsonProperty("$special[property.name]") + private Long specialPropertyName = null; + + public SpecialModelName specialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + return this; + } + + /** + * Get specialPropertyName + * @return specialPropertyName + **/ + @ApiModelProperty(value = "") + public Long getSpecialPropertyName() { + return specialPropertyName; + } + + public void setSpecialPropertyName(Long specialPropertyName) { + this.specialPropertyName = specialPropertyName; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.specialPropertyName, specialModelName.specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash(specialPropertyName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + + sb.append(" specialPropertyName: ").append(toIndentedString(specialPropertyName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Tag.java new file mode 100644 index 00000000000..298085317a4 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/Tag.java @@ -0,0 +1,97 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Tag + */ + +public class Tag { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("name") + private String name = null; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/User.java b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/User.java new file mode 100644 index 00000000000..8e40f7e0594 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/java/io/swagger/model/User.java @@ -0,0 +1,235 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * User + */ + +public class User { + @JsonProperty("id") + private Long id = null; + + @JsonProperty("username") + private String username = null; + + @JsonProperty("firstName") + private String firstName = null; + + @JsonProperty("lastName") + private String lastName = null; + + @JsonProperty("email") + private String email = null; + + @JsonProperty("password") + private String password = null; + + @JsonProperty("phone") + private String phone = null; + + @JsonProperty("userStatus") + private Integer userStatus = null; + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + + public void setPhone(String phone) { + this.phone = phone; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot-delegate/src/main/resources/application.properties b/samples/server/petstore/springboot-delegate/src/main/resources/application.properties new file mode 100644 index 00000000000..a2ef8627027 --- /dev/null +++ b/samples/server/petstore/springboot-delegate/src/main/resources/application.properties @@ -0,0 +1,5 @@ +springfox.documentation.swagger.v2.path=/api-docs +server.contextPath=/v2 +server.port=8080 +spring.jackson.date-format=io.swagger.RFC3339DateFormat +spring.jackson.serialization.WRITE_DATES_AS_TIMESTAMPS=false \ No newline at end of file diff --git a/samples/server/petstore/springboot/pom.xml b/samples/server/petstore/springboot/pom.xml index a61dac493d7..c9e1e77e74b 100644 --- a/samples/server/petstore/springboot/pom.xml +++ b/samples/server/petstore/springboot/pom.xml @@ -59,5 +59,12 @@ jackson-datatype-threetenbp 2.6.4 + + + javax.validation + validation-api + 1.1.0.Final + provided + - \ No newline at end of file + diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java index 867335a3fb6..2feb92b12e5 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApi.java @@ -17,7 +17,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "fake", description = "the fake API") public interface FakeApi { @@ -70,9 +70,9 @@ public interface FakeApi { @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java index 70fb75199b2..c984ea73b68 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeApiController.java @@ -19,11 +19,13 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Controller public class FakeApiController implements FakeApi { + + public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -51,9 +53,9 @@ public class FakeApiController implements FakeApi { @ApiParam(value = "Form parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestPart(value="enumFormString", required=false) String enumFormString, @ApiParam(value = "Header parameter enum test (string array)" , allowableValues="GREATER_THAN, DOLLAR") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray, @ApiParam(value = "Header parameter enum test (string)" , allowableValues="_ABC, _EFG, _XYZ_", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString, - @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, - @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, - @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, + @ApiParam(value = "Query parameter enum test (string array)", allowableValues = "GREATER_THAN, DOLLAR") @RequestParam(value = "enumQueryStringArray", required = false) List enumQueryStringArray, + @ApiParam(value = "Query parameter enum test (string)", allowableValues = "_ABC, _EFG, _XYZ_", defaultValue = "-efg") @RequestParam(value = "enumQueryString", required = false, defaultValue="-efg") String enumQueryString, + @ApiParam(value = "Query parameter enum test (double)") @RequestParam(value = "enumQueryInteger", required = false) Integer enumQueryInteger, @ApiParam(value = "Query parameter enum test (double)" ) @RequestPart(value="enumQueryDouble", required=false) Double enumQueryDouble) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApi.java index 628380949f8..bf962faa6fd 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApi.java @@ -14,7 +14,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApiController.java index 8b527aa9a9d..60a2b4d44ce 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/FakeClassnameTestApiController.java @@ -16,11 +16,13 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Controller public class FakeClassnameTestApiController implements FakeClassnameTestApi { + + public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @RequestBody Client body) { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java index 7d48cfb31c9..dcd4a0f8b8c 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java @@ -16,7 +16,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "pet", description = "the pet API") public interface PetApi { @@ -63,7 +63,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByStatus", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); + ResponseEntity> findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status); @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @@ -78,7 +78,7 @@ public interface PetApi { @RequestMapping(value = "/pet/findByTags", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); + ResponseEntity> findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags); @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java index edf1abc3ead..847b24e1a80 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApiController.java @@ -18,11 +18,13 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Controller public class PetApiController implements PetApi { + + public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body) { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -34,12 +36,12 @@ public class PetApiController implements PetApi { return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { + public ResponseEntity> findPetsByStatus( @NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "AVAILABLE, PENDING, SOLD") @RequestParam(value = "status", required = true) List status) { // do some magic! return new ResponseEntity>(HttpStatus.OK); } - public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { + public ResponseEntity> findPetsByTags( @NotNull @ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags) { // do some magic! return new ResponseEntity>(HttpStatus.OK); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java index f5526de9862..47c2c561ff1 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java @@ -15,7 +15,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "store", description = "the store API") public interface StoreApi { @@ -49,7 +49,7 @@ public interface StoreApi { @RequestMapping(value = "/store/order/{orderId}", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); + ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId); @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class, tags={ "store", }) diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java index bd582ae1a94..97a1b7e5129 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApiController.java @@ -17,11 +17,13 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Controller public class StoreApiController implements StoreApi { + + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -32,7 +34,7 @@ public class StoreApiController implements StoreApi { return new ResponseEntity>(HttpStatus.OK); } - public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { + public ResponseEntity getOrderById( @Min(1) @Max(5)@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId) { // do some magic! return new ResponseEntity(HttpStatus.OK); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java index c31b5a143ee..2d15d4b071a 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java @@ -15,7 +15,7 @@ import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Api(value = "user", description = "the user API") public interface UserApi { @@ -75,8 +75,8 @@ public interface UserApi { @RequestMapping(value = "/user/login", produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); + ResponseEntity loginUser( @NotNull @ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password); @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class, tags={ "user", }) diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java index f9f6fbd25a4..c321750e95e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApiController.java @@ -17,11 +17,13 @@ import org.springframework.web.multipart.MultipartFile; import java.util.List; - +import javax.validation.constraints.*; @Controller public class UserApiController implements UserApi { + + public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body) { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -47,8 +49,8 @@ public class UserApiController implements UserApi { return new ResponseEntity(HttpStatus.OK); } - public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, - @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { + public ResponseEntity loginUser( @NotNull @ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username, + @NotNull @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password) { // do some magic! return new ResponseEntity(HttpStatus.OK); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/AdditionalPropertiesClass.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/AdditionalPropertiesClass.java index f74f7d3d882..81535e041fa 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/AdditionalPropertiesClass.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; - +import javax.validation.constraints.*; /** * AdditionalPropertiesClass */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java index 60aaf82231f..a218f0b5542 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Animal.java @@ -7,10 +7,15 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Animal */ +@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"), +}) public class Animal { @JsonProperty("className") @@ -29,6 +34,7 @@ public class Animal { * @return className **/ @ApiModelProperty(required = true, value = "") + @NotNull public String getClassName() { return className; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/AnimalFarm.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/AnimalFarm.java index c2b0084d9cd..33dc04699af 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/AnimalFarm.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/AnimalFarm.java @@ -4,7 +4,7 @@ import java.util.Objects; import io.swagger.model.Animal; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * AnimalFarm */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java index 803eb69e16a..3be691e4d95 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfArrayOfNumberOnly.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * ArrayOfArrayOfNumberOnly */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfNumberOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfNumberOnly.java index bebc2470927..12196897345 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayOfNumberOnly.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * ArrayOfNumberOnly */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayTest.java index 19464a99acd..a26a1600287 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ArrayTest.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.model.ReadOnlyFirst; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * ArrayTest */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Capitalization.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Capitalization.java new file mode 100644 index 00000000000..d7ad5642ccf --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Capitalization.java @@ -0,0 +1,189 @@ +package io.swagger.model; + +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import javax.validation.constraints.*; +/** + * Capitalization + */ + +public class Capitalization { + @JsonProperty("smallCamel") + private String smallCamel = null; + + @JsonProperty("CapitalCamel") + private String capitalCamel = null; + + @JsonProperty("small_Snake") + private String smallSnake = null; + + @JsonProperty("Capital_Snake") + private String capitalSnake = null; + + @JsonProperty("SCA_ETH_Flow_Points") + private String scAETHFlowPoints = null; + + @JsonProperty("ATT_NAME") + private String ATT_NAME = null; + + public Capitalization smallCamel(String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @ApiModelProperty(value = "") + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + public Capitalization capitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @ApiModelProperty(value = "") + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + public Capitalization smallSnake(String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @ApiModelProperty(value = "") + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + public Capitalization capitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @ApiModelProperty(value = "") + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @ApiModelProperty(value = "") + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + public Capitalization ATT_NAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @ApiModelProperty(value = "Name of the pet ") + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(java.lang.Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(java.lang.Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Cat.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Cat.java index 95bea570923..747e5dc0c7e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Cat.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Cat.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Animal; - +import javax.validation.constraints.*; /** * Cat */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java index ba1ecfdb2b8..9629da6500e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Category */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ClassModel.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ClassModel.java index 16c743e4f32..d69acffefa8 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ClassModel.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ClassModel.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Model for testing model with \"_class\" property */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Client.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Client.java index fcb2b0a8340..f9cec5a225e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Client.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Client.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Client */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Dog.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Dog.java index f8072688756..9057e840fc3 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Dog.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Dog.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.Animal; - +import javax.validation.constraints.*; /** * Dog */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumArrays.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumArrays.java index 959b35e6b13..97ab6f6410e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumArrays.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumArrays.java @@ -8,7 +8,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * EnumArrays */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumClass.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumClass.java index d8ac42c4872..cdfc0933c3e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumClass.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumClass.java @@ -2,7 +2,7 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; - +import javax.validation.constraints.*; import com.fasterxml.jackson.annotation.JsonCreator; /** diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java index 66e7c1ffe5a..9f2a0275a6a 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/EnumTest.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import io.swagger.model.OuterEnum; - +import javax.validation.constraints.*; /** * EnumTest */ @@ -19,7 +19,9 @@ public class EnumTest { public enum EnumStringEnum { UPPER("UPPER"), - LOWER("lower"); + LOWER("lower"), + + EMPTY(""); private String value; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java index 9d0aac9f73a..342ebe05be6 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/FormatTest.java @@ -9,7 +9,7 @@ import java.math.BigDecimal; import java.util.UUID; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; - +import javax.validation.constraints.*; /** * FormatTest */ @@ -66,6 +66,8 @@ public class FormatTest { * @return integer **/ @ApiModelProperty(value = "") + @Min(10) + @Max(100) public Integer getInteger() { return integer; } @@ -86,6 +88,8 @@ public class FormatTest { * @return int32 **/ @ApiModelProperty(value = "") + @Min(20) + @Max(200) public Integer getInt32() { return int32; } @@ -124,6 +128,9 @@ public class FormatTest { * @return number **/ @ApiModelProperty(required = true, value = "") + @NotNull + @DecimalMin("32.1") + @DecimalMax("543.2") public BigDecimal getNumber() { return number; } @@ -144,6 +151,8 @@ public class FormatTest { * @return _float **/ @ApiModelProperty(value = "") + @DecimalMin("54.3") + @DecimalMax("987.6") public Float getFloat() { return _float; } @@ -164,6 +173,8 @@ public class FormatTest { * @return _double **/ @ApiModelProperty(value = "") + @DecimalMin("67.8") + @DecimalMax("123.4") public Double getDouble() { return _double; } @@ -182,6 +193,7 @@ public class FormatTest { * @return string **/ @ApiModelProperty(value = "") + @Pattern(regexp="/[a-z]/i") public String getString() { return string; } @@ -200,6 +212,7 @@ public class FormatTest { * @return _byte **/ @ApiModelProperty(required = true, value = "") + @NotNull public byte[] getByte() { return _byte; } @@ -236,6 +249,7 @@ public class FormatTest { * @return date **/ @ApiModelProperty(required = true, value = "") + @NotNull public LocalDate getDate() { return date; } @@ -290,6 +304,8 @@ public class FormatTest { * @return password **/ @ApiModelProperty(required = true, value = "") + @NotNull + @Size(min=10,max=64) public String getPassword() { return password; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java index 55817f8dd14..a26492e4912 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/HasOnlyReadOnly.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * HasOnlyReadOnly */ @@ -26,7 +26,7 @@ public class HasOnlyReadOnly { * Get bar * @return bar **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public String getBar() { return bar; } @@ -44,7 +44,7 @@ public class HasOnlyReadOnly { * Get foo * @return foo **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public String getFoo() { return foo; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/MapTest.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MapTest.java index 9ef30a045d0..9a0566a8dd1 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/MapTest.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MapTest.java @@ -9,7 +9,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; - +import javax.validation.constraints.*; /** * MapTest */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java index 507b3c5e662..19eb9f2b139 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -11,7 +11,7 @@ import java.util.List; import java.util.Map; import java.util.UUID; import org.threeten.bp.OffsetDateTime; - +import javax.validation.constraints.*; /** * MixedPropertiesAndAdditionalPropertiesClass */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Model200Response.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Model200Response.java index 09ad4d0d60e..4d47f6c03c9 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Model200Response.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Model200Response.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Model for testing model name starting with number */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java index 82f447004ee..36da9b20d9d 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * ModelApiResponse */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelReturn.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelReturn.java index 884a45c598e..7ffc24a0144 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelReturn.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelReturn.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Model for testing reserved words */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java index aa31ac8d79a..953199166ff 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Name.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Model for testing model name same as property name */ @@ -34,6 +34,7 @@ public class Name { * @return name **/ @ApiModelProperty(required = true, value = "") + @NotNull public Integer getName() { return name; } @@ -51,7 +52,7 @@ public class Name { * Get snakeCase * @return snakeCase **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public Integer getSnakeCase() { return snakeCase; } @@ -87,7 +88,7 @@ public class Name { * Get _123Number * @return _123Number **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public Integer get123Number() { return _123Number; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/NumberOnly.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/NumberOnly.java index 9424f7a4b5e..e6dbf3139e2 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/NumberOnly.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/NumberOnly.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; - +import javax.validation.constraints.*; /** * NumberOnly */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java index b63c620c987..c5381d2fa7e 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.threeten.bp.OffsetDateTime; - +import javax.validation.constraints.*; /** * Order */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/OuterEnum.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/OuterEnum.java index 0abc3d063b5..5f0075e4457 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/OuterEnum.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/OuterEnum.java @@ -2,7 +2,7 @@ package io.swagger.model; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonValue; - +import javax.validation.constraints.*; import com.fasterxml.jackson.annotation.JsonCreator; /** diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java index 823d25e05a0..9adc708de71 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java @@ -10,7 +10,7 @@ import io.swagger.model.Category; import io.swagger.model.Tag; import java.util.ArrayList; import java.util.List; - +import javax.validation.constraints.*; /** * Pet */ @@ -113,6 +113,7 @@ public class Pet { * @return name **/ @ApiModelProperty(example = "doggie", required = true, value = "") + @NotNull public String getName() { return name; } @@ -136,6 +137,7 @@ public class Pet { * @return photoUrls **/ @ApiModelProperty(required = true, value = "") + @NotNull public List getPhotoUrls() { return photoUrls; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java index 76d529c087a..47700659fd2 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ReadOnlyFirst.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * ReadOnlyFirst */ @@ -26,7 +26,7 @@ public class ReadOnlyFirst { * Get bar * @return bar **/ - @ApiModelProperty(value = "") + @ApiModelProperty(readOnly = true, value = "") public String getBar() { return bar; } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/SpecialModelName.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/SpecialModelName.java index 2cdc99de90e..880d70599b0 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/SpecialModelName.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/SpecialModelName.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * SpecialModelName */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java index 846812a5031..298085317a4 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * Tag */ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java index 52c5fff826e..8e40f7e0594 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java @@ -5,7 +5,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; - +import javax.validation.constraints.*; /** * User */ diff --git a/samples/server/petstore/ze-ph/.swagger-codegen-ignore b/samples/server/petstore/ze-ph/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/ze-ph/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# 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 Swagger Codgen 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/ze-ph/README.md b/samples/server/petstore/ze-ph/README.md new file mode 100644 index 00000000000..81eb543af3a --- /dev/null +++ b/samples/server/petstore/ze-ph/README.md @@ -0,0 +1,10 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a PHP server. + +This example uses the [Zend Expressive](https://zendframework.github.io/zend-expressive) micro framework and [Path Handler](https://github.com/Articus/PathHandler) library. To see how to make this your own, please take a look at the template here: + +[TEMPLATES](https://github.com/swagger-api/swagger-codegen/tree/master/modules/swagger-codegen/src/main/resources/ze-ph/) diff --git a/samples/server/petstore/ze-ph/application/config.yml b/samples/server/petstore/ze-ph/application/config.yml new file mode 100644 index 00000000000..dce9c534bcd --- /dev/null +++ b/samples/server/petstore/ze-ph/application/config.yml @@ -0,0 +1,2 @@ +#App +cache_configuration: false diff --git a/samples/server/petstore/ze-ph/application/config/app.yml b/samples/server/petstore/ze-ph/application/config/app.yml new file mode 100644 index 00000000000..d91bcd21339 --- /dev/null +++ b/samples/server/petstore/ze-ph/application/config/app.yml @@ -0,0 +1,19 @@ +dependencies: + invokables: + #Has to add this line because currently router is strict requirement for Zend\Expressive\Application even if only middleware_pipeline is used + Zend\Expressive\Router\RouterInterface: Zend\Expressive\Router\ZendRouter + Zend\Diactoros\Response\EmitterInterface: Zend\Diactoros\Response\SapiStreamEmitter + App\ErrorMiddleware: App\ErrorMiddleware + factories: + Zend\Expressive\Application: Zend\Expressive\Container\ApplicationFactory + Articus\PathHandler\Middleware: Articus\PathHandler\MiddlewareFactory + Articus\DataTransfer\Service: Articus\DataTransfer\ServiceFactory + +middleware_pipeline: + api: + middleware: Articus\PathHandler\Middleware + path: /v2 + error: + middleware: App\ErrorMiddleware + error: true + priority: -10000 diff --git a/samples/server/petstore/ze-ph/application/config/data_transfer.yml b/samples/server/petstore/ze-ph/application/config/data_transfer.yml new file mode 100644 index 00000000000..6040af29208 --- /dev/null +++ b/samples/server/petstore/ze-ph/application/config/data_transfer.yml @@ -0,0 +1,28 @@ +data_transfer: + metadata_cache: + adapter: + name: blackhole +# adapter: +# name: filesystem +# options: +# cache_dir: data/cache/data_transfer +# namespace: dt + + strategies: + invokables: + App\Strategy\Date: App\Strategy\Date + App\Strategy\DateTime: App\Strategy\DateTime +# factories: + aliases: + Date: App\Strategy\Date + DateTime: App\Strategy\DateTime + validators: + invokables: + App\Validator\Type: App\Validator\Type + factories: + Articus\DataTransfer\Validator\Dictionary: Articus\DataTransfer\Validator\Factory + Articus\DataTransfer\Validator\Collection: Articus\DataTransfer\Validator\Factory + aliases: + Dictionary: Articus\DataTransfer\Validator\Dictionary + Collection: Articus\DataTransfer\Validator\Collection + Type: App\Validator\Type diff --git a/samples/server/petstore/ze-ph/application/config/path_handler.yml b/samples/server/petstore/ze-ph/application/config/path_handler.yml new file mode 100644 index 00000000000..39048ff6f48 --- /dev/null +++ b/samples/server/petstore/ze-ph/application/config/path_handler.yml @@ -0,0 +1,131 @@ +path_handler: + routes: + routes: + 'pet': + type: Literal + options: + route: /pet + defaults: + handler: Pet + may_terminate: true + child_routes: + 'findByStatus': + type: Literal + options: + route: /findByStatus + defaults: + handler: PetFindByStatus + 'findByTags': + type: Literal + options: + route: /findByTags + defaults: + handler: PetFindByTags + '{petId}': + type: Segment + options: + route: /:petId + defaults: + handler: PetPetId + may_terminate: true + child_routes: + 'uploadImage': + type: Literal + options: + route: /uploadImage + defaults: + handler: PetPetIdUploadImage + 'store': + type: Literal + options: + route: /store + child_routes: + 'inventory': + type: Literal + options: + route: /inventory + defaults: + handler: StoreInventory + 'order': + type: Literal + options: + route: /order + defaults: + handler: StoreOrder + may_terminate: true + child_routes: + '{orderId}': + type: Segment + options: + route: /:orderId + defaults: + handler: StoreOrderOrderId + 'user': + type: Literal + options: + route: /user + defaults: + handler: User + may_terminate: true + child_routes: + 'createWithArray': + type: Literal + options: + route: /createWithArray + defaults: + handler: UserCreateWithArray + 'createWithList': + type: Literal + options: + route: /createWithList + defaults: + handler: UserCreateWithList + 'login': + type: Literal + options: + route: /login + defaults: + handler: UserLogin + 'logout': + type: Literal + options: + route: /logout + defaults: + handler: UserLogout + '{username}': + type: Segment + options: + route: /:username + defaults: + handler: UserUsername + + default_params: + middleware: '' + metadata_cache: + adapter: + name: blackhole +# adapter: +# name: filesystem +# options: +# cache_dir: data/cache/path_handler +# namespace: ph + + handlers: + invokables: + Pet: App\Handler\Pet + PetFindByStatus: App\Handler\PetFindByStatus + PetFindByTags: App\Handler\PetFindByTags + PetPetId: App\Handler\PetPetId + PetPetIdUploadImage: App\Handler\PetPetIdUploadImage + StoreInventory: App\Handler\StoreInventory + StoreOrder: App\Handler\StoreOrder + StoreOrderOrderId: App\Handler\StoreOrderOrderId + User: App\Handler\User + UserCreateWithArray: App\Handler\UserCreateWithArray + UserCreateWithList: App\Handler\UserCreateWithList + UserLogin: App\Handler\UserLogin + UserLogout: App\Handler\UserLogout + UserUsername: App\Handler\UserUsername +# consumers: +# attributes: +# producers: diff --git a/samples/server/petstore/ze-ph/application/container.php b/samples/server/petstore/ze-ph/application/container.php new file mode 100644 index 00000000000..e70a0663cf3 --- /dev/null +++ b/samples/server/petstore/ze-ph/application/container.php @@ -0,0 +1,46 @@ +setService('config', $config); +$container->setAlias('Config', 'config'); + +return $container; diff --git a/samples/server/petstore/ze-ph/composer.json b/samples/server/petstore/ze-ph/composer.json new file mode 100644 index 00000000000..5cad52b27e2 --- /dev/null +++ b/samples/server/petstore/ze-ph/composer.json @@ -0,0 +1,22 @@ +{ + "name": "GIT_USER_ID/GIT_REPO_ID", + "description": "", + "license": "proprietary", + "version": "1.0.0", + "type": "project", + "require": { + "php": "^5.6 || ^7.0", + "ext-yaml" : "^1.2 || ^2.0", + "zendframework/zend-expressive": "^1.0", + "zendframework/zend-expressive-router": "1.2.*", + "articus/path-handler": "0.1.*", + "articus/data-transfer": "*", + "zendframework/zend-serializer": "*", + "zendframework/zend-config": "*" + }, + "autoload": { + "psr-4": { + "": "src/" + } + } +} diff --git a/samples/server/petstore/ze-ph/public/index.php b/samples/server/petstore/ze-ph/public/index.php new file mode 100644 index 00000000000..09e8b0233e4 --- /dev/null +++ b/samples/server/petstore/ze-ph/public/index.php @@ -0,0 +1,10 @@ +get(\Zend\Expressive\Application::class); +$app->run(); \ No newline at end of file diff --git a/samples/server/petstore/ze-ph/src/App/DTO/ApiResponse.php b/samples/server/petstore/ze-ph/src/App/DTO/ApiResponse.php new file mode 100644 index 00000000000..9d978986b06 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/DTO/ApiResponse.php @@ -0,0 +1,30 @@ +withStatus(500, 'Internal server error'); + $response->getBody()->write((string)$error); + error_log((string) $error); + return ($out === null)? $response : $out($request, $response); + } +} \ No newline at end of file diff --git a/samples/server/petstore/ze-ph/src/App/Handler/Pet.php b/samples/server/petstore/ze-ph/src/App/Handler/Pet.php new file mode 100644 index 00000000000..035e9b19b83 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/Pet.php @@ -0,0 +1,54 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } + /** + * Update an existing pet + * 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, mediaType="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, mediaType="application/xml") + * @PHA\Attribute(name=PHAttribute\Transfer::class, options={"type":\App\DTO\Pet::class,"objectAttr":"body"}) + * 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") + */ + public function handlePut(ServerRequestInterface $request) + { + //TODO implement method + /** @var \App\DTO\Pet $body */ + $body = $request->getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Handler/PetFindByStatus.php b/samples/server/petstore/ze-ph/src/App/Handler/PetFindByStatus.php new file mode 100644 index 00000000000..3c9ae5149cc --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/PetFindByStatus.php @@ -0,0 +1,29 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Handler/StoreOrderOrderId.php b/samples/server/petstore/ze-ph/src/App/Handler/StoreOrderOrderId.php new file mode 100644 index 00000000000..4bb3c7e8444 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/StoreOrderOrderId.php @@ -0,0 +1,41 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithArray.php b/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithArray.php new file mode 100644 index 00000000000..cc0f119db3f --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithArray.php @@ -0,0 +1,31 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithList.php b/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithList.php new file mode 100644 index 00000000000..7cd3e2cc649 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/UserCreateWithList.php @@ -0,0 +1,31 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Handler/UserLogin.php b/samples/server/petstore/ze-ph/src/App/Handler/UserLogin.php new file mode 100644 index 00000000000..657218c99e8 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Handler/UserLogin.php @@ -0,0 +1,29 @@ +getAttribute("body"); + throw new PHException\HttpCode(500, "Not implemented"); + } +} diff --git a/samples/server/petstore/ze-ph/src/App/Strategy/Date.php b/samples/server/petstore/ze-ph/src/App/Strategy/Date.php new file mode 100644 index 00000000000..91c83c363a8 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Strategy/Date.php @@ -0,0 +1,17 @@ +format(static::DATE_TIME_FORMAT); + } + return $result; + } + + /** + * @inheritDoc + */ + public function hydrate($arrayValue, $objectValue, array $array = null) + { + $result = null; + if (!empty($arrayValue)) { + $date = $this->parseDateString($arrayValue); + if ($date instanceof \DateTime) { + $result = $date; + } + } + return $result; + } + + /** + * @param $arrayValue + * @return \DateTime + */ + protected function parseDateString($arrayValue) + { + return \DateTime::createFromFormat(static::DATE_TIME_FORMAT, $arrayValue, new \DateTimeZone('UTC')); + } +} \ No newline at end of file diff --git a/samples/server/petstore/ze-ph/src/App/Validator/Type.php b/samples/server/petstore/ze-ph/src/App/Validator/Type.php new file mode 100644 index 00000000000..79644bacf06 --- /dev/null +++ b/samples/server/petstore/ze-ph/src/App/Validator/Type.php @@ -0,0 +1,71 @@ + 'Invalid type given.', + ]; + + /** + * @var string + */ + protected $type; + + /** + * @return mixed + */ + public function getType() + { + return $this->type; + } + + /** + * @param string $type + * @return self + */ + public function setType($type) + { + $this->type = $type; + return $this; + } + + /** + * @inheritDoc + */ + public function isValid($value) + { + $result = true; + if (!$this->checkType($value)) { + $this->error(self::INVALID); + $result = false; + } + return $result; + } + + protected function checkType($value) + { + switch ($this->type) { + case 'int': + return is_int($value); + case 'bool': + return is_bool($value); + case 'float': + return is_float($value) || is_int($value); + case 'string': + return is_string($value); + default: + throw new \InvalidArgumentException(sprintf('Can not check for type %s.', $this->type)); + } + } +} \ No newline at end of file