diff --git a/README.md b/README.md index 4c4632337224..6a93010b9ddd 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se | | Languages/Frameworks | |-|-| -**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Dart (1.x, 2.x)**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node, Rxjs) +**API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0), **C++** (cpp-restsdk, Qt5, Tizen), **Clojure**, **Dart (1.x, 2.x)**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (rust, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 8.x), Aurelia, Axios, Fetch, Inversify, jQuery, Node, Rxjs) **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin), **Haskell** (Servant), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, Slim, Silex, [Symfony](https://symfony.com/), [Zend Expressive](https://github.com/zendframework/zend-expressive)), **Python** (Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** ([Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc** **Configuration files** | [**Apache2**](https://httpd.apache.org/) @@ -814,6 +814,7 @@ Here is a list of template creators: * Rust (rust-server): @metaswitch * Scala (scalaz & http4s): @tbrown1979 * Scala (Akka): @cchafer + * Scala (sttp): @chameleon82 * Swift: @tkqubo * Swift 3: @hexelon * Swift 4: @ehyche diff --git a/bin/openapi3/python-flask-petstore-python2.sh b/bin/openapi3/python-flask-petstore-python2.sh index e33183e3a218..b9afa34fcd63 100755 --- a/bin/openapi3/python-flask-petstore-python2.sh +++ b/bin/openapi3/python-flask-petstore-python2.sh @@ -26,7 +26,7 @@ then fi # if you've executed sbt assembly previously it will use that instead. -input=modules/openapi-generator/src/test/resources/3_0/petstore.yaml +input=modules/openapi-generator/src/test/resources/3_0/petstore-with-object-as-parameter.yaml out_folder=samples/openapi3/server/petstore/python-flask-python2 resources=modules/openapi-generator/src/main/resources/python-flask diff --git a/bin/openapi3/python-flask-petstore.sh b/bin/openapi3/python-flask-petstore.sh index b2422ba069b3..6b0f03aa3d28 100755 --- a/bin/openapi3/python-flask-petstore.sh +++ b/bin/openapi3/python-flask-petstore.sh @@ -26,7 +26,7 @@ then fi # if you've executed sbt assembly previously it will use that instead. -input=modules/openapi-generator/src/test/resources/3_0/petstore.yaml +input=modules/openapi-generator/src/test/resources/3_0/petstore-with-object-as-parameter.yaml out_folder=samples/openapi3/server/petstore/python-flask resources=modules/openapi-generator/src/main/resources/python-flask diff --git a/bin/openapi3/scala-sttp-petstore.sh b/bin/openapi3/scala-sttp-petstore.sh new file mode 100755 index 000000000000..9157368acfb0 --- /dev/null +++ b/bin/openapi3/scala-sttp-petstore.sh @@ -0,0 +1,32 @@ +#!/bin/sh + +SCRIPT="$0" +echo "# START SCRIPT: $SCRIPT" + +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/openapi-generator-cli/target/openapi-generator-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} -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate --artifact-id 'scala-sttp-petstore' -t modules/openapi-generator/src/main/resources/scala-sttp -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -g scala-sttp -o samples/openapi3/client/petstore/scala-sttp $@" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/openapi3/windows/python-experimental-petstore.bat b/bin/openapi3/windows/python-experimental-petstore.bat index 73c433de2784..29c097a55721 100644 --- a/bin/openapi3/windows/python-experimental-petstore.bat +++ b/bin/openapi3/windows/python-experimental-petstore.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -set ags=generate -i modules\openapi-generator\src\test\resources\3_0\petstore-with-fake-endpoints-models-for-testing.yaml -g python-experimental -o samples\openapi3\client\petstore\python-experimental --additional-properties packageName=petstore_api +set ags=generate -i modules\openapi-generator\src\test\resources\3_0\petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml -g python-experimental -o samples\openapi3\client\petstore\python-experimental --additional-properties packageName=petstore_api java %JAVA_OPTS% -jar %executable% %ags% diff --git a/bin/openapi3/windows/scala-sttp-petstore.bat b/bin/openapi3/windows/scala-sttp-petstore.bat new file mode 100755 index 000000000000..3aaf98462a8b --- /dev/null +++ b/bin/openapi3/windows/scala-sttp-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\openapi-generator-cli\target\openapi-generator-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate --artifact-id "scala-sttp-petstore" -t modules\openapi-generator\src\main\resources\scala-sttp -i modules\openapi-generator\src\test\resources\3_0\petstore.yaml -g scala-sttp -o samples\openapi3\client\petstore\scala-sttp + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/docs/generators.md b/docs/generators.md index c8dd81b0cc7c..1991c57ffddc 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -54,6 +54,7 @@ The following generators are available: * [scala-akka](generators/scala-akka.md) * [scala-gatling](generators/scala-gatling.md) * [scala-httpclient-deprecated (deprecated)](generators/scala-httpclient-deprecated.md) +* [scala-sttp (beta)](generators/scala-sttp.md) * [scalaz](generators/scalaz.md) * [swift2-deprecated (deprecated)](generators/swift2-deprecated.md) * [swift3-deprecated (deprecated)](generators/swift3-deprecated.md) diff --git a/docs/generators/javascript-flowtyped.md b/docs/generators/javascript-flowtyped.md index 3b3bb77331c3..6ecd6654d10d 100644 --- a/docs/generators/javascript-flowtyped.md +++ b/docs/generators/javascript-flowtyped.md @@ -9,7 +9,7 @@ sidebar_label: javascript-flowtyped |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| -|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| diff --git a/docs/generators/scala-sttp.md b/docs/generators/scala-sttp.md new file mode 100644 index 000000000000..bcf665f875b7 --- /dev/null +++ b/docs/generators/scala-sttp.md @@ -0,0 +1,216 @@ +--- +title: Config Options for scala-sttp +sidebar_label: scala-sttp +--- + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|apiPackage|package for generated api classes| |null| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|mainPackage|Top-level package name, which defines 'apiPackage', 'modelPackage', 'invokerPackage'| |org.openapitools.client| +|modelPackage|package for generated models| |null| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sourceFolder|source folder for generated code| |null| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | +|Array|java.util.List| +|ArrayList|java.util.ArrayList| +|BigDecimal|java.math.BigDecimal| +|Date|java.util.Date| +|DateTime|org.joda.time.DateTime| +|File|java.io.File| +|HashMap|java.util.HashMap| +|ListBuffer|scala.collection.mutable.ListBuffer| +|ListSet|scala.collection.immutable.ListSet| +|LocalDate|org.joda.time.*| +|LocalDateTime|org.joda.time.*| +|LocalTime|org.joda.time.*| +|Timestamp|java.sql.Timestamp| +|URI|java.net.URI| +|UUID|java.util.UUID| + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|ListBuffer| +|map|Map| +|set|Set| + + +## LANGUAGE PRIMITIVES + + + +## RESERVED WORDS + + + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✓|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✓|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✗|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✓|OAS2,OAS3 diff --git a/docs/generators/scalatra.md b/docs/generators/scalatra.md index 0313b6d2644a..b202548a6ea4 100644 --- a/docs/generators/scalatra.md +++ b/docs/generators/scalatra.md @@ -67,56 +67,44 @@ sidebar_label: scalatra ## FEATURE SET diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index d83b524042cd..f382194df4ab 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -12,7 +12,7 @@ sidebar_label: typescript-angular |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| |fileNaming|Naming convention for the output files: 'camelCase', 'kebab-case'.| |camelCase| |modelFileSuffix|The suffix of the file of the generated model (model<suffix>.ts).| |null| -|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |modelSuffix|The suffix of the generated model.| |null| |ngVersion|The version of Angular.| |9.0.0| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| diff --git a/docs/generators/typescript-angularjs.md b/docs/generators/typescript-angularjs.md index e66164fa1eb6..fbfd828ba323 100644 --- a/docs/generators/typescript-angularjs.md +++ b/docs/generators/typescript-angularjs.md @@ -9,7 +9,7 @@ sidebar_label: typescript-angularjs |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| -|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| |prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| |sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| diff --git a/docs/generators/typescript-aurelia.md b/docs/generators/typescript-aurelia.md index d0278734f7be..955079117b0e 100644 --- a/docs/generators/typescript-aurelia.md +++ b/docs/generators/typescript-aurelia.md @@ -9,7 +9,7 @@ sidebar_label: typescript-aurelia |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| -|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| |nullSafeAdditionalProps|Set to make additional properties types declare that their indexer may return undefined| |false| diff --git a/docs/generators/typescript-axios.md b/docs/generators/typescript-axios.md index 1b7fae3d145a..5e65684a0e6e 100644 --- a/docs/generators/typescript-axios.md +++ b/docs/generators/typescript-axios.md @@ -9,7 +9,7 @@ sidebar_label: typescript-axios |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| -|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmRepository|Use this property to set an url of your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| diff --git a/docs/generators/typescript-inversify.md b/docs/generators/typescript-inversify.md index c6657b5b5f70..5d68c9f08399 100644 --- a/docs/generators/typescript-inversify.md +++ b/docs/generators/typescript-inversify.md @@ -9,7 +9,7 @@ sidebar_label: typescript-inversify |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| -|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| diff --git a/docs/generators/typescript-jquery.md b/docs/generators/typescript-jquery.md index f5f40aaa6424..91d61cf31e10 100644 --- a/docs/generators/typescript-jquery.md +++ b/docs/generators/typescript-jquery.md @@ -10,7 +10,7 @@ sidebar_label: typescript-jquery |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| |jqueryAlreadyImported|When using this in legacy app using mix of typescript and javascript, this will only declare jquery and not import it| |false| -|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| diff --git a/docs/generators/typescript-rxjs.md b/docs/generators/typescript-rxjs.md index a2a3c09c6005..9a210f4934b9 100644 --- a/docs/generators/typescript-rxjs.md +++ b/docs/generators/typescript-rxjs.md @@ -9,7 +9,7 @@ sidebar_label: typescript-rxjs |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| |enumNameSuffix|Suffix that will be appended to all enum names. A special 'v4-compat' value enables the backward-compatible behavior (as pre v4.2.3)| |v4-compat| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |PascalCase| -|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java index 3e68b0c862d7..6c6f50b544e1 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java @@ -268,7 +268,7 @@ private void generateMarkdownHelp(StringBuilder sb, CodegenConfig config) { if (Boolean.TRUE.equals(featureSets)) { sb.append(newline).append("## FEATURE SET").append(newline).append(newline); - List flattened = config.getFeatureSet().flatten(); + List flattened = config.getGeneratorMetadata().getFeatureSet().flatten(); flattened.sort(Comparator.comparing(FeatureSet.FeatureSetFlattened::getFeatureCategory)); AtomicReference lastCategory = new AtomicReference<>(); @@ -385,7 +385,7 @@ private void generatePlainTextHelp(StringBuilder sb, CodegenConfig config) { if (Boolean.TRUE.equals(featureSets)) { sb.append(newline).append("FEATURE SET").append(newline); - List flattened = config.getFeatureSet().flatten(); + List flattened = config.getGeneratorMetadata().getFeatureSet().flatten(); flattened.sort(Comparator.comparing(FeatureSet.FeatureSetFlattened::getFeatureCategory)); AtomicReference lastCategory = new AtomicReference<>(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java index d00cc2b8b057..06fd6a30d627 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java @@ -287,8 +287,6 @@ public interface CodegenConfig { FeatureSet getFeatureSet(); - void setFeatureSet(FeatureSet featureSet); - boolean isRemoveEnumValuePrefix(); void setRemoveEnumValuePrefix(boolean removeEnumValuePrefix); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index dfc4cb3bc4c5..cd3e2abb7987 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -71,6 +71,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -138,7 +139,6 @@ public class DefaultCodegen implements CodegenConfig { .build(); } - protected FeatureSet featureSet; protected GeneratorMetadata generatorMetadata; protected String inputSpec; protected String outputFolder = ""; @@ -1303,10 +1303,9 @@ public DefaultCodegen() { codegenType = CodegenType.OTHER; } - featureSet = DefaultFeatureSet; - generatorMetadata = GeneratorMetadata.newBuilder() .stability(Stability.STABLE) + .featureSet(DefaultFeatureSet) .generationMessage(String.format(Locale.ROOT, "OpenAPI Generator: %s (%s)", getName(), codegenType.toValue())) .build(); @@ -2266,6 +2265,11 @@ public CodegenModel fromModel(String name, Schema schema) { postProcessModelProperty(m, prop); } } + if (m.allVars != null) { + for (CodegenProperty prop : m.allVars) { + postProcessModelProperty(m, prop); + } + } if (sortModelPropertiesByRequiredFlag) { Collections.sort(m.vars, new Comparator() { @@ -5675,12 +5679,7 @@ public void setStrictSpecBehavior(final boolean strictSpecBehavior) { @Override public FeatureSet getFeatureSet() { - return this.featureSet; - } - - @Override - public void setFeatureSet(final FeatureSet featureSet) { - this.featureSet = featureSet == null ? DefaultFeatureSet : featureSet; + return this.generatorMetadata.getFeatureSet(); } /** @@ -5746,6 +5745,13 @@ public void addOneOfInterfaceModel(ComposedSchema cs, String type) { public void addImportsToOneOfInterface(List> imports) {} //// End of methods related to the "useOneOfInterfaces" feature + protected void modifyFeatureSet(Consumer processor) { + FeatureSet.Builder builder = getFeatureSet().modify(); + processor.accept(builder); + this.generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .featureSet(builder.build()).build(); + } + private static class SanitizeNameOptions { public SanitizeNameOptions(String name, String removeCharRegEx, List exceptions) { this.name = name; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java index ad230ea432d8..fdd625e88390 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java @@ -101,7 +101,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code public AbstractJavaCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf( @@ -119,7 +119,7 @@ public AbstractJavaCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); supportsInheritance = true; modelTemplateFiles.put("model.mustache", ".java"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java index b0e44e5565e7..3bb8323cd83c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractScalaCodegen.java @@ -115,6 +115,7 @@ public AbstractScalaCodegen() { cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); + } @Override @@ -319,6 +320,31 @@ public Map postProcessModels(Map objs) { return objs; } + @Override + public String toModelName(final String name) { + final String sanitizedName = sanitizeName(modelNamePrefix + this.stripPackageName(name) + modelNameSuffix); + + // camelize the model name + // phone_number => PhoneNumber + final String camelizedName = camelize(sanitizedName); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(camelizedName)) { + final String modelName = "Model" + camelizedName; + LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + + // model name starts with number + if (name.matches("^\\d.*")) { + final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); + return modelName; + } + + return camelizedName; + } + @Override public String toModelFilename(String name) { // should be the same as the model name diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java index 6fa57faf5a24..39240bfd46b8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -25,6 +25,7 @@ import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CodegenConstants.ENUM_PROPERTY_NAMING_TYPE; +import org.openapitools.codegen.CodegenConstants.MODEL_PROPERTY_NAMING_TYPE; import org.openapitools.codegen.*; import org.openapitools.codegen.meta.features.*; import org.openapitools.codegen.utils.ModelUtils; @@ -55,6 +56,9 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp public static final String ENUM_NAME_SUFFIX_DESC_CUSTOMIZED = CodegenConstants.ENUM_NAME_SUFFIX_DESC + " A special '" + ENUM_NAME_SUFFIX_V4_COMPAT + "' value enables the backward-compatible behavior (as pre v4.2.3)"; + public static final String MODEL_PROPERTY_NAMING_DESC_WITH_WARNING = CodegenConstants.MODEL_PROPERTY_NAMING_DESC + + ". Only change it if you provide your own run-time code for (de-)serialization of models"; + public static final String NULL_SAFE_ADDITIONAL_PROPS = "nullSafeAdditionalProps"; public static final String NULL_SAFE_ADDITIONAL_PROPS_DESC = "Set to make additional properties types declare that their indexer may return undefined"; @@ -62,7 +66,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp @SuppressWarnings("squid:S5164") protected static final ThreadLocal SNAPSHOT_SUFFIX_FORMAT = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMddHHmm", Locale.ROOT)); - protected String modelPropertyNaming = "camelCase"; + protected MODEL_PROPERTY_NAMING_TYPE modelPropertyNaming = MODEL_PROPERTY_NAMING_TYPE.original; protected ENUM_PROPERTY_NAMING_TYPE enumPropertyNaming = ENUM_PROPERTY_NAMING_TYPE.PascalCase; protected Boolean supportsES6 = false; protected Boolean nullSafeAdditionalProps = false; @@ -78,7 +82,7 @@ public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen imp public AbstractTypeScriptClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf( @@ -96,7 +100,7 @@ public AbstractTypeScriptClientCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); // clear import mapping (from default generator) as TS does not use it // at the moment @@ -170,7 +174,7 @@ public AbstractTypeScriptClientCodegen() { cliOptions.add(new CliOption(CodegenConstants.ENUM_NAME_SUFFIX, ENUM_NAME_SUFFIX_DESC_CUSTOMIZED).defaultValue(this.enumSuffix)); cliOptions.add(new CliOption(CodegenConstants.ENUM_PROPERTY_NAMING, CodegenConstants.ENUM_PROPERTY_NAMING_DESC).defaultValue(this.enumPropertyNaming.name())); - cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue(this.modelPropertyNaming)); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_DESC_WITH_WARNING).defaultValue(this.modelPropertyNaming.name())); cliOptions.add(new CliOption(CodegenConstants.SUPPORTS_ES6, CodegenConstants.SUPPORTS_ES6_DESC).defaultValue(String.valueOf(this.getSupportsES6()))); this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package." + " Required to generate a full package")); @@ -179,7 +183,12 @@ public AbstractTypeScriptClientCodegen() { "When setting this property to true, the version will be suffixed with -SNAPSHOT." + this.SNAPSHOT_SUFFIX_FORMAT.get().toPattern(), false)); this.cliOptions.add(new CliOption(NULL_SAFE_ADDITIONAL_PROPS, NULL_SAFE_ADDITIONAL_PROPS_DESC).defaultValue(String.valueOf(this.getNullSafeAdditionalProps()))); + } + protected void supportModelPropertyNaming(MODEL_PROPERTY_NAMING_TYPE defaultModelPropertyNaming) { + removeOption(CodegenConstants.MODEL_PROPERTY_NAMING); + modelPropertyNaming = defaultModelPropertyNaming; + cliOptions.add(new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC).defaultValue(modelPropertyNaming.name())); } @Override @@ -274,52 +283,37 @@ public String modelFileFolder() { @Override public String toParamName(String name) { - // sanitize name name = sanitizeName(name, "[^\\w$]"); if ("_".equals(name)) { name = "_u"; } - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) { - return name; - } - - name = getNameUsingModelPropertyNaming(name); - - // for reserved word or word starting with number, append _ - if (isReservedWord(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } + name = camelize(name, true); + name = toSafeIdentifier(name); return name; } @Override public String toVarName(String name) { - name = this.toParamName(name); - - // if the property name has any breaking characters such as :, ;, . etc. - // then wrap the name within single quotes. - // my:interface:property: string; => 'my:interface:property': string; - if (propertyHasBreakingCharacters(name)) { - name = "\'" + name + "\'"; + name = sanitizeName(name, "[^\\w$]"); + + if ("_".equals(name)) { + name = "_u"; } + name = getNameUsingModelPropertyNaming(name); + name = toSafeIdentifier(name); + return name; } - /** - * Checks whether property names have breaking characters like ':', '-'. - * @param str string to check for breaking characters - * @return true if breaking characters are present and false if not - */ - private boolean propertyHasBreakingCharacters(String str) { - final String regex = "^.*[+*:;,.()-]+.*$"; - final Pattern pattern = Pattern.compile(regex); - final Matcher matcher = pattern.matcher(str); - return matcher.matches(); + private String toSafeIdentifier(String name) { + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + return name; } @Override @@ -533,32 +527,31 @@ public String toOperationId(String operationId) { throw new RuntimeException("Empty method name (operationId) not allowed"); } - // method name cannot use reserved keyword or word starting with number, e.g. return or 123return - // append _ at the beginning, e.g. _return or _123return - if (isReservedWord(operationId) || operationId.matches("^\\d.*")) { - return escapeReservedWord(camelize(sanitizeName(operationId), true)); - } + operationId = camelize(sanitizeName(operationId), true); + operationId = toSafeIdentifier(operationId); - return camelize(sanitizeName(operationId), true); + return operationId; } public void setModelPropertyNaming(String naming) { - if ("original".equals(naming) || "camelCase".equals(naming) || - "PascalCase".equals(naming) || "snake_case".equals(naming)) { - this.modelPropertyNaming = naming; - } else { - throw new IllegalArgumentException("Invalid model property naming '" + - naming + "'. Must be 'original', 'camelCase', " + - "'PascalCase' or 'snake_case'"); + try { + modelPropertyNaming = MODEL_PROPERTY_NAMING_TYPE.valueOf(naming); + } catch (IllegalArgumentException e) { + String values = Stream.of(MODEL_PROPERTY_NAMING_TYPE.values()) + .map(value -> "'" + value.name() + "'") + .collect(Collectors.joining(", ")); + + String msg = String.format(Locale.ROOT, "Invalid model property naming '%s'. Must be one of %s.", naming, values); + throw new IllegalArgumentException(msg); } } - public String getModelPropertyNaming() { - return this.modelPropertyNaming; + public MODEL_PROPERTY_NAMING_TYPE getModelPropertyNaming() { + return modelPropertyNaming; } private String getNameUsingModelPropertyNaming(String name) { - switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) { + switch (getModelPropertyNaming()) { case original: return name; case camelCase: diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaCodegen.java index 1726b0cda819..1b25ab3dbb4a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaCodegen.java @@ -57,7 +57,7 @@ public void processOpts() { super.processOpts(); // TODO: Ada maintainer review. - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .excludeDocumentationFeatures(DocumentationFeature.Readme) .excludeWireFormatFeatures( WireFormatFeature.XML, @@ -86,7 +86,7 @@ public void processOpts() { ParameterFeature.Cookie ) .includeClientModificationFeatures(ClientModificationFeature.BasePath) - .build(); + ); if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { packageName = (String) additionalProperties.get(CodegenConstants.PACKAGE_NAME); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaServerCodegen.java index 329065b22cbd..4c8d365fcaa1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AdaServerCodegen.java @@ -36,7 +36,7 @@ public AdaServerCodegen() { super(); // TODO: Ada maintainer review. - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .excludeWireFormatFeatures( WireFormatFeature.XML, @@ -64,7 +64,7 @@ public AdaServerCodegen() { ParameterFeature.Cookie ) .includeClientModificationFeatures(ClientModificationFeature.BasePath) - .build(); + ); } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java index 150f723180d3..1e7349a53bd8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AndroidClientCodegen.java @@ -61,7 +61,7 @@ public AndroidClientCodegen() { super(); // TODO: Android client maintainer review. - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .excludeWireFormatFeatures( WireFormatFeature.PROTOBUF @@ -87,7 +87,7 @@ public AndroidClientCodegen() { ParameterFeature.Cookie ) .includeClientModificationFeatures(ClientModificationFeature.BasePath) - .build(); + ); outputFolder = "generated-code/android"; modelTemplateFiles.put("model.mustache", ".java"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java index d3bbe7743613..5cd7dfb6c679 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Apache2ConfigCodegen.java @@ -52,7 +52,7 @@ public Apache2ConfigCodegen() { super(); // TODO: Apache2 maintainer review. - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .parameterFeatures(EnumSet.of(ParameterFeature.Path)) .securityFeatures(EnumSet.of(SecurityFeature.BasicAuth)) .dataTypeFeatures(EnumSet.noneOf(DataTypeFeature.class)) @@ -61,7 +61,7 @@ public Apache2ConfigCodegen() { .globalFeatures(EnumSet.noneOf(GlobalFeature.class)) .schemaSupportFeatures(EnumSet.noneOf(SchemaSupportFeature.class)) .clientModificationFeatures(EnumSet.noneOf(ClientModificationFeature.class)) - .build(); + ); apiTemplateFiles.put("apache-config.mustache", ".conf"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java index 731e951ec612..9421ae29866c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AsciidocDocumentationCodegen.java @@ -187,13 +187,13 @@ public AsciidocDocumentationCodegen() { super(); // TODO: Asciidoc maintainer review. - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) .documentationFeatures(EnumSet.noneOf(DocumentationFeature.class)) .globalFeatures(EnumSet.noneOf(GlobalFeature.class)) .schemaSupportFeatures(EnumSet.noneOf(SchemaSupportFeature.class)) .clientModificationFeatures(EnumSet.noneOf(ClientModificationFeature.class)) - .build(); + ); LOGGER.trace("start asciidoc codegen"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java index fdcad979bf8f..66fe43864a7b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetCoreServerCodegen.java @@ -89,7 +89,7 @@ public AspNetCoreServerCodegen() { super(); // TODO: AspnetCore community review - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .excludeWireFormatFeatures(WireFormatFeature.PROTOBUF) .includeSecurityFeatures( @@ -117,7 +117,7 @@ public AspNetCoreServerCodegen() { .includeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code" + File.separator + getName(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AvroSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AvroSchemaCodegen.java index 6e96542eaaf0..8d60bbed894d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AvroSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AvroSchemaCodegen.java @@ -44,7 +44,7 @@ public AvroSchemaCodegen() { .build(); // TODO: Avro maintainer review. - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .parameterFeatures(EnumSet.noneOf(ParameterFeature.class)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) .wireFormatFeatures(EnumSet.noneOf(WireFormatFeature.class)) @@ -55,7 +55,7 @@ public AvroSchemaCodegen() { SchemaSupportFeature.Union ) .clientModificationFeatures(EnumSet.noneOf(ClientModificationFeature.class)) - .build(); + ); outputFolder = "generated-code/avro-schema"; modelTemplateFiles.put("model.mustache", ".avsc"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java index 3c13a4a2f75f..bf59d7db699f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/BashClientCodegen.java @@ -103,7 +103,7 @@ public BashClientCodegen() { super(); // TODO: Bash maintainer review - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .documentationFeatures(EnumSet.of( DocumentationFeature.Readme )) @@ -125,7 +125,7 @@ public BashClientCodegen() { SchemaSupportFeature.Polymorphism, SchemaSupportFeature.Union ) - .build(); + ); setReservedWordsLowerCase( Arrays.asList( diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java index 24c035ab87af..2b5830ea890e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java @@ -53,7 +53,7 @@ public CLibcurlClientCodegen() { // TODO: c maintainer review // Assumes that C community considers api/model header files as documentation. // Generator supports Basic, OAuth, and API key explicitly. Bearer is excluded although clients are able to set headers directly. - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures( DocumentationFeature.Readme ) @@ -73,7 +73,7 @@ public CLibcurlClientCodegen() { SchemaSupportFeature.Polymorphism, SchemaSupportFeature.Union ) - .build(); + ); modelPackage = "models"; apiPackage = "api"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java index 4f318bb2b598..2c30b432da05 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java @@ -80,7 +80,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { public CSharpClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.of( SecurityFeature.OAuth2_Implicit, @@ -103,7 +103,7 @@ public CSharpClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); supportsInheritance = true; modelTemplateFiles.put("model.mustache", ".cs"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpDotNet2ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpDotNet2ClientCodegen.java index 11d32d5f05fc..61af6a358431 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpDotNet2ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpDotNet2ClientCodegen.java @@ -41,9 +41,7 @@ public class CSharpDotNet2ClientCodegen extends AbstractCSharpCodegen { public CSharpDotNet2ClientCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) .stability(Stability.DEPRECATED) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java index 2ca162a2c5e0..cc24632a2ec1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNancyFXServerCodegen.java @@ -69,7 +69,7 @@ public class CSharpNancyFXServerCodegen extends AbstractCSharpCodegen { public CSharpNancyFXServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .excludeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) .excludeGlobalFeatures( @@ -84,7 +84,7 @@ public CSharpNancyFXServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code" + File.separator + getName(); apiTemplateFiles.put("api.mustache", ".cs"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java index 779f2b66c5eb..22e5597fbec5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java @@ -92,7 +92,7 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { public CSharpNetCoreClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.of( SecurityFeature.OAuth2_Implicit, @@ -115,7 +115,7 @@ public CSharpNetCoreClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); // mapped non-nullable type without ? typeMapping = new HashMap(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java index 48e4a123cdd2..cb31f4f895d4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ClojureClientCodegen.java @@ -64,7 +64,7 @@ public ClojureClientCodegen() { super(); // TODO: Clojure maintainer review - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .excludeDocumentationFeatures( DocumentationFeature.Readme ) @@ -80,7 +80,7 @@ public ClojureClientCodegen() { SchemaSupportFeature.Polymorphism, SchemaSupportFeature.Union ) - .build(); + ); outputFolder = "generated-code" + File.separator + "clojure"; modelTemplateFiles.put("spec.mustache", ".clj"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiCodegen.java index e368355cc670..1de98be94e73 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ConfluenceWikiCodegen.java @@ -36,7 +36,7 @@ public ConfluenceWikiCodegen() { super(); // TODO: ConfluenceWiki maintainer review - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .documentationFeatures(EnumSet.noneOf(DocumentationFeature.class)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) .excludeParameterFeatures(ParameterFeature.Cookie) @@ -49,7 +49,7 @@ public ConfluenceWikiCodegen() { SchemaSupportFeature.Polymorphism, SchemaSupportFeature.Union ) - .build(); + ); outputFolder = "docs"; embeddedTemplateDir = templateDir = "confluenceWikiDocs"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java index ae72864d61e0..208e4d3735de 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java @@ -69,7 +69,7 @@ public CppPistacheServerCodegen() { super(); // TODO: cpp-pistache-server maintainer review - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) .excludeGlobalFeatures( @@ -85,7 +85,7 @@ public CppPistacheServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); if (StringUtils.isEmpty(modelNamePrefix)) { modelNamePrefix = PREFIX; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java index 82e4364eb91e..b6c86a6a1b0f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5AbstractCodegen.java @@ -34,7 +34,7 @@ public class CppQt5AbstractCodegen extends AbstractCppCodegen implements Codegen public CppQt5AbstractCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .excludeWireFormatFeatures(WireFormatFeature.PROTOBUF) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) .excludeGlobalFeatures( @@ -50,7 +50,7 @@ public CppQt5AbstractCodegen() { .includeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); // set modelNamePrefix as default for QHttpEngine Server if (StringUtils.isEmpty(modelNamePrefix)) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java index 3f33b21f8d34..7c35de11720f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQt5QHttpEngineServerCodegen.java @@ -39,9 +39,7 @@ public class CppQt5QHttpEngineServerCodegen extends CppQt5AbstractCodegen implem public CppQt5QHttpEngineServerCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); // set the output folder here outputFolder = "generated-code/cpp-qt5-qhttpengine-server"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java index 68065389d47b..b0a4f574f0e5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java @@ -80,7 +80,7 @@ public CppRestSdkClientCodegen() { super(); // TODO: cpp-restsdk maintainer review - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.of( SecurityFeature.BasicAuth, @@ -100,7 +100,7 @@ public CppRestSdkClientCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); apiPackage = "org.openapitools.client.api"; modelPackage = "org.openapitools.client.model"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java index df4a08db9681..3234cfb4c9fb 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestbedServerCodegen.java @@ -47,7 +47,7 @@ public CppRestbedServerCodegen() { super(); // TODO: cpp-restbed-server maintainer review - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) .excludeGlobalFeatures( @@ -63,7 +63,7 @@ public CppRestbedServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); apiPackage = "org.openapitools.server.api"; modelPackage = "org.openapitools.server.model"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java index 970753d6a28b..c0db6bec907b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppTizenClientCodegen.java @@ -43,7 +43,7 @@ public CppTizenClientCodegen() { super(); // TODO: cpp-tizen maintainer review - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.of( SecurityFeature.BearerToken @@ -61,7 +61,7 @@ public CppTizenClientCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = ""; modelTemplateFiles.put("model-header.mustache", ".h"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java index 5bdaf70e5c56..4e966fc43cbd 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartClientCodegen.java @@ -66,7 +66,7 @@ public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { public DartClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.of( SecurityFeature.OAuth2_Implicit, @@ -88,7 +88,7 @@ public DartClientCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); // clear import mapping (from default generator) as dart does not use it at the moment importMapping.clear(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java index 934354fb2dfe..eabb64854a4c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartJaguarClientCodegen.java @@ -62,7 +62,7 @@ public class DartJaguarClientCodegen extends DartClientCodegen { public DartJaguarClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.of( SecurityFeature.OAuth2_Implicit, @@ -84,7 +84,7 @@ public DartJaguarClientCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); browserClient = false; outputFolder = "generated-code/dart-jaguar"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java index e1f297956438..5784d2559067 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/EiffelClientCodegen.java @@ -61,7 +61,7 @@ public String getHelp() { public EiffelClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.of( SecurityFeature.OAuth2_Implicit, @@ -84,7 +84,7 @@ public EiffelClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); uuid = UUID.randomUUID(); uuidTest = UUID.randomUUID(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java index d96f85319a64..6f487e0d4757 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java @@ -61,7 +61,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig public ElixirClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .securityFeatures(EnumSet.of( SecurityFeature.OAuth2_Implicit, @@ -82,7 +82,7 @@ public ElixirClientCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); // set the output folder here outputFolder = "generated-code/elixir"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java index 903c92de2f09..780b055c579f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElmClientCodegen.java @@ -76,7 +76,7 @@ public String getHelp() { public ElmClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -95,7 +95,7 @@ public ElmClientCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); outputFolder = "generated-code/elm"; modelTemplateFiles.put("model.mustache", ".elm"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java index 02a25cd9cf52..48de55ac1425 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangClientCodegen.java @@ -58,7 +58,7 @@ public String getHelp() { public ErlangClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.of(SecurityFeature.ApiKey)) @@ -77,7 +77,7 @@ public ErlangClientCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); outputFolder = "generated-code/erlang"; modelTemplateFiles.put("model.mustache", ".erl"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java index b48eb615be4e..096a688b9d36 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangProperCodegen.java @@ -60,7 +60,7 @@ public String getHelp() { public ErlangProperCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.of( @@ -82,7 +82,7 @@ public ErlangProperCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); outputFolder = "generated-code/erlang"; modelTemplateFiles.put("model.mustache", ".erl"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java index 068c36a6ffde..bdaa30e9614a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ErlangServerCodegen.java @@ -43,7 +43,7 @@ public class ErlangServerCodegen extends DefaultCodegen implements CodegenConfig public ErlangServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.of( @@ -62,7 +62,7 @@ public ErlangServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); // set the output folder here outputFolder = "generated-code/erlang-server"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java index c5a38e18077c..dddf6cd22fa7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FlashClientCodegen.java @@ -46,7 +46,7 @@ public class FlashClientCodegen extends DefaultCodegen implements CodegenConfig public FlashClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.of( @@ -67,7 +67,7 @@ public FlashClientCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); modelPackage = "org.openapitools.client.model"; apiPackage = "org.openapitools.client.api"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpFunctionsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpFunctionsServerCodegen.java index a90446eab29f..2ee536a765c1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpFunctionsServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpFunctionsServerCodegen.java @@ -54,7 +54,7 @@ public FsharpFunctionsServerCodegen() { super(); // TODO: There's a README.mustache, but it doesn't seem to be referenced… - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features // .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.noneOf( @@ -74,7 +74,7 @@ public FsharpFunctionsServerCodegen() { .includeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) .stability(Stability.BETA) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java index ea4c79468b7d..44546ec001bf 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/FsharpGiraffeServerCodegen.java @@ -61,9 +61,8 @@ public class FsharpGiraffeServerCodegen extends AbstractFSharpCodegen { public FsharpGiraffeServerCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) .stability(Stability.BETA) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java index 97f8099f9756..58a7090288c3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java @@ -44,7 +44,7 @@ public class GoClientCodegen extends AbstractGoCodegen { public GoClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.of( @@ -71,7 +71,7 @@ public GoClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); outputFolder = "generated-code/go"; modelTemplateFiles.put("model.mustache", ".go"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoGinServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoGinServerCodegen.java index 7d0d0990acc4..4fb58cd7ee80 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoGinServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoGinServerCodegen.java @@ -42,7 +42,7 @@ public class GoGinServerCodegen extends AbstractGoCodegen { public GoGinServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf( @@ -60,7 +60,7 @@ public GoGinServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); // set the output folder here outputFolder = "generated-code/go"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java index 08281463465c..df1ab569d127 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java @@ -47,7 +47,7 @@ public class GoServerCodegen extends AbstractGoCodegen { public GoServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf( @@ -65,7 +65,7 @@ public GoServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); // set the output folder here outputFolder = "generated-code/go"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLNodeJSExpressServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLNodeJSExpressServerCodegen.java index bebc631748f7..35ab7e43366b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLNodeJSExpressServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLNodeJSExpressServerCodegen.java @@ -50,7 +50,7 @@ public String getHelp() { public GraphQLNodeJSExpressServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.noneOf( @@ -68,7 +68,7 @@ public GraphQLNodeJSExpressServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); packageName = "openapi3graphql-server"; packageVersion = "1.0.0"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLSchemaCodegen.java index 99c13c20058f..a8d1bb35a77f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GraphQLSchemaCodegen.java @@ -46,7 +46,7 @@ public String getHelp() { public GraphQLSchemaCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features // .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.noneOf( @@ -61,7 +61,7 @@ public GraphQLSchemaCodegen() { .excludeSchemaSupportFeatures( SchemaSupportFeature.Polymorphism ) - .build(); + ); outputFolder = "generated-code/graphql-schema"; modelTemplateFiles.put("model.mustache", ".graphql"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GroovyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GroovyClientCodegen.java index 22c083218d60..1066f2294b90 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GroovyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GroovyClientCodegen.java @@ -33,7 +33,7 @@ public class GroovyClientCodegen extends AbstractJavaCodegen { public GroovyClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -52,7 +52,7 @@ public GroovyClientCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); // avoid importing the following as models languageSpecificPrimitives.add("Date"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java index 1f3ef7925b71..15a37e681e88 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellHttpClientCodegen.java @@ -170,7 +170,7 @@ public String getHelp() { public HaskellHttpClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.of( @@ -194,7 +194,7 @@ public HaskellHttpClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); this.prependFormOrBodyParameters = true; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java index 14621f597610..024447f3dd33 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/HaskellServantCodegen.java @@ -81,7 +81,7 @@ public String getHelp() { public HaskellServantCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.of( @@ -101,7 +101,7 @@ public HaskellServantCodegen() { .includeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); // override the mapping to keep the original mapping in Haskell specialCharReplacements.put("-", "Dash"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterClientCodegen.java index 17d2a1230f9c..5617b2973da4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterClientCodegen.java @@ -75,7 +75,7 @@ public String getHelp() { public JMeterClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.of( SecurityFeature.BasicAuth, @@ -97,7 +97,7 @@ public JMeterClientCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); // set the output folder here outputFolder = "generated-code/JMeterClientCodegen"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java index acc4dcc3739b..07ece9aaea0c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java @@ -108,10 +108,10 @@ public JavaClientCodegen() { super(); // TODO: Move GlobalFeature.ParameterizedServer to library: jersey after moving featureSet to generatorMetadata - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .includeGlobalFeatures(GlobalFeature.ParameterizedServer) - .build(); + ); outputFolder = "generated-code" + File.separator + "java"; embeddedTemplateDir = templateDir = "Java"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java index e68737e72a71..97c7bdb50b39 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaInflectorServerCodegen.java @@ -41,9 +41,7 @@ public class JavaInflectorServerCodegen extends AbstractJavaCodegen { public JavaInflectorServerCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); sourceFolder = "src/gen/java"; apiTestTemplateFiles.clear(); // TODO: add test template diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java index f47edb272eb8..a607dee5ac43 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJAXRSSpecServerCodegen.java @@ -56,9 +56,7 @@ public class JavaJAXRSSpecServerCodegen extends AbstractJavaJAXRSServerCodegen { public JavaJAXRSSpecServerCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); invokerPackage = "org.openapitools.api"; artifactId = "openapi-jaxrs-server"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java index a0bb1ac6eb46..7e299b45194e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java @@ -41,9 +41,7 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { public JavaJerseyServerCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); outputFolder = "generated-code/JavaJaxRS-Jersey"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaMSF4JServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaMSF4JServerCodegen.java index 708b7447ee38..5b86c4178f39 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaMSF4JServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaMSF4JServerCodegen.java @@ -39,9 +39,7 @@ public class JavaMSF4JServerCodegen extends AbstractJavaJAXRSServerCodegen { public JavaMSF4JServerCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); outputFolder = "generated-code/JavaJaxRS-MSF4J"; apiTemplateFiles.put("apiService.mustache", ".java"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPKMSTServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPKMSTServerCodegen.java index 7095fa54a2d8..2cf3681bb0c3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPKMSTServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPKMSTServerCodegen.java @@ -54,9 +54,7 @@ public class JavaPKMSTServerCodegen extends AbstractJavaCodegen { public JavaPKMSTServerCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); groupId = "com.prokarma"; artifactId = "pkmst-microservice"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java index 90ce97233e23..fb6b93472dc8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaPlayFrameworkCodegen.java @@ -58,9 +58,7 @@ public class JavaPlayFrameworkCodegen extends AbstractJavaCodegen implements Bea public JavaPlayFrameworkCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); outputFolder = "generated-code/javaPlayFramework"; apiTestTemplateFiles.clear(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyEapServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyEapServerCodegen.java index a8d53dfa2838..0d7e6c42d129 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyEapServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyEapServerCodegen.java @@ -41,9 +41,7 @@ public class JavaResteasyEapServerCodegen extends AbstractJavaJAXRSServerCodegen public JavaResteasyEapServerCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); artifactId = "openapi-jaxrs-resteasy-eap-server"; useBeanValidation = true; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyServerCodegen.java index b8beedfee109..d817db3e7ce2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaResteasyServerCodegen.java @@ -37,9 +37,7 @@ public class JavaResteasyServerCodegen extends AbstractJavaJAXRSServerCodegen im public JavaResteasyServerCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); artifactId = "openapi-jaxrs-resteasy-server"; outputFolder = "generated-code/JavaJaxRS-Resteasy"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java index c051d13cb9a0..c4206e8a995b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaUndertowServerCodegen.java @@ -42,9 +42,7 @@ public class JavaUndertowServerCodegen extends AbstractJavaCodegen { public JavaUndertowServerCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); embeddedTemplateDir = templateDir = "java-undertow-server"; invokerPackage = "org.openapitools.handler"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java index a9e0332ca7e4..c0dd3c793e38 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaVertXServerCodegen.java @@ -59,9 +59,7 @@ public class JavaVertXServerCodegen extends AbstractJavaCodegen { public JavaVertXServerCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); // set the output folder here outputFolder = "generated-code" + File.separator + "javaVertXServer"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java index 14e708a290e5..2beed8ba2f4a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptClientCodegen.java @@ -94,9 +94,7 @@ public class JavascriptClientCodegen extends DefaultCodegen implements CodegenCo public JavascriptClientCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); outputFolder = "generated-code/js"; modelTemplateFiles.put("model.mustache", ".js"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptFlowtypedClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptFlowtypedClientCodegen.java index 4d97d7043707..322b7b98e999 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptFlowtypedClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavascriptFlowtypedClientCodegen.java @@ -37,9 +37,7 @@ public class JavascriptFlowtypedClientCodegen extends AbstractTypeScriptClientCo public JavascriptFlowtypedClientCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); // clear import mapping (from default generator) as TS does not use it // at the moment diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java index 15ed281c16d7..4580ad56a907 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java @@ -99,7 +99,7 @@ public KotlinClientCodegen() { /* * OAuth flows supported _only_ by client explicitly setting bearer token. The "flows" are not supported. */ - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .excludeWireFormatFeatures(WireFormatFeature.XML, WireFormatFeature.PROTOBUF) .excludeSecurityFeatures( @@ -122,7 +122,7 @@ public KotlinClientCodegen() { ParameterFeature.Cookie ) .includeClientModificationFeatures(ClientModificationFeature.BasePath) - .build(); + ); artifactId = "kotlin-client"; packageName = "org.openapitools.client"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java index 25e40fcd6255..39f32bb0fc1c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinServerCodegen.java @@ -60,7 +60,7 @@ public class KotlinServerCodegen extends AbstractKotlinCodegen { public KotlinServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.of( @@ -80,7 +80,7 @@ public KotlinServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); artifactId = "kotlin-server"; packageName = "org.openapitools.server"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java index c1b781ce9ffc..8658f878432d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java @@ -85,7 +85,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen public KotlinSpringServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.of( @@ -105,7 +105,7 @@ public KotlinSpringServerCodegen() { .includeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); reservedWords.addAll(VARIABLE_RESERVED_WORDS); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinVertxServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinVertxServerCodegen.java index 193358867c64..3398363e5eb1 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinVertxServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinVertxServerCodegen.java @@ -54,7 +54,7 @@ public String getHelp() { public KotlinVertxServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf( @@ -72,7 +72,7 @@ public KotlinVertxServerCodegen() { .includeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) .stability(Stability.BETA) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java index 564931583b10..29e64126947f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/LuaClientCodegen.java @@ -57,7 +57,7 @@ public String getHelp() { public LuaClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.of( @@ -77,7 +77,7 @@ public LuaClientCodegen() { .includeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code/lua"; modelTemplateFiles.put("model.mustache", ".lua"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java index 71a681f0eb67..fdf1d994e9ba 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/MysqlSchemaCodegen.java @@ -63,7 +63,7 @@ public class MysqlSchemaCodegen extends DefaultCodegen implements CodegenConfig public MysqlSchemaCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.noneOf(WireFormatFeature.class)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -77,7 +77,7 @@ public MysqlSchemaCodegen() { SchemaSupportFeature.Polymorphism ) .clientModificationFeatures(EnumSet.noneOf(ClientModificationFeature.class)) - .build(); + ); // clear import mapping (from default generator) as mysql does not use import directives importMapping.clear(); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java index a0fefd2485d2..101dbab1fb9d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NimClientCodegen.java @@ -56,7 +56,7 @@ public String getHelp() { public NimClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -76,7 +76,7 @@ public NimClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) .stability(Stability.BETA) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java index 33f594db0ca6..73f9a133a588 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSExpressServerCodegen.java @@ -57,7 +57,7 @@ public class NodeJSExpressServerCodegen extends DefaultCodegen implements Codege public NodeJSExpressServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.of( @@ -75,7 +75,7 @@ public NodeJSExpressServerCodegen() { .includeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) .stability(Stability.BETA) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSServerCodegen.java index d4a3c7594afe..86a5eb7f35f5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/NodeJSServerCodegen.java @@ -61,7 +61,7 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig public NodeJSServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -77,7 +77,7 @@ public NodeJSServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); // mark the generator as deprecated in the documentation generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java index 73635c0fbd77..d3e022bf6d6d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OCamlClientCodegen.java @@ -75,7 +75,7 @@ public String getHelp() { public OCamlClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.of( @@ -93,7 +93,7 @@ public OCamlClientCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); outputFolder = "generated-code/ocaml"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java index b35a821bf9b7..2fa81b97dd4e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ObjcClientCodegen.java @@ -66,7 +66,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public ObjcClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.of( @@ -87,7 +87,7 @@ public ObjcClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); supportsInheritance = true; outputFolder = "generated-code" + File.separator + "objc"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java index 3cd85d211038..a2c9ec35c1a0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIGenerator.java @@ -39,7 +39,7 @@ public class OpenAPIGenerator extends DefaultCodegen implements CodegenConfig { public OpenAPIGenerator() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .documentationFeatures(EnumSet.allOf(DocumentationFeature.class)) .dataTypeFeatures(EnumSet.allOf(DataTypeFeature.class)) .wireFormatFeatures(EnumSet.allOf(WireFormatFeature.class)) @@ -47,7 +47,7 @@ public OpenAPIGenerator() { .globalFeatures(EnumSet.allOf(GlobalFeature.class)) .parameterFeatures(EnumSet.allOf(ParameterFeature.class)) .schemaSupportFeatures(EnumSet.allOf(SchemaSupportFeature.class)) - .build(); + ); embeddedTemplateDir = templateDir = "openapi"; outputFolder = "generated-code/openapi"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIYamlGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIYamlGenerator.java index 49c9fb788b22..4d678a5ad29f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIYamlGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/OpenAPIYamlGenerator.java @@ -43,7 +43,7 @@ public class OpenAPIYamlGenerator extends DefaultCodegen implements CodegenConfi public OpenAPIYamlGenerator() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .documentationFeatures(EnumSet.allOf(DocumentationFeature.class)) .dataTypeFeatures(EnumSet.allOf(DataTypeFeature.class)) .wireFormatFeatures(EnumSet.allOf(WireFormatFeature.class)) @@ -51,7 +51,7 @@ public OpenAPIYamlGenerator() { .globalFeatures(EnumSet.allOf(GlobalFeature.class)) .parameterFeatures(EnumSet.allOf(ParameterFeature.class)) .schemaSupportFeatures(EnumSet.allOf(SchemaSupportFeature.class)) - .build(); + ); embeddedTemplateDir = templateDir = "openapi-yaml"; outputFolder = "generated-code/openapi-yaml"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java index c11841e31598..8eef21d0e89d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PerlClientCodegen.java @@ -51,7 +51,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public PerlClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.of( @@ -73,7 +73,7 @@ public PerlClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); // add multiple inheritance support (beta) supportsMultipleInheritance = true; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java index 09524470cdb7..5e85b1e0a4d9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpClientCodegen.java @@ -39,7 +39,7 @@ public class PhpClientCodegen extends AbstractPhpCodegen { public PhpClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -52,7 +52,7 @@ public PhpClientCodegen() { .excludeSchemaSupportFeatures( SchemaSupportFeature.Polymorphism ) - .build(); + ); // clear import mapping (from default generator) as php does not use it // at the moment diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java index cccbc73925a1..f9aa0ecba440 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLaravelServerCodegen.java @@ -66,7 +66,7 @@ public String getHelp() { public PhpLaravelServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -79,7 +79,7 @@ public PhpLaravelServerCodegen() { .excludeSchemaSupportFeatures( SchemaSupportFeature.Polymorphism ) - .build(); + ); embeddedTemplateDir = templateDir = "php-laravel"; variableNamingConvention = "camelCase"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLumenServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLumenServerCodegen.java index dbfca2627782..e5ef7bba34cc 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLumenServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpLumenServerCodegen.java @@ -62,7 +62,7 @@ public String getHelp() { public PhpLumenServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -75,7 +75,7 @@ public PhpLumenServerCodegen() { .excludeSchemaSupportFeatures( SchemaSupportFeature.Polymorphism ) - .build(); + ); embeddedTemplateDir = templateDir = "php-lumen"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java index fb39852d2e9e..9307d1b221d8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSilexServerCodegen.java @@ -39,7 +39,7 @@ public class PhpSilexServerCodegen extends DefaultCodegen implements CodegenConf public PhpSilexServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -52,7 +52,7 @@ public PhpSilexServerCodegen() { .excludeSchemaSupportFeatures( SchemaSupportFeature.Polymorphism ) - .build(); + ); invokerPackage = camelize("OpenAPIServer"); String packageName = "OpenAPIServer"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java index 8c5d84a8e5b0..a7b6267394e8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlimServerCodegen.java @@ -49,7 +49,7 @@ public class PhpSlimServerCodegen extends AbstractPhpCodegen { public PhpSlimServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -62,7 +62,7 @@ public PhpSlimServerCodegen() { .excludeSchemaSupportFeatures( SchemaSupportFeature.Polymorphism ) - .build(); + ); generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) .stability(Stability.DEPRECATED) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java index 8d98f28e3dfd..8db491a15649 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java @@ -82,7 +82,7 @@ public class PhpSymfonyServerCodegen extends AbstractPhpCodegen implements Codeg public PhpSymfonyServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -95,7 +95,7 @@ public PhpSymfonyServerCodegen() { .excludeSchemaSupportFeatures( SchemaSupportFeature.Polymorphism ) - .build(); + ); // clear import mapping (from default generator) as php does not use it // at the moment diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpZendExpressivePathHandlerServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpZendExpressivePathHandlerServerCodegen.java index 19436f73ef83..2189189121d9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpZendExpressivePathHandlerServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpZendExpressivePathHandlerServerCodegen.java @@ -59,7 +59,7 @@ public String getHelp() { public PhpZendExpressivePathHandlerServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -72,7 +72,7 @@ public PhpZendExpressivePathHandlerServerCodegen() { .excludeSchemaSupportFeatures( SchemaSupportFeature.Polymorphism ) - .build(); + ); //no point to use double - http://php.net/manual/en/language.types.float.php , especially because of PHP 7+ float type declaration typeMapping.put("double", "float"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java index af8f712e93cf..cc2ba5bbd567 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PowerShellClientCodegen.java @@ -50,7 +50,7 @@ public class PowerShellClientCodegen extends DefaultCodegen implements CodegenCo public PowerShellClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML)) .securityFeatures(EnumSet.of( @@ -70,7 +70,7 @@ public PowerShellClientCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code" + File.separator + "powershell"; modelTemplateFiles.put("model.mustache", ".ps1"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java index 66c731d077fa..c2bccf21152f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java @@ -69,12 +69,12 @@ public ProtobufSchemaCodegen() { .stability(Stability.BETA) .build(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .includeWireFormatFeatures(WireFormatFeature.PROTOBUF) .wireFormatFeatures(EnumSet.of(WireFormatFeature.PROTOBUF)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) - .build(); + ); outputFolder = "generated-code/protobuf-schema"; modelTemplateFiles.put("model.mustache", ".proto"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAbstractConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAbstractConnexionServerCodegen.java index 21dd07fb6538..18256382d585 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAbstractConnexionServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAbstractConnexionServerCodegen.java @@ -65,9 +65,7 @@ public class PythonAbstractConnexionServerCodegen extends DefaultCodegen impleme public PythonAbstractConnexionServerCodegen(String templateDirectory, boolean fixBodyNameValue) { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); fixBodyName = fixBodyNameValue; modelPackage = "models"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java index c3afd660f4ac..7f9dd74bf3d2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonAiohttpConnexionServerCodegen.java @@ -28,7 +28,7 @@ public class PythonAiohttpConnexionServerCodegen extends PythonAbstractConnexion public PythonAiohttpConnexionServerCodegen() { super("python-aiohttp", true); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.of( @@ -49,7 +49,7 @@ public PythonAiohttpConnexionServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); testPackage = "tests"; embeddedTemplateDir = templateDir = "python-aiohttp"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java index dd60815d0d4f..6e7a32ca217c 100755 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonBluePlanetServerCodegen.java @@ -33,7 +33,7 @@ public class PythonBluePlanetServerCodegen extends PythonAbstractConnexionServer public PythonBluePlanetServerCodegen() { super("python-blueplanet", true); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.of( @@ -54,7 +54,7 @@ public PythonBluePlanetServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); testPackage = "tests"; embeddedTemplateDir = templateDir = "python-blueplanet"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java index f8ce69ed964d..ca59f763d74c 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientCodegen.java @@ -59,7 +59,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig public PythonClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.of( @@ -80,7 +80,7 @@ public PythonClientCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); // clear import mapping (from default generator) as python does not use it // at the moment diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java index a9c57e3f07a0..9ea7c3fbe34a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java @@ -53,7 +53,7 @@ public class PythonClientExperimentalCodegen extends PythonClientCodegen { public PythonClientExperimentalCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.of( @@ -74,7 +74,7 @@ public PythonClientExperimentalCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); // this may set datatype right for additional properties instantiationTypes.put("map", "dict"); @@ -706,6 +706,56 @@ public void postProcessParameter(CodegenParameter p) { } } + private void addNullDefaultToOneOfAnyOfReqProps(Schema schema, CodegenModel result){ + // for composed schema models, if the required properties are only from oneOf or anyOf models + // give them a nulltype.Null so the user can omit including them in python + ComposedSchema cs = (ComposedSchema) schema; + + // these are the properties that are from properties in self cs or cs allOf + Map selfProperties = new LinkedHashMap(); + List selfRequired = new ArrayList(); + + // these are the properties that are from properties in cs oneOf or cs anyOf + Map otherProperties = new LinkedHashMap(); + List otherRequired = new ArrayList(); + + List oneOfanyOfSchemas = new ArrayList<>(); + List oneOf = cs.getOneOf(); + if (oneOf != null) { + oneOfanyOfSchemas.addAll(oneOf); + } + List anyOf = cs.getAnyOf(); + if (anyOf != null) { + oneOfanyOfSchemas.addAll(anyOf); + } + for (Schema sc: oneOfanyOfSchemas) { + Schema refSchema = ModelUtils.getReferencedSchema(this.openAPI, sc); + addProperties(otherProperties, otherRequired, refSchema); + } + Set otherRequiredSet = new HashSet(otherRequired); + + List allOf = cs.getAllOf(); + if ((schema.getProperties() != null && !schema.getProperties().isEmpty()) || allOf != null) { + // NOTE: this function also adds the allOf propesrties inside schema + addProperties(selfProperties, selfRequired, schema); + } + if (result.discriminator != null) { + selfRequired.add(result.discriminator.getPropertyBaseName()); + } + Set selfRequiredSet = new HashSet(selfRequired); + + List reqVars = result.getRequiredVars(); + if (reqVars != null) { + for (CodegenProperty cp: reqVars) { + String propName = cp.baseName; + if (otherRequiredSet.contains(propName) && !selfRequiredSet.contains(propName)) { + // if var is in otherRequiredSet and is not in selfRequiredSet and is in result.requiredVars + // then set it to nullable because the user doesn't have to give a value for it + cp.setDefaultValue("nulltype.Null"); + } + } + } + } /** * Convert OAS Model object to Codegen Model object @@ -806,6 +856,11 @@ public CodegenModel fromModel(String name, Schema schema) { if (result.imports.contains(result.classname)) { result.imports.remove(result.classname); } + + if (result.requiredVars.size() > 0 && (result.oneOf.size() > 0 || result.anyOf.size() > 0)) { + addNullDefaultToOneOfAnyOfReqProps(schema, result); + } + return result; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java index a6551c030121..85be42aca6f7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RClientCodegen.java @@ -71,7 +71,7 @@ public String getHelp() { public RClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.of( @@ -95,7 +95,7 @@ public RClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); outputFolder = "generated-code/r"; modelTemplateFiles.put("model.mustache", ".R"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java index 9022c2462fc0..f28e94e6a9ce 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java @@ -70,7 +70,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { public RubyClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.of( @@ -95,7 +95,7 @@ public RubyClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); supportsInheritance = true; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java index ddcc5c6f21ed..5dcd18c372b3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyOnRailsServerCodegen.java @@ -74,7 +74,7 @@ public class RubyOnRailsServerCodegen extends AbstractRubyCodegen { public RubyOnRailsServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -90,7 +90,7 @@ public RubyOnRailsServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code" + File.separator + "rails5"; apiPackage = "app/controllers"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java index 7f626aade4c0..23126e3b4a5a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubySinatraServerCodegen.java @@ -43,7 +43,7 @@ public class RubySinatraServerCodegen extends AbstractRubyCodegen { public RubySinatraServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -59,7 +59,7 @@ public RubySinatraServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); apiPackage = "lib"; outputFolder = "generated-code" + File.separator + "sinatra"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java index 9292e7a82666..1f81ba8133be 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java @@ -65,7 +65,7 @@ public String getHelp() { public RustClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.of( @@ -89,7 +89,7 @@ public RustClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); outputFolder = "generated-code/rust"; modelTemplateFiles.put("model.mustache", ".rs"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java index b32bb274fd93..1076e3f545d2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java @@ -76,7 +76,7 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { public RustServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.of( @@ -101,7 +101,7 @@ public RustServerCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); // Show the generation timestamp by default diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java index 7b3938edf418..cc2c15091b13 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaAkkaClientCodegen.java @@ -49,6 +49,7 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code protected boolean registerNonStandardStatusCodes = true; protected boolean renderJavadoc = true; protected boolean removeOAuthSecurities = true; + // protected boolean stripPackageName = false; @SuppressWarnings("hiding") @@ -57,7 +58,7 @@ public class ScalaAkkaClientCodegen extends AbstractScalaCodegen implements Code public ScalaAkkaClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.of( @@ -81,7 +82,7 @@ public ScalaAkkaClientCodegen() { ClientModificationFeature.BasePath, ClientModificationFeature.UserAgent ) - .build(); + ); outputFolder = "generated-code/scala-akka"; modelTemplateFiles.put("model.mustache", ".scala"); @@ -304,11 +305,6 @@ public String toDefaultValue(Schema p) { } } - @Override - public String toModelName(final String name) { - return formatIdentifier(name, true); - } - private static abstract class CustomLambda implements Mustache.Lambda { @Override public void execute(Template.Fragment frag, Writer out) throws IOException { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaFinchServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaFinchServerCodegen.java index 000f0add07c9..d49f37e56225 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaFinchServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaFinchServerCodegen.java @@ -42,7 +42,7 @@ public class ScalaFinchServerCodegen extends DefaultCodegen implements CodegenCo public ScalaFinchServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -58,7 +58,7 @@ public ScalaFinchServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code/finch"; modelTemplateFiles.put("model.mustache", ".scala"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java index 304b43a14ba8..4cd79f8644e3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaGatlingCodegen.java @@ -82,7 +82,7 @@ public ScalaGatlingCodegen() { // Although the generator supports authorization, it's done via manual header modification and it's done // globally. This means it doesn't _technically_ support auth per OpenAPI Spec (which would allow, for example, a different API key per operation), // so it's not listed here as supported. - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -101,7 +101,7 @@ public ScalaGatlingCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); sourceFolder = "src" + File.separator + "gatling" + File.separator + "scala"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java index 0d6462160fd3..1f4a5f238591 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttpClientCodegen.java @@ -55,7 +55,7 @@ public ScalaHttpClientCodegen() { .stability(Stability.DEPRECATED) .build(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -74,7 +74,7 @@ public ScalaHttpClientCodegen() { .includeClientModificationFeatures( ClientModificationFeature.BasePath ) - .build(); + ); outputFolder = "generated-code/scala-http-client"; modelTemplateFiles.put("model.mustache", ".scala"); @@ -105,7 +105,6 @@ public ScalaHttpClientCodegen() { additionalProperties.put("authScheme", authScheme); additionalProperties.put("authPreemptive", authPreemptive); additionalProperties.put("clientName", clientName); - additionalProperties.put(CodegenConstants.STRIP_PACKAGE_NAME, stripPackageName); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("apiInvoker.mustache", @@ -267,31 +266,6 @@ public String toOperationId(String operationId) { return camelize(operationId, true); } - @Override - public String toModelName(final String name) { - final String sanitizedName = sanitizeName(modelNamePrefix + this.stripPackageName(name) + modelNameSuffix); - - // camelize the model name - // phone_number => PhoneNumber - final String camelizedName = camelize(sanitizedName); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(camelizedName)) { - final String modelName = "Model" + camelizedName; - LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); - return modelName; - } - - // model name starts with number - if (name.matches("^\\d.*")) { - final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); - return modelName; - } - - return camelizedName; - } - @Override public String toEnumName(CodegenProperty property) { return formatIdentifier(stripPackageName(property.baseName), true); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java index c7f97cc6903d..4b8b48b4d880 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaLagomServerCodegen.java @@ -39,7 +39,7 @@ public class ScalaLagomServerCodegen extends AbstractScalaCodegen implements Cod public ScalaLagomServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -55,7 +55,7 @@ public ScalaLagomServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code/scala-lagom-server"; modelTemplateFiles.put("model.mustache", ".scala"); @@ -229,35 +229,6 @@ public String toOperationId(String operationId) { return camelize(operationId, true); } - @Override - public String toModelName(final String name) { - final String sanitizedName = sanitizeName(modelNamePrefix + name + modelNameSuffix); - - // camelize the model name - // phone_number => PhoneNumber - final String camelizedName = camelize(sanitizedName); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(camelizedName)) { - final String modelName = "Model" + camelizedName; - LOGGER.warn( - camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); - return modelName; - } - - // model name starts with number - if (name.matches("^\\d.*")) { - final String modelName = - "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn( - name + " (model name starts with number) cannot be used as model name. Renamed to " - + modelName); - return modelName; - } - - return camelizedName; - } - @Override public Map postProcessModelsEnum(Map objs) { objs = super.postProcessModelsEnum(objs); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java index 11acf405ff22..d0a723156778 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPlayFrameworkServerCodegen.java @@ -59,7 +59,7 @@ public class ScalaPlayFrameworkServerCodegen extends AbstractScalaCodegen implem public ScalaPlayFrameworkServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -75,7 +75,7 @@ public ScalaPlayFrameworkServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code" + File.separator + "scala-play-server"; modelTemplateFiles.put("model.mustache", ".scala"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java new file mode 100644 index 000000000000..2c1441c2bdef --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaSttpClientCodegen.java @@ -0,0 +1,96 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.servers.Server; +import org.openapitools.codegen.CodegenConfig; +import org.openapitools.codegen.CodegenOperation; +import org.openapitools.codegen.SupportingFile; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; + +import java.io.File; +import java.util.List; + +public class ScalaSttpClientCodegen extends ScalaAkkaClientCodegen implements CodegenConfig { + protected String mainPackage = "org.openapitools.client"; + + public ScalaSttpClientCodegen() { + super(); + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + embeddedTemplateDir = templateDir = "scala-sttp"; + outputFolder = "generated-code/scala-sttp"; + } + + @Override + public void processOpts() { + super.processOpts(); + if (additionalProperties.containsKey("mainPackage")) { + setMainPackage((String) additionalProperties.get("mainPackage")); + additionalProperties.replace("configKeyPath", this.configKeyPath); + apiPackage = mainPackage + ".api"; + modelPackage = mainPackage + ".model"; + invokerPackage = mainPackage + ".core"; + additionalProperties.put("apiPackage", apiPackage); + additionalProperties.put("modelPackage", modelPackage); + } + + if (!additionalProperties.containsKey("java8")) { + additionalProperties.put("joda", "true"); + } + + supportingFiles.clear(); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); + final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("requests.mustache", invokerFolder, "requests.scala")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", invokerFolder, "ApiInvoker.scala")); + final String apiFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, "EnumsSerializers.scala")); + supportingFiles.add(new SupportingFile("serializers.mustache", invokerFolder, "Serializers.scala")); + } + + @Override + public String getName() { + return "scala-sttp"; + } + + @Override + public String getHelp() { + return "Generates a Scala client library (beta) based on Sttp."; + } + + @Override + public String encodePath(String input) { + String result = super.encodePath(input); + return result.replace("{", "${"); + } + + @Override + public CodegenOperation fromOperation(String path, + String httpMethod, + Operation operation, + List servers) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); + op.path = encodePath(path); + return op; + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalatraServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalatraServerCodegen.java index c511b29ba894..4e8caa4d0179 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalatraServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalatraServerCodegen.java @@ -31,7 +31,7 @@ public class ScalatraServerCodegen extends AbstractScalaCodegen implements Codeg public ScalatraServerCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) @@ -47,7 +47,7 @@ public ScalatraServerCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code/scalatra"; modelTemplateFiles.put("model.mustache", ".scala"); @@ -57,17 +57,6 @@ public ScalatraServerCodegen() { apiPackage = "org.openapitools.server.api"; modelPackage = "org.openapitools.server.model"; - setReservedWordsLowerCase( - Arrays.asList( - "abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while", "type") - ); - defaultIncludes = new HashSet( Arrays.asList("double", "Int", diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java index 8274a6aa657e..4248eb890cfd 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalazClientCodegen.java @@ -45,7 +45,7 @@ public class ScalazClientCodegen extends AbstractScalaCodegen implements Codegen public ScalazClientCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) .excludeGlobalFeatures( @@ -60,7 +60,7 @@ public ScalazClientCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code/scalaz"; embeddedTemplateDir = templateDir = "scalaz"; @@ -274,31 +274,6 @@ public String toOperationId(String operationId) { return camelize(operationId, true); } - @Override - public String toModelName(final String name) { - final String sanitizedName = sanitizeName(modelNamePrefix + this.stripPackageName(name) + modelNameSuffix); - - // camelize the model name - // phone_number => PhoneNumber - final String camelizedName = camelize(sanitizedName); - - // model name cannot use reserved keyword, e.g. return - if (isReservedWord(camelizedName)) { - final String modelName = "Model" + camelizedName; - LOGGER.warn(camelizedName + " (reserved word) cannot be used as model name. Renamed to " + modelName); - return modelName; - } - - // model name starts with number - if (name.matches("^\\d.*")) { - final String modelName = "Model" + camelizedName; // e.g. 200Response => Model200Response (after camelize) - LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + modelName); - return modelName; - } - - return camelizedName; - } - private static abstract class CustomLambda implements Mustache.Lambda { @Override public void execute(Template.Fragment frag, Writer out) throws IOException { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java index 5478f307bc93..8450fbd5f4de 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java @@ -102,7 +102,7 @@ public class SpringCodegen extends AbstractJavaCodegen public SpringCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .includeDocumentationFeatures(DocumentationFeature.Readme) .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) .securityFeatures(EnumSet.of( @@ -127,7 +127,7 @@ public SpringCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code/javaSpring"; embeddedTemplateDir = templateDir = "JavaSpring"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticDocCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticDocCodegen.java index 9faa3e7144ab..ce43779dfd74 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticDocCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticDocCodegen.java @@ -33,7 +33,7 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { public StaticDocCodegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .documentationFeatures(EnumSet.allOf(DocumentationFeature.class)) .dataTypeFeatures(EnumSet.allOf(DataTypeFeature.class)) .wireFormatFeatures(EnumSet.allOf(WireFormatFeature.class)) @@ -41,7 +41,7 @@ public StaticDocCodegen() { .globalFeatures(EnumSet.allOf(GlobalFeature.class)) .parameterFeatures(EnumSet.allOf(ParameterFeature.class)) .schemaSupportFeatures(EnumSet.allOf(SchemaSupportFeature.class)) - .build(); + ); // clear import mapping (from default generator) as this generator does not use it // at the moment diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java index 2c523d6c6b0b..347b371c7769 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtml2Generator.java @@ -55,7 +55,7 @@ public class StaticHtml2Generator extends DefaultCodegen implements CodegenConfi public StaticHtml2Generator() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .documentationFeatures(EnumSet.allOf(DocumentationFeature.class)) .dataTypeFeatures(EnumSet.allOf(DataTypeFeature.class)) .wireFormatFeatures(EnumSet.allOf(WireFormatFeature.class)) @@ -63,7 +63,7 @@ public StaticHtml2Generator() { .globalFeatures(EnumSet.allOf(GlobalFeature.class)) .parameterFeatures(EnumSet.allOf(ParameterFeature.class)) .schemaSupportFeatures(EnumSet.allOf(SchemaSupportFeature.class)) - .build(); + ); outputFolder = "docs"; embeddedTemplateDir = templateDir = "htmlDocs2"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtmlGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtmlGenerator.java index a633da650a86..c50f4492b402 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtmlGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/StaticHtmlGenerator.java @@ -41,7 +41,7 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig public StaticHtmlGenerator() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .documentationFeatures(EnumSet.allOf(DocumentationFeature.class)) .dataTypeFeatures(EnumSet.allOf(DataTypeFeature.class)) .wireFormatFeatures(EnumSet.allOf(WireFormatFeature.class)) @@ -49,7 +49,7 @@ public StaticHtmlGenerator() { .globalFeatures(EnumSet.allOf(GlobalFeature.class)) .parameterFeatures(EnumSet.allOf(ParameterFeature.class)) .schemaSupportFeatures(EnumSet.allOf(SchemaSupportFeature.class)) - .build(); + ); outputFolder = "docs"; embeddedTemplateDir = templateDir = "htmlDocs"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift3Codegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift3Codegen.java index 1f5e53684105..e2f798df5dc2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift3Codegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift3Codegen.java @@ -76,7 +76,7 @@ public Swift3Codegen() { .stability(Stability.DEPRECATED) .build(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) .excludeGlobalFeatures( @@ -91,7 +91,7 @@ public Swift3Codegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code" + File.separator + "swift"; modelTemplateFiles.put("model.mustache", ".swift"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java index 77389ce3f907..b15c045efd7a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift4Codegen.java @@ -78,7 +78,7 @@ public class Swift4Codegen extends DefaultCodegen implements CodegenConfig { public Swift4Codegen() { super(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.of( SecurityFeature.BasicAuth, @@ -97,7 +97,7 @@ public Swift4Codegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code" + File.separator + "swift"; modelTemplateFiles.put("model.mustache", ".swift"); @@ -148,7 +148,9 @@ public Swift4Codegen() { Arrays.asList( // Added for Objective-C compatibility "id", "description", "NSArray", "NSURL", "CGFloat", "NSSet", "NSString", "NSInteger", "NSUInteger", - "NSError", "NSDictionary" + "NSError", "NSDictionary", + // Cannot override with a stored property 'className' + "className" ) ); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java index 610da984c856..f5bf07815349 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java @@ -133,7 +133,9 @@ public Swift5ClientCodegen() { Arrays.asList( // Added for Objective-C compatibility "id", "description", "NSArray", "NSURL", "CGFloat", "NSSet", "NSString", "NSInteger", "NSUInteger", - "NSError", "NSDictionary" + "NSError", "NSDictionary", + // Cannot override with a stored property 'className' + "className" ) ); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftClientCodegen.java index c5daa1f54cd1..039d271fa053 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftClientCodegen.java @@ -95,7 +95,7 @@ public SwiftClientCodegen() { .stability(Stability.DEPRECATED) .build(); - featureSet = getFeatureSet().modify() + modifyFeatureSet(features -> features .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON)) .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) .excludeGlobalFeatures( @@ -110,7 +110,7 @@ public SwiftClientCodegen() { .excludeParameterFeatures( ParameterFeature.Cookie ) - .build(); + ); outputFolder = "generated-code" + File.separator + "swift"; modelTemplateFiles.put("model.mustache", ".swift"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java index 99dfa285bbbd..1c28aac54396 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java @@ -71,9 +71,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode public TypeScriptAngularClientCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); this.outputFolder = "generated-code/typescript-angular"; @@ -456,7 +454,7 @@ public Map postProcessOperationsWithModels(Map o // Add the more complicated component instead of just the brace. CodegenParameter parameter = findPathParameterByName(op, parameterName.toString()); - pathBuffer.append(toVarName(parameterName.toString())); + pathBuffer.append(toParamName(parameterName.toString())); if (parameter != null && parameter.isDateTime) { pathBuffer.append(".toISOString()"); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java index 4d9f14383500..a441027bff06 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAxiosClientCodegen.java @@ -44,9 +44,7 @@ public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodege public TypeScriptAxiosClientCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); // clear import mapping (from default generator) as TS does not use it // at the moment diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java index 9ea63beb2cf7..b1ab5e4fa818 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java @@ -48,9 +48,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege public TypeScriptFetchClientCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); // clear import mapping (from default generator) as TS does not use it // at the moment @@ -66,6 +64,7 @@ public TypeScriptFetchClientCodegen() { typeMapping.put("date", "Date"); typeMapping.put("DateTime", "Date"); + supportModelPropertyNaming(CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.camelCase); this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json")); this.cliOptions.add(new CliOption(WITH_INTERFACES, "Setting this property to true will generate interfaces next to the default class implementations.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); this.cliOptions.add(new CliOption(USE_SINGLE_REQUEST_PARAMETER, "Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.TRUE.toString())); @@ -102,8 +101,8 @@ public void setTypescriptThreePlus(Boolean typescriptThreePlus) { @Override public void processOpts() { super.processOpts(); - additionalProperties.put("isOriginalModelPropertyNaming", getModelPropertyNaming().equals("original")); - additionalProperties.put("modelPropertyNaming", getModelPropertyNaming()); + additionalProperties.put("isOriginalModelPropertyNaming", getModelPropertyNaming() == CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.original); + additionalProperties.put("modelPropertyNaming", getModelPropertyNaming().name()); String sourceDir = ""; if (additionalProperties.containsKey(NPM_NAME)) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java index 75b91392fa1a..93f47c09b5e5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptInversifyClientCodegen.java @@ -44,9 +44,7 @@ public class TypeScriptInversifyClientCodegen extends AbstractTypeScriptClientCo public TypeScriptInversifyClientCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); this.outputFolder = "generated-code/typescript-inversify"; @@ -225,7 +223,7 @@ public Map postProcessOperationsWithModels(Map o insideCurly--; // Add the more complicated component instead of just the brace. - pathBuffer.append(toVarName(parameterName.toString())); + pathBuffer.append(toParamName(parameterName.toString())); pathBuffer.append("))}"); parameterName.setLength(0); break; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java index 275af5c82e2d..c680840da7ad 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptJqueryClientCodegen.java @@ -40,9 +40,7 @@ public class TypeScriptJqueryClientCodegen extends AbstractTypeScriptClientCodeg public TypeScriptJqueryClientCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); modelTemplateFiles.put("model.mustache", ".ts"); apiTemplateFiles.put("api.mustache", ".ts"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java index a56ae5ce7c98..6a46fbc78dd0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptNodeClientCodegen.java @@ -64,6 +64,7 @@ public TypeScriptNodeClientCodegen() { modelPackage = "model"; apiPackage = "api"; + supportModelPropertyNaming(CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.camelCase); this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json")); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptReduxQueryClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptReduxQueryClientCodegen.java index 33e82b8e87b8..26f6fb6f06b3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptReduxQueryClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptReduxQueryClientCodegen.java @@ -61,6 +61,7 @@ public TypeScriptReduxQueryClientCodegen() { typeMapping.put("date", "Date"); typeMapping.put("DateTime", "Date"); + supportModelPropertyNaming(CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.camelCase); this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json")); this.cliOptions.add(new CliOption(WITH_INTERFACES, "Setting this property to true will generate interfaces next to the default class implementations.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); this.cliOptions.add(new CliOption(USE_SINGLE_REQUEST_PARAMETER, "Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.TRUE.toString())); @@ -87,8 +88,8 @@ public void setNpmRepository(String npmRepository) { @Override public void processOpts() { super.processOpts(); - additionalProperties.put("isOriginalModelPropertyNaming", getModelPropertyNaming().equals("original")); - additionalProperties.put("modelPropertyNaming", getModelPropertyNaming()); + additionalProperties.put("isOriginalModelPropertyNaming", getModelPropertyNaming() == CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.original); + additionalProperties.put("modelPropertyNaming", getModelPropertyNaming().name()); supportingFiles.add(new SupportingFile("index.mustache", "src", "index.ts")); supportingFiles.add(new SupportingFile("runtime.mustache", "src", "runtime.ts")); supportingFiles.add(new SupportingFile("tsconfig.mustache", "", "tsconfig.json")); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java index 13a17b5f518c..fbcad1bc8048 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptRxjsClientCodegen.java @@ -21,6 +21,8 @@ import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.parser.util.SchemaTypeUtil; import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.FeatureSet; +import org.openapitools.codegen.meta.GeneratorMetadata; import org.openapitools.codegen.meta.features.DocumentationFeature; import org.openapitools.codegen.utils.ModelUtils; import org.slf4j.Logger; @@ -43,9 +45,7 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen public TypeScriptRxjsClientCodegen() { super(); - featureSet = getFeatureSet().modify() - .includeDocumentationFeatures(DocumentationFeature.Readme) - .build(); + modifyFeatureSet(features -> features.includeDocumentationFeatures(DocumentationFeature.Readme)); outputFolder = "generated-code/typescript-rxjs"; embeddedTemplateDir = templateDir = "typescript-rxjs"; @@ -89,8 +89,6 @@ public void setNpmRepository(String npmRepository) { @Override public void processOpts() { super.processOpts(); - additionalProperties.put("isOriginalModelPropertyNaming", getModelPropertyNaming().equals("original")); - additionalProperties.put("modelPropertyNaming", getModelPropertyNaming()); supportingFiles.add(new SupportingFile("index.mustache", "", "index.ts")); supportingFiles.add(new SupportingFile("runtime.mustache", "", "runtime.ts")); supportingFiles.add(new SupportingFile("apis.index.mustache", apiPackage().replace('.', File.separatorChar), "index.ts")); diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index c48f628a3aac..89cbc16b8965 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -126,3 +126,4 @@ org.openapitools.codegen.languages.AsciidocDocumentationCodegen org.openapitools.codegen.languages.FsharpFunctionsServerCodegen org.openapitools.codegen.languages.MarkdownDocumentationCodegen +org.openapitools.codegen.languages.ScalaSttpClientCodegen diff --git a/modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache index 74125fc936ec..028365600740 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt5-client/CMakeLists.txt.mustache @@ -5,7 +5,11 @@ set(CMAKE_VERBOSE_MAKEFILE ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_AUTOMOC ON) -set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -Wall -Wno-unused-variable") +if (MSVC) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4") +else () + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -Wall -Wno-unused-variable") +endif () find_package(Qt5Core REQUIRED) find_package(Qt5Network REQUIRED){{#contentCompression}} diff --git a/modules/openapi-generator/src/main/resources/python-flask/controller.mustache b/modules/openapi-generator/src/main/resources/python-flask/controller.mustache index 243da33e5709..9b7fdb198743 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/controller.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/controller.mustache @@ -69,7 +69,7 @@ def {{operationId}}({{#allParams}}{{paramName}}{{^required}}=None{{/required}}{{ {{^isFile}} {{^isUuid}} if connexion.request.is_json: - {{paramName}} = {{baseType}}.from_dict(connexion.request.get_json()) # noqa: E501 + {{paramName}} = {{#baseType}}{{baseType}}{{/baseType}}{{^baseType}}{{#dataType}} {{dataType}}{{/dataType}}{{/baseType}}.from_dict(connexion.request.get_json()) # noqa: E501 {{/isUuid}} {{/isFile}} {{/isPrimitiveType}} diff --git a/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache b/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache index 921d67d029a2..b5dab7b9af0b 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/requirements.mustache @@ -1,4 +1,4 @@ -connexion >= 2.5.0; python_version>="3.6" +connexion >= 2.6.0; python_version>="3.6" connexion >= 2.3.0; python_version=="3.5" connexion >= 2.3.0; python_version=="3.4" connexion == 2.4.0; python_version<="2.7" diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model.mustache index 0ca198ddf96c..ef7da5728252 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model.mustache @@ -7,6 +7,7 @@ import re # noqa: F401 import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from {{packageName}}.model_utils import ( # noqa: F401 ModelComposed, diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_composed.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_composed.mustache index 5a1ece1f9266..e00bf129b247 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_composed.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_composed.mustache @@ -17,11 +17,18 @@ '_from_server': _from_server, '_configuration': _configuration, } - model_args = { + required_args = { {{#requiredVars}} '{{name}}': {{name}}, {{/requiredVars}} } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) @@ -30,9 +37,8 @@ self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] -{{#requiredVars}} - self.{{name}} = {{name}} -{{/requiredVars}} + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) for var_name, var_value in six.iteritems(kwargs): if var_name in unused_args and \ self._configuration is not None and \ diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_shared.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_shared.mustache index 318d693e15d0..9dd5bc2b6f3f 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_shared.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/method_init_shared.mustache @@ -1,11 +1,23 @@ def __init__(self{{#requiredVars}}{{^defaultValue}}, {{name}}{{/defaultValue}}{{/requiredVars}}{{#requiredVars}}{{#defaultValue}}, {{name}}={{{defaultValue}}}{{/defaultValue}}{{/requiredVars}}, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """{{classname}} - a model defined in OpenAPI -{{#requiredVars}}{{^hasMore}} Args:{{/hasMore}}{{/requiredVars}}{{#requiredVars}}{{^defaultValue}} - {{name}} ({{{dataType}}}):{{#description}} {{description}}{{/description}}{{/defaultValue}}{{/requiredVars}}{{#requiredVars}}{{^hasMore}} -{{/hasMore}}{{/requiredVars}} - Keyword Args:{{#requiredVars}}{{#defaultValue}} - {{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} defaults to {{{defaultValue}}}, must be one of [{{{defaultValue}}}] # noqa: E501{{/defaultValue}}{{/requiredVars}} +{{#requiredVars}} +{{#-first}} + Args: +{{/-first}} +{{^defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{description}}{{/description}} +{{/defaultValue}} +{{#-last}} + +{{/-last}} +{{/requiredVars}} + Keyword Args: +{{#requiredVars}} +{{#defaultValue}} + {{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} defaults to {{{defaultValue}}}{{#allowableValues}}, must be one of [{{#enumVars}}{{{value}}}, {{/enumVars}}]{{/allowableValues}} # noqa: E501 +{{/defaultValue}} +{{/requiredVars}} _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. @@ -18,8 +30,10 @@ _configuration (Configuration): the instance to use when deserializing a file_type parameter. If passed, type conversion is attempted - If omitted no type conversion is done.{{#optionalVars}} - {{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} # noqa: E501{{/optionalVars}} + If omitted no type conversion is done. +{{#optionalVars}} + {{name}} ({{{dataType}}}):{{#description}} {{description}}.{{/description}} [optional]{{#defaultValue}} if omitted the server will use the default value of {{{defaultValue}}}{{/defaultValue}} # noqa: E501 +{{/optionalVars}} """ self._data_store = {} diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_setattr_getattr_composed.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_setattr_getattr_composed.mustache index e5eee88a9608..9adb2a08a1fb 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_setattr_getattr_composed.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_templates/methods_setattr_getattr_composed.mustache @@ -41,21 +41,23 @@ if self._path_to_item: path_to_item.extend(self._path_to_item) path_to_item.append(name) + values = set() if model_instances: - values = set() for model_instance in model_instances: if name in model_instance._data_store: values.add(model_instance._data_store[name]) - if len(values) == 1: - return list(values)[0] + len_values = len(values) + if len_values == 0: + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + path_to_item + ) + elif len_values == 1: + return list(values)[0] + elif len_values > 1: raise ApiValueError( "Values stored for property {0} in {1} difffer when looking " "at self and self's composed instances. All values must be " "the same".format(name, type(self).__name__), path_to_item - ) - - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) \ No newline at end of file + ) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/model_utils.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/model_utils.mustache index 8193d8a3b2a9..7f05f2dbe855 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/model_utils.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/model_utils.mustache @@ -828,7 +828,7 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas() is not None: - model_instances = model_instance._composed_instances + model_instances.extend(model_instance._composed_instances) for model_instance in model_instances: for attr, value in six.iteritems(model_instance._data_store): if serialize: @@ -951,12 +951,12 @@ def get_oneof_instance(self, model_args, constant_args): used to make instances Returns - oneof_instance (instance) + oneof_instance (instance/None) """ - oneof_instance = None if len(self._composed_schemas()['oneOf']) == 0: - return oneof_instance + return None + oneof_instances = [] for oneof_class in self._composed_schemas()['oneOf']: # transform js keys to python keys in fixed_model_args fixed_model_args = change_keys_js_to_python( @@ -969,20 +969,30 @@ def get_oneof_instance(self, model_args, constant_args): if var_name in fixed_model_args: kwargs[var_name] = fixed_model_args[var_name] + # do not try to make a model with no input args + if len(kwargs) == 0: + continue + # and use it to make the instance kwargs.update(constant_args) try: oneof_instance = oneof_class(**kwargs) - break + oneof_instances.append(oneof_instance) except Exception: pass - if oneof_instance is None: + if len(oneof_instances) == 0: raise ApiValueError( "Invalid inputs given to generate an instance of %s. Unable to " "make any instances of the classes in oneOf definition." % self.__class__.__name__ ) - return oneof_instance + elif len(oneof_instances) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Multiple " + "oneOf instances were generated when a max of one is allowed." % + self.__class__.__name__ + ) + return oneof_instances[0] def get_anyof_instances(self, model_args, constant_args): @@ -1012,6 +1022,10 @@ def get_anyof_instances(self, model_args, constant_args): if var_name in fixed_model_args: kwargs[var_name] = fixed_model_args[var_name] + # do not try to make a model with no input args + if len(kwargs) == 0: + continue + # and use it to make the instance kwargs.update(constant_args) try: diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/requirements.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/requirements.mustache index eb358efd5bd3..a56bedffbf57 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/requirements.mustache @@ -1,3 +1,4 @@ +nulltype certifi >= 14.05.14 future; python_version<="2.7" six >= 1.10 diff --git a/modules/openapi-generator/src/main/resources/python/python-experimental/setup.mustache b/modules/openapi-generator/src/main/resources/python/python-experimental/setup.mustache index 2fe84efcee06..796475c45642 100644 --- a/modules/openapi-generator/src/main/resources/python/python-experimental/setup.mustache +++ b/modules/openapi-generator/src/main/resources/python/python-experimental/setup.mustache @@ -21,6 +21,7 @@ REQUIRES = [ "six >= 1.10", "certifi", "python-dateutil", + "nulltype", {{#asyncio}} "aiohttp >= 3.0.0", {{/asyncio}} diff --git a/modules/openapi-generator/src/main/resources/ruby-client/Gemfile.mustache b/modules/openapi-generator/src/main/resources/ruby-client/Gemfile.mustache index 69255e559f7c..c2e3127cdcfe 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/Gemfile.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/Gemfile.mustache @@ -3,7 +3,7 @@ source 'https://rubygems.org' gemspec group :development, :test do - gem 'rake', '~> 12.0.0' + gem 'rake', '~> 13.0.1' gem 'pry-byebug' gem 'rubocop', '~> 0.66.0' end diff --git a/modules/openapi-generator/src/main/resources/ruby-client/api_client_spec.mustache b/modules/openapi-generator/src/main/resources/ruby-client/api_client_spec.mustache index 364c60419c4f..a079cc9fd350 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/api_client_spec.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/api_client_spec.mustache @@ -150,7 +150,7 @@ describe {{moduleName}}::ApiClient do end it 'fails for invalid collection format' do - expect{api_client.build_collection_param(param, :INVALID)}.to raise_error(RuntimeError, 'unknown collection format: :INVALID') + expect { api_client.build_collection_param(param, :INVALID) }.to raise_error(RuntimeError, 'unknown collection format: :INVALID') end end diff --git a/modules/openapi-generator/src/main/resources/ruby-client/rubocop.mustache b/modules/openapi-generator/src/main/resources/ruby-client/rubocop.mustache index 0ef33ce5e322..df46058490d0 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/rubocop.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/rubocop.mustache @@ -14,12 +14,6 @@ AllCops: Style/AndOr: Enabled: true -# Do not use braces for hash literals when they are the last argument of a -# method call. -Style/BracesAroundHashParameters: - Enabled: true - EnforcedStyle: context_dependent - # Align `when` with `case`. Layout/CaseIndentation: Enabled: true @@ -46,7 +40,7 @@ Layout/EmptyLinesAroundMethodBody: Layout/EmptyLinesAroundModuleBody: Enabled: true -Layout/IndentFirstArgument: +Layout/FirstArgumentIndentation: Enabled: true # Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. @@ -57,7 +51,7 @@ Style/HashSyntax: # extra level of indentation. Layout/IndentationConsistency: Enabled: true - EnforcedStyle: rails + EnforcedStyle: indented_internal_methods # Two spaces, no tabs (for indentation). Layout/IndentationWidth: @@ -123,7 +117,7 @@ Layout/Tab: Enabled: true # Blank lines should not have any spaces. -Layout/TrailingBlankLines: +Layout/TrailingEmptyLines: Enabled: true # No trailing whitespace. @@ -131,7 +125,7 @@ Layout/TrailingWhitespace: Enabled: false # Use quotes for string literals when they are enough. -Style/UnneededPercentQ: +Style/RedundantPercentQ: Enabled: true # Align `end` with the matching keyword or starting expression except for diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/methodParameters.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/methodParameters.mustache index 256265710733..54dc2f92a51f 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-client/methodParameters.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/methodParameters.mustache @@ -1 +1 @@ -{{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}{{#isContainer}}{{dataType}}{{/isContainer}}{{^isContainer}}Option[{{dataType}}]{{/isContainer}}{{/required}}{{^defaultValue}}{{^required}}{{^isContainer}} = None{{/isContainer}}{{/required}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#authMethods.0}})(implicit {{#authMethods}}{{#isApiKey}}apiKey: ApiKeyValue{{/isApiKey}}{{#isBasic}}{{#isBasicBasic}}basicAuth: BasicCredentials{{/isBasicBasic}}{{#isBasicBearer}}bearerToken: BearerToken{{/isBasicBearer}}{{/isBasic}}{{#hasMore}}, {{/hasMore}}{{/authMethods}}{{/authMethods.0}} +{{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}{{#isContainer}}{{dataType}}{{/isContainer}}{{^isContainer}}Option[{{dataType}}]{{/isContainer}}{{/required}}{{^defaultValue}}{{^required}}{{^isContainer}} = None{{/isContainer}}{{/required}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#authMethods.0}})(implicit {{#authMethods}}{{#isApiKey}}apiKey: ApiKeyValue{{/isApiKey}}{{#isBasic}}{{#isBasicBasic}}basicAuth: BasicCredentials{{/isBasicBasic}}{{#isBasicBearer}}bearerToken: BearerToken{{/isBasicBearer}}{{/isBasic}}{{#hasMore}}, {{/hasMore}}{{/authMethods}}{{/authMethods.0}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/README.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/README.mustache new file mode 100644 index 000000000000..0a61209568da --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/README.mustache @@ -0,0 +1,107 @@ +# {{artifactId}} + +{{appName}} +- API version: {{appVersion}} +{{^hideGenerationTimestamp}} + - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} + +{{#appDescriptionWithNewLines}}{{{appDescriptionWithNewLines}}}{{/appDescriptionWithNewLines}} + +{{#infoUrl}} + For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: +1. Java 1.7+ +2. Maven/Gradle/SBT + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + {{{groupId}}} + {{{artifactId}}} + {{{artifactVersion}}} + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}" +``` + +### SBT users + +```scala +libraryDependencies += "{{{groupId}}}" % "{{{artifactId}}}" % "{{{artifactVersion}}}" +``` + +## Getting Started + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | **{{operationId}}** | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation for Models + +{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md) +{{/model}}{{/models}} + +## Documentation for Authorization + +{{^authMethods}}All endpoints do not require authorization. +{{/authMethods}}Authentication schemes defined for the API: +{{#authMethods}}### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache new file mode 100644 index 000000000000..412bfca507d4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/api.mustache @@ -0,0 +1,45 @@ +{{>licenseInfo}} +package {{package}} + +{{#imports}} +import {{import}} +{{/imports}} +import {{mainPackage}}.core._ +import alias._ +import sttp.client._ +import sttp.model.Method + +{{#operations}} +object {{classname}} { + + def apply(baseUrl: String = "{{{basePath}}}")(implicit serializer: SttpSerializer) = new {{classname}}(baseUrl) +} + +class {{classname}}(baseUrl: String)(implicit serializer: SttpSerializer) { + + import Helpers._ + import serializer._ + +{{#operation}} +{{#javadocRenderer}} +{{>javadoc}} +{{/javadocRenderer}} + def {{operationId}}({{>methodParameters}}): ApiRequestT[{{>operationReturnType}}] = + basicRequest + .method(Method.{{httpMethod.toUpperCase}}, uri"$baseUrl{{{path}}}{{#queryParams.0}}?{{#queryParams}}{{baseName}}=${{{paramName}}}{{^-last}}&{{/-last}}{{/queryParams}}{{/queryParams.0}}{{#isApiKey}}{{#isKeyInQuery}}{{^queryParams.0}}?{{/queryParams.0}}{{#queryParams.0}}&{{/queryParams.0}}{{keyParamName}}=${apiKey.value}&{{/isKeyInQuery}}{{/isApiKey}}") + .contentType({{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}}{{^consumes}}"application/json"{{/consumes}}){{#headerParams}} + .header({{>paramCreation}}){{/headerParams}}{{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + .auth.withCredentials(basicAuth.user, basicAuth.password){{/isBasicBasic}}{{#isBasicBearer}} + .auth.bearer(bearerToken.token){{/isBasicBearer}}{{/isBasic}}{{#isApiKey}}{{#isKeyInHeader}} + .header("{{keyParamName}}", apiKey.value){{/isKeyInHeader}}{{#isKeyInCookie}} + .cookie("{{keyParamName}}", apiKey.value){{/isKeyInCookie}}{{/isApiKey}}{{/authMethods}}{{#formParams.0}} + .body(Map({{#formParams}} + {{>paramFormCreation}},{{/formParams}} + )){{/formParams.0}}{{#bodyParam}} + .body({{paramName}}){{/bodyParam}} + .response(asJson[{{>operationReturnType}}]) + +{{/operation}} +} + +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/apiInvoker.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/apiInvoker.mustache new file mode 100644 index 000000000000..254e92c74aac --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/apiInvoker.mustache @@ -0,0 +1,50 @@ +{{>licenseInfo}} +package {{{mainPackage}}}.core + +import org.json4s._ +import sttp.client._ +import sttp.model.StatusCode +import org.openapitools.client.api.EnumsSerializers +import sttp.client.json4s.SttpJson4sApi +import sttp.client.monad.MonadError + +class SttpSerializer(implicit val format: Formats = DefaultFormats ++ EnumsSerializers.all ++ Serializers.all, + implicit val serialization: org.json4s.Serialization = org.json4s.jackson.Serialization) extends SttpJson4sApi + +class HttpException(val statusCode: StatusCode, val statusText: String, val message: String) extends Exception(s"[$statusCode] $statusText: $message") + +object Helpers { + + // Helper to handle Optional header parameters + implicit class optionalParams(val request: RequestT[Identity, Either[String, String], Nothing]) extends AnyVal { + def header( header: String, optValue: Option[Any]): RequestT[Identity, Either[String, String], Nothing] = { + optValue.map( value => request.header(header, value.toString)).getOrElse(request) + } + } + +} + +object ApiInvoker { + + /** + * Allows request execution without calling apiInvoker.execute(request) + * request.result can be used to get a monad wrapped content. + * + * @param request the apiRequest to be executed + */ + implicit class ApiRequestImprovements[R[_], T](request: RequestT[Identity, Either[ResponseError[Exception], T], Nothing]) { + + def result(implicit backend: SttpBackend[R, Nothing, Nothing]): R[T] = { + val responseT = request.send() + val ME: MonadError[R] = backend.responseMonad + ME.flatMap(responseT) { + response => + response.body match { + case Left(ex) => ME.error[T](new HttpException(response.code, response.statusText, ex.body)) + case Right(value) => ME.unit(value) + } + } + } + } + +} diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/build.sbt.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/build.sbt.mustache new file mode 100644 index 000000000000..00fe48b731da --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/build.sbt.mustache @@ -0,0 +1,27 @@ +version := "{{artifactVersion}}" +name := "{{artifactId}}" +organization := "{{groupId}}" + +scalaVersion := "2.13.0" + +crossScalaVersions := Seq(scalaVersion.value, "2.12.10", "2.11.12") + +libraryDependencies ++= Seq( + "com.softwaremill.sttp.client" %% "core" % "2.0.0", + "com.softwaremill.sttp.client" %% "json4s" % "2.0.0", +{{#joda}} + "joda-time" % "joda-time" % "2.10.1", +{{/joda}} + "org.json4s" %% "json4s-jackson" % "3.6.7", + // test dependencies + "org.scalatest" %% "scalatest" % "3.0.8" % Test, + "junit" % "junit" % "4.13" % "test" +) + +scalacOptions := Seq( + "-unchecked", + "-deprecation", + "-feature" +) + +publishArtifact in (Compile, packageDoc) := false \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/enumsSerializers.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/enumsSerializers.mustache new file mode 100644 index 000000000000..8c7e6f2e41e5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/enumsSerializers.mustache @@ -0,0 +1,42 @@ +{{>licenseInfo}} +package {{apiPackage}} + +{{#models.0}} +import {{modelPackage}}._ +{{/models.0}} +import org.json4s._ +import scala.reflect.ClassTag + +object EnumsSerializers { + + def all: Seq[Serializer[_]] = Seq[Serializer[_]](){{#models}}{{#model}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+ + new EnumNameSerializer({{classname}}Enums.{{datatypeWithEnum}}){{/isEnum}}{{/vars}}{{/hasEnums}}{{/model}}{{/models}} + + private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E) + extends Serializer[E#Value] { + import JsonDSL._ + + val EnumerationClass: Class[E#Value] = classOf[E#Value] + + def deserialize(implicit format: Formats): + PartialFunction[(TypeInfo, JValue), E#Value] = { + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => + json match { + case JString(value) => + enum.withName(value) + case value => + throw new MappingException(s"Can't convert $value to $EnumerationClass") + } + } + + private[this] def isValid(json: JValue) = json match { + case JString(value) if enum.values.exists(_.toString == value) => true + case _ => false + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case i: E#Value => i.toString + } + } + +} diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/javadoc.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/javadoc.mustache new file mode 100644 index 000000000000..e42fa1dcdcd7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/javadoc.mustache @@ -0,0 +1,25 @@ +{{#notes}} +{{{notes}}} + +{{/notes}} +Expected answers: +{{#responses}} + code {{code}} : {{{dataType}}} {{#message}}({{{message}}}){{/message}} + {{#headers}} + {{#-first}} + Headers : + {{/-first}} + {{{baseName}}} - {{{description}}} + {{/headers}} +{{/responses}} +{{#authMethods.0}} + +Available security schemes: +{{#authMethods}} + {{name}} ({{type}}) +{{/authMethods}} +{{/authMethods.0}} + +{{#allParams}} +@param {{{paramName}}} {{{description}}} +{{/allParams}} diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/licenseInfo.mustache new file mode 100644 index 000000000000..835764cfc729 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}The version of the OpenAPI document: {{{version}}}{{/version}} + * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/methodParameters.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/methodParameters.mustache new file mode 100644 index 000000000000..54dc2f92a51f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/methodParameters.mustache @@ -0,0 +1 @@ +{{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}{{#isContainer}}{{dataType}}{{/isContainer}}{{^isContainer}}Option[{{dataType}}]{{/isContainer}}{{/required}}{{^defaultValue}}{{^required}}{{^isContainer}} = None{{/isContainer}}{{/required}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#authMethods.0}})(implicit {{#authMethods}}{{#isApiKey}}apiKey: ApiKeyValue{{/isApiKey}}{{#isBasic}}{{#isBasicBasic}}basicAuth: BasicCredentials{{/isBasicBasic}}{{#isBasicBearer}}bearerToken: BearerToken{{/isBasicBearer}}{{/isBasic}}{{#hasMore}}, {{/hasMore}}{{/authMethods}}{{/authMethods.0}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/model.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/model.mustache new file mode 100644 index 000000000000..941266f3306e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/model.mustache @@ -0,0 +1,50 @@ +{{>licenseInfo}} +package {{package}} + +{{#imports}} +import {{import}} +{{/imports}} +import {{mainPackage}}.core.ApiModel + +{{#models}} +{{#model}} +{{#description}} +{{#javadocRenderer}} +{{#title}} +{{{title}}} +{{/title}} +{{{description}}} +{{/javadocRenderer}} +{{/description}} +case class {{classname}}( + {{#vars}} + {{#description}} + /* {{{description}}} */ + {{/description}} + {{{name}}}: {{^required}}Option[{{/required}}{{^isEnum}}{{dataType}}{{/isEnum}}{{#isEnum}}{{classname}}Enums.{{datatypeWithEnum}}{{/isEnum}}{{^required}}] = None{{/required}}{{#hasMore}},{{/hasMore}} + {{/vars}} +) extends ApiModel + +{{#hasEnums}} +object {{classname}}Enums { + + {{#vars}} + {{#isEnum}} + type {{datatypeWithEnum}} = {{datatypeWithEnum}}.Value + {{/isEnum}} + {{/vars}} + {{#vars}} + {{#isEnum}} + object {{datatypeWithEnum}} extends Enumeration { +{{#_enum}} + val {{#fnEnumEntry}}{{.}}{{/fnEnumEntry}} = Value("{{.}}") +{{/_enum}} + } + + {{/isEnum}} + {{/vars}} +} +{{/hasEnums}} +{{/model}} +{{/models}} + diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/operationReturnType.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/operationReturnType.mustache new file mode 100644 index 000000000000..a8917911853a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/operationReturnType.mustache @@ -0,0 +1 @@ +{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/paramCreation.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/paramCreation.mustache new file mode 100644 index 000000000000..68280bd9a36b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/paramCreation.mustache @@ -0,0 +1 @@ +"{{baseName}}", {{#isContainer}}ArrayValues({{{paramName}}}{{#collectionFormat}}, {{collectionFormat.toUpperCase}}{{/collectionFormat}}){{/isContainer}}{{^isContainer}}{{{paramName}}}{{/isContainer}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/paramFormCreation.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/paramFormCreation.mustache new file mode 100644 index 000000000000..a0f1a65c0746 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/paramFormCreation.mustache @@ -0,0 +1 @@ +"{{baseName}}" -> {{#isContainer}}ArrayValues({{{paramName}}}{{#collectionFormat}}, {{collectionFormat.toUpperCase}}{{/collectionFormat}}){{/isContainer}}{{^isContainer}}{{{paramName}}}{{/isContainer}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/paramQueryCreation.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/paramQueryCreation.mustache new file mode 100644 index 000000000000..8a1ea8cfcbf7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/paramQueryCreation.mustache @@ -0,0 +1 @@ +{{#isContainer}}${ formatQueryArray("{{{baseName}}}",{{{paramName}}}{{#collectionFormat}}, {{collectionFormat.toUpperCase}}{{/collectionFormat}}) }{{/isContainer}}{{^isContainer}}{{baseName}}=${ {{{paramName}}} }{{/isContainer}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/requests.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/requests.mustache new file mode 100644 index 000000000000..31158fd67cbf --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/requests.mustache @@ -0,0 +1,48 @@ +{{>licenseInfo}} +package {{mainPackage}}.core + +import sttp.client.{Identity, RequestT, ResponseError} + +/** + * This trait needs to be added to any model defined by the api. + */ +trait ApiModel + +/** + * Sttp type aliases + */ +object alias { + type ApiRequestT[T] = RequestT[Identity, Either[ResponseError[Exception], T], Nothing] +} + +/** + * Single trait defining a credential that can be transformed to a paramName / paramValue tupple + */ +sealed trait Credentials { + def asQueryParam: Option[(String, String)] = None +} + +sealed case class BasicCredentials(user: String, password: String) extends Credentials + +sealed case class BearerToken(token: String) extends Credentials + +sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { + override def asQueryParam: Option[(String, String)] = location match { + case ApiKeyLocations.QUERY => Some((keyName, key.value)) + case _ => None + } +} + +sealed case class ApiKeyValue(value: String) + +sealed trait ApiKeyLocation + +object ApiKeyLocations { + + case object QUERY extends ApiKeyLocation + + case object HEADER extends ApiKeyLocation + + case object COOKIE extends ApiKeyLocation + +} diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/responseState.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/responseState.mustache new file mode 100644 index 000000000000..d1b3798e6de1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/responseState.mustache @@ -0,0 +1 @@ +{{#isDefault}}Success{{/isDefault}}{{^isDefault}}Error{{/isDefault}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-sttp/serializers.mustache b/modules/openapi-generator/src/main/resources/scala-sttp/serializers.mustache new file mode 100644 index 000000000000..a17d77069157 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-sttp/serializers.mustache @@ -0,0 +1,57 @@ +package {{invokerPackage}} + +{{#java8}} +import java.time.{LocalDate, LocalDateTime, OffsetDateTime, ZoneId} +import java.time.format.DateTimeFormatter +import scala.util.Try +{{/java8}} +{{#joda}} +import org.joda.time.DateTime +import org.joda.time.format.ISODateTimeFormat +{{/joda}} +import org.json4s.{Serializer, CustomSerializer, JNull} +import org.json4s.JsonAST.JString + +object Serializers { + +{{#java8}} + case object DateTimeSerializer extends CustomSerializer[OffsetDateTime](_ => ( { + case JString(s) => + Try(OffsetDateTime.parse(s, DateTimeFormatter.ISO_OFFSET_DATE_TIME)) orElse + Try(LocalDateTime.parse(s).atZone(ZoneId.systemDefault()).toOffsetDateTime) getOrElse (null) + case JNull => null + }, { + case d: OffsetDateTime => + JString(d.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)) + })) + + case object LocalDateSerializer extends CustomSerializer[LocalDate]( _ => ( { + case JString(s) => LocalDate.parse(s) + case JNull => null + }, { + case d: LocalDate => + JString(d.format(DateTimeFormatter.ISO_LOCAL_DATE)) + })) +{{/java8}} +{{#joda}} + case object DateTimeSerializer extends CustomSerializer[DateTime](_ => ( { + case JString(s) => + ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(s) + case JNull => null + }, { + case d: org.joda.time.DateTime => + JString(ISODateTimeFormat.dateTime().print(d)) + }) + ) + + case object LocalDateSerializer extends CustomSerializer[org.joda.time.LocalDate](_ => ( { + case JString(s) => org.joda.time.format.DateTimeFormat.forPattern("yyyy-MM-dd").parseLocalDate(s) + case JNull => null + }, { + case d: org.joda.time.LocalDate => JString(d.toString("yyyy-MM-dd")) + })) +{{/joda}} + + def all: Seq[Serializer[_]] = Seq[Serializer[_]]() :+ LocalDateSerializer :+ DateTimeSerializer + +} diff --git a/modules/openapi-generator/src/main/resources/swift4/api.mustache b/modules/openapi-generator/src/main/resources/swift4/api.mustache index 18eab9425a69..d91b687219cb 100644 --- a/modules/openapi-generator/src/main/resources/swift4/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift4/api.mustache @@ -15,7 +15,7 @@ extension {{projectName}}API { {{#description}} /** {{description}} */{{/description}} -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{classname}} { +{{#objcCompatible}}@objc {{/objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{classname}}{{#objcCompatible}} : NSObject{{/objcCompatible}} { {{#operation}} {{#allParams}} {{#isEnum}} diff --git a/modules/openapi-generator/src/main/resources/swift4/modelObject.mustache b/modules/openapi-generator/src/main/resources/swift4/modelObject.mustache index 806086efc80f..516dc7014281 100644 --- a/modules/openapi-generator/src/main/resources/swift4/modelObject.mustache +++ b/modules/openapi-generator/src/main/resources/swift4/modelObject.mustache @@ -1,4 +1,5 @@ -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct {{classname}}: Codable { +{{^objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct {{classname}}: Codable { {{/objcCompatible}} +{{#objcCompatible}}@objc {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class {{classname}}: NSObject, Codable { {{/objcCompatible}} {{#allVars}} {{#isEnum}} @@ -15,7 +16,7 @@ {{/description}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var {{name}}: {{{datatype}}}{{#unwrapRequired}}?{{/unwrapRequired}}{{^unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#objcCompatible}}{{#vendorExtensions.x-swift-optional-scalar}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var {{name}}Num: NSNumber? { get { - return {{name}}.map({ return NSNumber(value: $0) }) + return {{name}} as NSNumber? } }{{/vendorExtensions.x-swift-optional-scalar}}{{/objcCompatible}} {{/isEnum}} @@ -58,7 +59,7 @@ // Decodable protocol methods - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(from decoder: Decoder) throws { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}}{{#objcCompatible}} required{{/objcCompatible}} init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: String.self) {{#allVars}} diff --git a/modules/openapi-generator/src/main/resources/swift5/api.mustache b/modules/openapi-generator/src/main/resources/swift5/api.mustache index d3f1604dcca0..f8b2ef2587e3 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api.mustache @@ -16,7 +16,7 @@ extension {{projectName}}API { {{#description}} /** {{description}} */{{/description}} -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{classname}} { +{{#objcCompatible}}@objc {{/objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class {{classname}}{{#objcCompatible}} : NSObject{{/objcCompatible}} { {{#operation}} {{#allParams}} {{#isEnum}} diff --git a/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache b/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache index f937bde2b8c1..25d7881c05a4 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelObject.mustache @@ -1,4 +1,5 @@ -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct {{classname}}: Codable { +{{^objcCompatible}}{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} struct {{classname}}: Codable { {{/objcCompatible}} +{{#objcCompatible}}@objc {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} class {{classname}}: NSObject, Codable { {{/objcCompatible}} {{#allVars}} {{#isEnum}} @@ -17,7 +18,7 @@ {{#vendorExtensions.x-swift-optional-scalar}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} var {{name}}Num: NSNumber? { get { - return {{name}}.map({ return NSNumber(value: $0) }) + return {{name}} as NSNumber? } } {{/vendorExtensions.x-swift-optional-scalar}} @@ -62,7 +63,7 @@ // Decodable protocol methods - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(from decoder: Decoder) throws { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}}{{#objcCompatible}} required{{/objcCompatible}} init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: String.self) {{#allVars}} diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache index 167ac8408493..9f798331db7c 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache @@ -189,7 +189,8 @@ export const {{classname}}AxiosParamCreator = function (configuration?: Configur localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; {{#hasFormParams}} localVarRequestOptions.data = localVarFormParams{{#vendorExtensions}}{{^multipartFormData}}.toString(){{/multipartFormData}}{{/vendorExtensions}}; {{/hasFormParams}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/protobuf/ProtobufSchemaCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/protobuf/ProtobufSchemaCodegenTest.java index a4c32c3b7945..540bd180956b 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/protobuf/ProtobufSchemaCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/protobuf/ProtobufSchemaCodegenTest.java @@ -29,7 +29,7 @@ public class ProtobufSchemaCodegenTest { @Test public void testFeatureSet() { final ProtobufSchemaCodegen codegen = new ProtobufSchemaCodegen(); - FeatureSet featureSet = codegen.getFeatureSet(); + FeatureSet featureSet = codegen.getGeneratorMetadata().getFeatureSet(); Assert.assertTrue(featureSet.getWireFormatFeatures().contains(WireFormatFeature.PROTOBUF)); Assert.assertEquals(featureSet.getWireFormatFeatures().size(), 1); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java index 2a657e01fff9..510691863540 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/scalaakka/ScalaAkkaClientCodegenTest.java @@ -363,4 +363,28 @@ public void codeGenerationTest() throws Exception { generatedFiles.get(someObjFilename), Resources.toString(Resources.getResource("codegen/scala/SomeObj.scala.txt"), StandardCharsets.UTF_8)); } + + @Test(description = "strip model name") + public void stripModelNameTest() throws Exception { + final Schema model = new Schema() + .description("a map model"); + final DefaultCodegen codegen = new ScalaAkkaClientCodegen(); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema("sample", model); + codegen.setOpenAPI(openAPI); + + final CodegenModel cms = codegen.fromModel("Stripped.ByDefault.ModelName", model); + Assert.assertEquals(cms.name, "Stripped.ByDefault.ModelName"); + Assert.assertEquals(cms.classname, "ModelName"); + Assert.assertEquals(cms.classFilename, "ModelName"); + + codegen.additionalProperties().put(CodegenConstants.STRIP_PACKAGE_NAME, "false"); + codegen.processOpts(); + + final CodegenModel cm = codegen.fromModel("Non.Stripped.ModelName", model); + + Assert.assertEquals(cm.name, "Non.Stripped.ModelName"); + Assert.assertEquals(cm.classname, "NonStrippedModelName"); + Assert.assertEquals(cm.classFilename, "NonStrippedModelName"); + + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientCodegenTest.java index 2e18afea218f..a72a93de9d81 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientCodegenTest.java @@ -1,6 +1,7 @@ package org.openapitools.codegen.typescript.fetch; import io.swagger.v3.oas.models.OpenAPI; +import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.TestUtils; import org.openapitools.codegen.languages.TypeScriptFetchClientCodegen; import org.testng.Assert; @@ -56,4 +57,16 @@ public void testWithoutSnapshotVersion() { } + @Test + public void toVarName() { + TypeScriptFetchClientCodegen codegen = new TypeScriptFetchClientCodegen(); + codegen.processOpts(); + Assert.assertEquals(codegen.toVarName("valid_var"), "validVar"); + + codegen = new TypeScriptFetchClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.MODEL_PROPERTY_NAMING, "original"); + codegen.processOpts(); + Assert.assertEquals(codegen.toVarName("valid_var"), "valid_var"); + } + } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java index a1a07d28aa68..c1646fcdc609 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java @@ -18,6 +18,18 @@ public class TypeScriptAngularClientCodegenTest { + @Test + public void toVarName() { + TypeScriptAngularClientCodegen codegen = new TypeScriptAngularClientCodegen(); + codegen.processOpts(); + Assert.assertEquals(codegen.toVarName("valid_var"), "valid_var"); + + codegen = new TypeScriptAngularClientCodegen(); + codegen.additionalProperties().put(CodegenConstants.MODEL_PROPERTY_NAMING, "camelCase"); + codegen.processOpts(); + Assert.assertEquals(codegen.toVarName("valid_var"), "validVar"); + } + @Test public void toEnumVarName() { TypeScriptAngularClientCodegen codegen = new TypeScriptAngularClientCodegen(); diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index ecc6f66f3b03..d9aedbba9c6d 100644 --- a/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -1779,3 +1779,82 @@ components: additionalProperties: type: object nullable: true + fruit: + properties: + color: + type: string + oneOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + apple: + type: object + properties: + cultivar: + type: string + banana: + type: object + properties: + lengthCm: + type: number + mammal: + oneOf: + - $ref: '#/components/schemas/whale' + - $ref: '#/components/schemas/zebra' + discriminator: + propertyName: className + mapping: + whale: '#/components/schemas/whale' + zebra: '#/components/schemas/zebra' + whale: + type: object + properties: + hasBaleen: + type: boolean + hasTeeth: + type: boolean + className: + type: string + required: + - className + zebra: + type: object + properties: + type: + type: string + enum: + - plains + - mountain + - grevys + className: + type: string + required: + - className + gmFruit: + properties: + color: + type: string + anyOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + fruitReq: + oneOf: + - $ref: '#/components/schemas/appleReq' + - $ref: '#/components/schemas/bananaReq' + appleReq: + type: object + properties: + cultivar: + type: string + mealy: + type: boolean + required: + - cultivar + bananaReq: + type: object + properties: + lengthCm: + type: number + sweet: + type: boolean + required: + - lengthCm diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore-with-object-as-parameter.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore-with-object-as-parameter.yaml new file mode 100644 index 000000000000..0cfbd1b0f9d3 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/petstore-with-object-as-parameter.yaml @@ -0,0 +1,793 @@ +openapi: 3.0.1 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + patch: + tags: + - pet + summary: Set the status of a pet in the store using an enum + description: '' + operationId: updatePetStatusWithEnum + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + - $ref: '#/components/parameters/statusEnum' + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/PetForm' + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/UploadForm' + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + security: + - auth_cookie: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + security: + - auth_cookie: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + security: + - auth_cookie: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `auth_cookie` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when toekn expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + security: + - auth_cookie: [] + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + security: + - auth_cookie: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - auth_cookie: [] +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user objects + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + PetForm: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/PetForm' + example: + name: fluffy + status: available + UploadForm: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/UploadForm' + example: + additionalMetadata: additional metadata example + file: c29tZSB0ZXN0IGRhdGEK + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + auth_cookie: + type: apiKey + name: AUTH_KEY + in: cookie + schemas: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: Pet + PetForm: + title: A pet form + description: A form for updating a pet + type: object + required: + - name + - status + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + UploadForm: + title: An upload form + description: A form for attaching files to a pet + type: object + required: + - file + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + statusEnum: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + parameters: + statusEnum: + description: The required status + explode: true + in: query + name: status + required: true + schema: + $ref: '#/components/schemas/statusEnum' + example: + pending + style: form diff --git a/modules/openapi-generator/src/test/resources/3_0/scala/stripModelName.yaml b/modules/openapi-generator/src/test/resources/3_0/scala/stripModelName.yaml new file mode 100644 index 000000000000..e1b1c496cb89 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/scala/stripModelName.yaml @@ -0,0 +1,46 @@ +openapi: 3.0.1 +info: + version: 1.0.0 + title: Example + license: + name: MIT +servers: + - url: http://api.example.xyz/v1 +paths: + /deprecated-test: + x-swagger-router-controller: /deprecated-test + post: + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Non.Stripped.Request' + responses: + '200': + description: responses + content: + application/json: + schema: + $ref: '#/components/schemas/Response' +components: + schemas: + Non.Stripped.Request: + type: object + properties: + customerCode: + type: string + example: '0001' + firstName: + type: string + deprecated: true + example: 'first' + Response: + type: object + properties: + customerCode: + type: string + example: '0001' + firstName: + type: string + deprecated: true + example: 'first' diff --git a/pom.xml b/pom.xml index 8c468600e3f8..bbf7ee1ecf66 100644 --- a/pom.xml +++ b/pom.xml @@ -1291,6 +1291,7 @@ samples/openapi3/client/petstore/go + samples/openapi3/client/petstore/scala-sttp samples/client/petstore/scala-httpclient samples/client/petstore/scalaz samples/client/petstore/clojure diff --git a/samples/client/petstore/python-experimental/petstore_api/model_utils.py b/samples/client/petstore/python-experimental/petstore_api/model_utils.py index 074e597cbd22..eed501c84502 100644 --- a/samples/client/petstore/python-experimental/petstore_api/model_utils.py +++ b/samples/client/petstore/python-experimental/petstore_api/model_utils.py @@ -274,13 +274,20 @@ def __getattr__(self, name): if self._path_to_item: path_to_item.extend(self._path_to_item) path_to_item.append(name) + values = set() if model_instances: - values = set() for model_instance in model_instances: if name in model_instance._data_store: values.add(model_instance._data_store[name]) - if len(values) == 1: - return list(values)[0] + len_values = len(values) + if len_values == 0: + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + path_to_item + ) + elif len_values == 1: + return list(values)[0] + elif len_values > 1: raise ApiValueError( "Values stored for property {0} in {1} difffer when looking " "at self and self's composed instances. All values must be " @@ -288,11 +295,6 @@ def __getattr__(self, name): path_to_item ) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - def to_dict(self): """Returns the model properties as a dict""" return model_to_dict(self, serialize=False) @@ -1082,7 +1084,7 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas() is not None: - model_instances = model_instance._composed_instances + model_instances.extend(model_instance._composed_instances) for model_instance in model_instances: for attr, value in six.iteritems(model_instance._data_store): if serialize: @@ -1205,12 +1207,12 @@ def get_oneof_instance(self, model_args, constant_args): used to make instances Returns - oneof_instance (instance) + oneof_instance (instance/None) """ - oneof_instance = None if len(self._composed_schemas()['oneOf']) == 0: - return oneof_instance + return None + oneof_instances = [] for oneof_class in self._composed_schemas()['oneOf']: # transform js keys to python keys in fixed_model_args fixed_model_args = change_keys_js_to_python( @@ -1223,20 +1225,30 @@ def get_oneof_instance(self, model_args, constant_args): if var_name in fixed_model_args: kwargs[var_name] = fixed_model_args[var_name] + # do not try to make a model with no input args + if len(kwargs) == 0: + continue + # and use it to make the instance kwargs.update(constant_args) try: oneof_instance = oneof_class(**kwargs) - break + oneof_instances.append(oneof_instance) except Exception: pass - if oneof_instance is None: + if len(oneof_instances) == 0: raise ApiValueError( "Invalid inputs given to generate an instance of %s. Unable to " "make any instances of the classes in oneOf definition." % self.__class__.__name__ ) - return oneof_instance + elif len(oneof_instances) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Multiple " + "oneOf instances were generated when a max of one is allowed." % + self.__class__.__name__ + ) + return oneof_instances[0] def get_anyof_instances(self, model_args, constant_args): @@ -1266,6 +1278,10 @@ def get_anyof_instances(self, model_args, constant_args): if var_name in fixed_model_args: kwargs[var_name] = fixed_model_args[var_name] + # do not try to make a model with no input args + if len(kwargs) == 0: + continue + # and use it to make the instance kwargs.update(constant_args) try: diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_any_type.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_any_type.py index 440ca3672749..d1a06123ea88 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_any_type.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_any_type.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """additional_properties_any_type.AdditionalPropertiesAnyType - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_array.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_array.py index 4c5054603ee0..bba4f0ed95f1 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_array.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_array.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """additional_properties_array.AdditionalPropertiesArray - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_boolean.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_boolean.py index 676c97d2915c..de012c132c90 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_boolean.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_boolean.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """additional_properties_boolean.AdditionalPropertiesBoolean - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py index d0dcda0f193e..c37e9b5c73bf 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -119,7 +120,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """additional_properties_class.AdditionalPropertiesClass - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_integer.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_integer.py index e51a3ada19d8..649fbc485896 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_integer.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_integer.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """additional_properties_integer.AdditionalPropertiesInteger - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_number.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_number.py index c8cceb764404..ce12662a8ed0 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_number.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_number.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """additional_properties_number.AdditionalPropertiesNumber - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_object.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_object.py index 56d227c144d3..e5c60015a9e1 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_object.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_object.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """additional_properties_object.AdditionalPropertiesObject - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_string.py b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_string.py index c4a066f00422..24cef21ba90d 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_string.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/additional_properties_string.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """additional_properties_string.AdditionalPropertiesString - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/animal.py b/samples/client/petstore/python-experimental/petstore_api/models/animal.py index 4971ab17ab56..45058ec7612f 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/animal.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/animal.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/client/petstore/python-experimental/petstore_api/models/api_response.py b/samples/client/petstore/python-experimental/petstore_api/models/api_response.py index 893024a80b99..f1680c87f67a 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/api_response.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/api_response.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -103,7 +104,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """api_response.ApiResponse - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py b/samples/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py index faa9b5c44ccd..bf6419e5c089 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """array_of_array_of_number_only.ArrayOfArrayOfNumberOnly - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py b/samples/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py index 2909708136de..f3bf89e27ba3 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """array_of_number_only.ArrayOfNumberOnly - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/array_test.py b/samples/client/petstore/python-experimental/petstore_api/models/array_test.py index 7f4f1090663a..0a01b3cad210 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/array_test.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/array_test.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -108,7 +109,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """array_test.ArrayTest - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/capitalization.py b/samples/client/petstore/python-experimental/petstore_api/models/capitalization.py index b4be4b15e71d..6011db39400c 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/capitalization.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/capitalization.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -109,7 +110,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """capitalization.Capitalization - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/cat.py b/samples/client/petstore/python-experimental/petstore_api/models/cat.py index 2683db835805..d40464eaf0e9 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/cat.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/cat.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -145,9 +146,16 @@ def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_it '_from_server': _from_server, '_configuration': _configuration, } - model_args = { + required_args = { 'class_name': class_name, } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) @@ -156,7 +164,8 @@ def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_it self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] - self.class_name = class_name + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) for var_name, var_value in six.iteritems(kwargs): if var_name in unused_args and \ self._configuration is not None and \ diff --git a/samples/client/petstore/python-experimental/petstore_api/models/cat_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/cat_all_of.py index 1c3fe2578a46..75e856dcbcde 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/cat_all_of.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/cat_all_of.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """cat_all_of.CatAllOf - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/category.py b/samples/client/petstore/python-experimental/petstore_api/models/category.py index fcdb58cb9568..5d3e21ddd7e9 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/category.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/category.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -104,7 +105,7 @@ def __init__(self, name='default-name', _check_type=True, _from_server=False, _p Args: Keyword Args: - name (str): defaults to 'default-name', must be one of ['default-name'] # noqa: E501 + name (str): defaults to 'default-name' # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child.py b/samples/client/petstore/python-experimental/petstore_api/models/child.py index efbce35e8ba3..501c22427916 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/child.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/child.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -112,7 +113,6 @@ def discriminator(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """child.Child - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -144,8 +144,15 @@ def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _conf '_from_server': _from_server, '_configuration': _configuration, } - model_args = { + required_args = { } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) @@ -154,6 +161,8 @@ def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _conf self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) for var_name, var_value in six.iteritems(kwargs): if var_name in unused_args and \ self._configuration is not None and \ diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/child_all_of.py index c4b55ed362b5..69f6b962f242 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/child_all_of.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_all_of.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """child_all_of.ChildAllOf - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_cat.py b/samples/client/petstore/python-experimental/petstore_api/models/child_cat.py index eab41ebbf11f..b83986bd68a8 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/child_cat.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_cat.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -142,9 +143,16 @@ def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item '_from_server': _from_server, '_configuration': _configuration, } - model_args = { + required_args = { 'pet_type': pet_type, } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) @@ -153,7 +161,8 @@ def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] - self.pet_type = pet_type + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) for var_name, var_value in six.iteritems(kwargs): if var_name in unused_args and \ self._configuration is not None and \ diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_cat_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/child_cat_all_of.py index 11b8c5d2c124..dbe4e88bcebc 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/child_cat_all_of.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_cat_all_of.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """child_cat_all_of.ChildCatAllOf - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_dog.py b/samples/client/petstore/python-experimental/petstore_api/models/child_dog.py index adbc33daf77c..da568bd7d271 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/child_dog.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_dog.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -142,9 +143,16 @@ def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item '_from_server': _from_server, '_configuration': _configuration, } - model_args = { + required_args = { 'pet_type': pet_type, } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) @@ -153,7 +161,8 @@ def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] - self.pet_type = pet_type + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) for var_name, var_value in six.iteritems(kwargs): if var_name in unused_args and \ self._configuration is not None and \ diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_dog_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/child_dog_all_of.py index 21fee1506a6f..f95f5ff8ae74 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/child_dog_all_of.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_dog_all_of.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """child_dog_all_of.ChildDogAllOf - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_lizard.py b/samples/client/petstore/python-experimental/petstore_api/models/child_lizard.py index 20c04d3f2fc1..62fa11f26e80 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/child_lizard.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_lizard.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -142,9 +143,16 @@ def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item '_from_server': _from_server, '_configuration': _configuration, } - model_args = { + required_args = { 'pet_type': pet_type, } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) @@ -153,7 +161,8 @@ def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] - self.pet_type = pet_type + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) for var_name, var_value in six.iteritems(kwargs): if var_name in unused_args and \ self._configuration is not None and \ diff --git a/samples/client/petstore/python-experimental/petstore_api/models/child_lizard_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/child_lizard_all_of.py index f429c864d5b8..27686379a890 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/child_lizard_all_of.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/child_lizard_all_of.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """child_lizard_all_of.ChildLizardAllOf - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/class_model.py b/samples/client/petstore/python-experimental/petstore_api/models/class_model.py index e4f1d63a264c..06c52dc8bee9 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/class_model.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/class_model.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """class_model.ClassModel - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/client.py b/samples/client/petstore/python-experimental/petstore_api/models/client.py index f3f645da3823..b7184b3f2b40 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/client.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/client.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """client.Client - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/dog.py b/samples/client/petstore/python-experimental/petstore_api/models/dog.py index 462869ffbd28..69af821b27e2 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/dog.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/dog.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -145,9 +146,16 @@ def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_it '_from_server': _from_server, '_configuration': _configuration, } - model_args = { + required_args = { 'class_name': class_name, } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) @@ -156,7 +164,8 @@ def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_it self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] - self.class_name = class_name + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) for var_name, var_value in six.iteritems(kwargs): if var_name in unused_args and \ self._configuration is not None and \ diff --git a/samples/client/petstore/python-experimental/petstore_api/models/dog_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/dog_all_of.py index ec62d18e6376..0832f4b696cc 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/dog_all_of.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/dog_all_of.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """dog_all_of.DogAllOf - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/enum_arrays.py b/samples/client/petstore/python-experimental/petstore_api/models/enum_arrays.py index 59f73c8f1c9e..358e9f680e76 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/enum_arrays.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/enum_arrays.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -109,7 +110,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """enum_arrays.EnumArrays - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/enum_class.py b/samples/client/petstore/python-experimental/petstore_api/models/enum_class.py index 994d7723842e..5f3f1894de47 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/enum_class.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/enum_class.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,7 @@ def __init__(self, value='-efg', _check_type=True, _from_server=False, _path_to_ Args: Keyword Args: - value (str): defaults to '-efg', must be one of ['-efg'] # noqa: E501 + value (str): defaults to '-efg', must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. diff --git a/samples/client/petstore/python-experimental/petstore_api/models/enum_test.py b/samples/client/petstore/python-experimental/petstore_api/models/enum_test.py index 2d5efd84b263..4c35c7b8c2bb 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/enum_test.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/enum_test.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/client/petstore/python-experimental/petstore_api/models/file.py b/samples/client/petstore/python-experimental/petstore_api/models/file.py index 46f02f4436cf..f71dc07b7ca8 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/file.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/file.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """file.File - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py b/samples/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py index 9c5cb0c63664..1260e8affda2 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -106,7 +107,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """file_schema_test_class.FileSchemaTestClass - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/format_test.py b/samples/client/petstore/python-experimental/petstore_api/models/format_test.py index 9325e5888e9b..823c3cb88d91 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/format_test.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/format_test.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/client/petstore/python-experimental/petstore_api/models/grandparent.py b/samples/client/petstore/python-experimental/petstore_api/models/grandparent.py index dc71d92196fd..98d7934f472f 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/grandparent.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/grandparent.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """grandparent.Grandparent - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/grandparent_animal.py b/samples/client/petstore/python-experimental/petstore_api/models/grandparent_animal.py index 127de0d2e04d..af25951ed73a 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/grandparent_animal.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/grandparent_animal.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py b/samples/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py index cf66f3fc02e8..c84cf0be3f2b 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -101,7 +102,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """has_only_read_only.HasOnlyReadOnly - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/list.py b/samples/client/petstore/python-experimental/petstore_api/models/list.py index d4cd4c4eb466..c7c80e8bd28b 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/list.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/list.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """list.List - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/map_test.py b/samples/client/petstore/python-experimental/petstore_api/models/map_test.py index 95d680e9ebdf..8cc47c0a6922 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/map_test.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/map_test.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -114,7 +115,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """map_test.MapTest - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py index 7eb5df3cc68f..143a79bfa266 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -108,7 +109,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/model200_response.py b/samples/client/petstore/python-experimental/petstore_api/models/model200_response.py index 4eb1672966ae..0c3885120210 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/model200_response.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/model200_response.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -101,7 +102,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """model200_response.Model200Response - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/model_return.py b/samples/client/petstore/python-experimental/petstore_api/models/model_return.py index 740c8e140563..75c3cea6318b 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/model_return.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/model_return.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """model_return.ModelReturn - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/name.py b/samples/client/petstore/python-experimental/petstore_api/models/name.py index c85f89a118c6..db81ae16916d 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/name.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/name.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/client/petstore/python-experimental/petstore_api/models/number_only.py b/samples/client/petstore/python-experimental/petstore_api/models/number_only.py index a3f20cd4b4b3..0c91e2ae62d0 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/number_only.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/number_only.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """number_only.NumberOnly - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/order.py b/samples/client/petstore/python-experimental/petstore_api/models/order.py index 15c23366e433..673295a8610c 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/order.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/order.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -114,7 +115,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """order.Order - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/outer_composite.py b/samples/client/petstore/python-experimental/petstore_api/models/outer_composite.py index e643f6e73bd9..c654c51daffe 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/outer_composite.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/outer_composite.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -108,7 +109,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """outer_composite.OuterComposite - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/outer_enum.py b/samples/client/petstore/python-experimental/petstore_api/models/outer_enum.py index 8796d7d3f2b6..9a933b28169b 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/outer_enum.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/outer_enum.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/client/petstore/python-experimental/petstore_api/models/outer_number.py b/samples/client/petstore/python-experimental/petstore_api/models/outer_number.py index faab717c987e..9f7b3de76d91 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/outer_number.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/outer_number.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/client/petstore/python-experimental/petstore_api/models/parent.py b/samples/client/petstore/python-experimental/petstore_api/models/parent.py index e75f035ec764..f62abd94ceed 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/parent.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/parent.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -110,7 +111,6 @@ def discriminator(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """parent.Parent - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be @@ -141,8 +141,15 @@ def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _conf '_from_server': _from_server, '_configuration': _configuration, } - model_args = { + required_args = { } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) @@ -151,6 +158,8 @@ def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _conf self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) for var_name, var_value in six.iteritems(kwargs): if var_name in unused_args and \ self._configuration is not None and \ diff --git a/samples/client/petstore/python-experimental/petstore_api/models/parent_all_of.py b/samples/client/petstore/python-experimental/petstore_api/models/parent_all_of.py index 49639b575660..f927649600bd 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/parent_all_of.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/parent_all_of.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """parent_all_of.ParentAllOf - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/parent_pet.py b/samples/client/petstore/python-experimental/petstore_api/models/parent_pet.py index 9ef05ab1a4a5..cdb96676c555 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/parent_pet.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/parent_pet.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -155,9 +156,16 @@ def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item '_from_server': _from_server, '_configuration': _configuration, } - model_args = { + required_args = { 'pet_type': pet_type, } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) @@ -166,7 +174,8 @@ def __init__(self, pet_type, _check_type=True, _from_server=False, _path_to_item self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] - self.pet_type = pet_type + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) for var_name, var_value in six.iteritems(kwargs): if var_name in unused_args and \ self._configuration is not None and \ diff --git a/samples/client/petstore/python-experimental/petstore_api/models/pet.py b/samples/client/petstore/python-experimental/petstore_api/models/pet.py index 1682c3cb51b2..74cd8afef1af 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/pet.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/pet.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/client/petstore/python-experimental/petstore_api/models/player.py b/samples/client/petstore/python-experimental/petstore_api/models/player.py index 4e2933ab4194..ea8d2a99456d 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/player.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/player.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/client/petstore/python-experimental/petstore_api/models/read_only_first.py b/samples/client/petstore/python-experimental/petstore_api/models/read_only_first.py index 6a18e6331f61..329ec017d435 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/read_only_first.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/read_only_first.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -101,7 +102,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """read_only_first.ReadOnlyFirst - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/special_model_name.py b/samples/client/petstore/python-experimental/petstore_api/models/special_model_name.py index 006f9454b854..d4ffc608a579 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/special_model_name.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/special_model_name.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """special_model_name.SpecialModelName - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py b/samples/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py index d7b0b0a94501..7f797f5f1b5d 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -97,7 +98,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """string_boolean_map.StringBooleanMap - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/tag.py b/samples/client/petstore/python-experimental/petstore_api/models/tag.py index 6c529a5785dd..9af85413b39d 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/tag.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/tag.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -103,7 +104,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """tag.Tag - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/type_holder_default.py b/samples/client/petstore/python-experimental/petstore_api/models/type_holder_default.py index 8579bfc1a17b..acde27d37ab4 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/type_holder_default.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/type_holder_default.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -115,10 +116,10 @@ def __init__(self, array_item, string_item='what', number_item=1.234, integer_it array_item ([int]): Keyword Args: - string_item (str): defaults to 'what', must be one of ['what'] # noqa: E501 - number_item (float): defaults to 1.234, must be one of [1.234] # noqa: E501 - integer_item (int): defaults to -2, must be one of [-2] # noqa: E501 - bool_item (bool): defaults to True, must be one of [True] # noqa: E501 + string_item (str): defaults to 'what' # noqa: E501 + number_item (float): defaults to 1.234 # noqa: E501 + integer_item (int): defaults to -2 # noqa: E501 + bool_item (bool): defaults to True # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. diff --git a/samples/client/petstore/python-experimental/petstore_api/models/type_holder_example.py b/samples/client/petstore/python-experimental/petstore_api/models/type_holder_example.py index 8c78ff54a7d2..dc8b5116da09 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/type_holder_example.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/type_holder_example.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -121,9 +122,9 @@ def __init__(self, bool_item, array_item, string_item='what', number_item=1.234, array_item ([int]): Keyword Args: - string_item (str): defaults to 'what', must be one of ['what'] # noqa: E501 - number_item (float): defaults to 1.234, must be one of [1.234] # noqa: E501 - integer_item (int): defaults to -2, must be one of [-2] # noqa: E501 + string_item (str): defaults to 'what', must be one of ["what", ] # noqa: E501 + number_item (float): defaults to 1.234, must be one of [1.234, ] # noqa: E501 + integer_item (int): defaults to -2, must be one of [-2, ] # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. diff --git a/samples/client/petstore/python-experimental/petstore_api/models/user.py b/samples/client/petstore/python-experimental/petstore_api/models/user.py index 3776e7e7f3f8..3b2eeb54b3d9 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/user.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/user.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -113,7 +114,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """user.User - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/petstore_api/models/xml_item.py b/samples/client/petstore/python-experimental/petstore_api/models/xml_item.py index 142c5ea2d6ff..3bcd62804dda 100644 --- a/samples/client/petstore/python-experimental/petstore_api/models/xml_item.py +++ b/samples/client/petstore/python-experimental/petstore_api/models/xml_item.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -155,7 +156,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """xml_item.XmlItem - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/client/petstore/python-experimental/requirements.txt b/samples/client/petstore/python-experimental/requirements.txt index eb358efd5bd3..a56bedffbf57 100644 --- a/samples/client/petstore/python-experimental/requirements.txt +++ b/samples/client/petstore/python-experimental/requirements.txt @@ -1,3 +1,4 @@ +nulltype certifi >= 14.05.14 future; python_version<="2.7" six >= 1.10 diff --git a/samples/client/petstore/python-experimental/setup.py b/samples/client/petstore/python-experimental/setup.py index 7fef185a1a43..09b715bbccba 100644 --- a/samples/client/petstore/python-experimental/setup.py +++ b/samples/client/petstore/python-experimental/setup.py @@ -26,6 +26,7 @@ "six >= 1.10", "certifi", "python-dateutil", + "nulltype", ] EXTRAS = {':python_version <= "2.7"': ['future']} diff --git a/samples/client/petstore/ruby-faraday/.rubocop.yml b/samples/client/petstore/ruby-faraday/.rubocop.yml index 0ef33ce5e322..df46058490d0 100644 --- a/samples/client/petstore/ruby-faraday/.rubocop.yml +++ b/samples/client/petstore/ruby-faraday/.rubocop.yml @@ -14,12 +14,6 @@ AllCops: Style/AndOr: Enabled: true -# Do not use braces for hash literals when they are the last argument of a -# method call. -Style/BracesAroundHashParameters: - Enabled: true - EnforcedStyle: context_dependent - # Align `when` with `case`. Layout/CaseIndentation: Enabled: true @@ -46,7 +40,7 @@ Layout/EmptyLinesAroundMethodBody: Layout/EmptyLinesAroundModuleBody: Enabled: true -Layout/IndentFirstArgument: +Layout/FirstArgumentIndentation: Enabled: true # Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. @@ -57,7 +51,7 @@ Style/HashSyntax: # extra level of indentation. Layout/IndentationConsistency: Enabled: true - EnforcedStyle: rails + EnforcedStyle: indented_internal_methods # Two spaces, no tabs (for indentation). Layout/IndentationWidth: @@ -123,7 +117,7 @@ Layout/Tab: Enabled: true # Blank lines should not have any spaces. -Layout/TrailingBlankLines: +Layout/TrailingEmptyLines: Enabled: true # No trailing whitespace. @@ -131,7 +125,7 @@ Layout/TrailingWhitespace: Enabled: false # Use quotes for string literals when they are enough. -Style/UnneededPercentQ: +Style/RedundantPercentQ: Enabled: true # Align `end` with the matching keyword or starting expression except for diff --git a/samples/client/petstore/ruby-faraday/Gemfile b/samples/client/petstore/ruby-faraday/Gemfile index 69255e559f7c..c2e3127cdcfe 100644 --- a/samples/client/petstore/ruby-faraday/Gemfile +++ b/samples/client/petstore/ruby-faraday/Gemfile @@ -3,7 +3,7 @@ source 'https://rubygems.org' gemspec group :development, :test do - gem 'rake', '~> 12.0.0' + gem 'rake', '~> 13.0.1' gem 'pry-byebug' gem 'rubocop', '~> 0.66.0' end diff --git a/samples/client/petstore/ruby/.rubocop.yml b/samples/client/petstore/ruby/.rubocop.yml index 0ef33ce5e322..df46058490d0 100644 --- a/samples/client/petstore/ruby/.rubocop.yml +++ b/samples/client/petstore/ruby/.rubocop.yml @@ -14,12 +14,6 @@ AllCops: Style/AndOr: Enabled: true -# Do not use braces for hash literals when they are the last argument of a -# method call. -Style/BracesAroundHashParameters: - Enabled: true - EnforcedStyle: context_dependent - # Align `when` with `case`. Layout/CaseIndentation: Enabled: true @@ -46,7 +40,7 @@ Layout/EmptyLinesAroundMethodBody: Layout/EmptyLinesAroundModuleBody: Enabled: true -Layout/IndentFirstArgument: +Layout/FirstArgumentIndentation: Enabled: true # Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. @@ -57,7 +51,7 @@ Style/HashSyntax: # extra level of indentation. Layout/IndentationConsistency: Enabled: true - EnforcedStyle: rails + EnforcedStyle: indented_internal_methods # Two spaces, no tabs (for indentation). Layout/IndentationWidth: @@ -123,7 +117,7 @@ Layout/Tab: Enabled: true # Blank lines should not have any spaces. -Layout/TrailingBlankLines: +Layout/TrailingEmptyLines: Enabled: true # No trailing whitespace. @@ -131,7 +125,7 @@ Layout/TrailingWhitespace: Enabled: false # Use quotes for string literals when they are enough. -Style/UnneededPercentQ: +Style/RedundantPercentQ: Enabled: true # Align `end` with the matching keyword or starting expression except for diff --git a/samples/client/petstore/ruby/Gemfile b/samples/client/petstore/ruby/Gemfile index 69255e559f7c..c2e3127cdcfe 100644 --- a/samples/client/petstore/ruby/Gemfile +++ b/samples/client/petstore/ruby/Gemfile @@ -3,7 +3,7 @@ source 'https://rubygems.org' gemspec group :development, :test do - gem 'rake', '~> 12.0.0' + gem 'rake', '~> 13.0.1' gem 'pry-byebug' gem 'rubocop', '~> 0.66.0' end diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index bef4a88a2e3b..4e2d9c5b69bc 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -156,7 +156,7 @@ end it 'fails for invalid collection format' do - expect{api_client.build_collection_param(param, :INVALID)}.to raise_error(RuntimeError, 'unknown collection format: :INVALID') + expect { api_client.build_collection_param(param, :INVALID) }.to raise_error(RuntimeError, 'unknown collection format: :INVALID') end end diff --git a/samples/client/petstore/scala-akka/.openapi-generator/VERSION b/samples/client/petstore/scala-akka/.openapi-generator/VERSION index 94bf4e677615..bfbf77eb7fad 100644 --- a/samples/client/petstore/scala-akka/.openapi-generator/VERSION +++ b/samples/client/petstore/scala-akka/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/scala-akka/README.md b/samples/client/petstore/scala-akka/README.md index 040074e90ff1..effa8f548ebd 100644 --- a/samples/client/petstore/scala-akka/README.md +++ b/samples/client/petstore/scala-akka/README.md @@ -118,3 +118,4 @@ Authentication schemes defined for the API: ## Author + diff --git a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala index cd23dc723d68..8cdb59f4c003 100644 --- a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala +++ b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala @@ -128,6 +128,8 @@ class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomC req.withHeaders(Authorization(BasicHttpCredentials(login, password))) case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) => req.withHeaders(RawHeader(keyName, keyValue.value)) + case (req, BearerToken(token)) => + req.withHeaders(RawHeader("Authorization", s"Bearer $token")) case (req, _) => req } } diff --git a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/requests.scala b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/requests.scala index b0b56b97fd73..0d3549efec9a 100644 --- a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/requests.scala +++ b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/requests.scala @@ -78,6 +78,8 @@ sealed trait Credentials { sealed case class BasicCredentials(user: String, password: String) extends Credentials +sealed case class BearerToken(token: String) extends Credentials + sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { override def asQueryParam: Option[(String, String)] = location match { case ApiKeyLocations.QUERY => Some((keyName, key.value)) diff --git a/samples/client/petstore/scala-gatling/.openapi-generator/VERSION b/samples/client/petstore/scala-gatling/.openapi-generator/VERSION index 58592f031f65..bfbf77eb7fad 100644 --- a/samples/client/petstore/scala-gatling/.openapi-generator/VERSION +++ b/samples/client/petstore/scala-gatling/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/scala-gatling/build.gradle b/samples/client/petstore/scala-gatling/build.gradle index e0d39a06fe33..a9a3eb68dadf 100644 --- a/samples/client/petstore/scala-gatling/build.gradle +++ b/samples/client/petstore/scala-gatling/build.gradle @@ -3,7 +3,7 @@ plugins { } repositories { - mavenCentral() + maven { url "https://repo1.maven.org/maven2" } } dependencies { diff --git a/samples/client/petstore/scala-httpclient/.openapi-generator/VERSION b/samples/client/petstore/scala-httpclient/.openapi-generator/VERSION index 58592f031f65..bfbf77eb7fad 100644 --- a/samples/client/petstore/scala-httpclient/.openapi-generator/VERSION +++ b/samples/client/petstore/scala-httpclient/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/scala-httpclient/build.gradle b/samples/client/petstore/scala-httpclient/build.gradle index 399197f950b3..bdfd125549b5 100644 --- a/samples/client/petstore/scala-httpclient/build.gradle +++ b/samples/client/petstore/scala-httpclient/build.gradle @@ -109,7 +109,7 @@ ext { repositories { mavenLocal() - mavenCentral() + maven { url "https://repo1.maven.org/maven2" } } dependencies { diff --git a/samples/client/petstore/scala-httpclient/pom.xml b/samples/client/petstore/scala-httpclient/pom.xml index 41aaba5f7f59..8ed860ddd65e 100644 --- a/samples/client/petstore/scala-httpclient/pom.xml +++ b/samples/client/petstore/scala-httpclient/pom.xml @@ -11,7 +11,7 @@ maven-mongodb-plugin-repo maven mongodb plugin repository - + https://maven-mongodb-plugin.googlecode.com/svn/maven/repo default diff --git a/samples/client/petstore/scalaz/.openapi-generator/VERSION b/samples/client/petstore/scalaz/.openapi-generator/VERSION index 58592f031f65..bfbf77eb7fad 100644 --- a/samples/client/petstore/scalaz/.openapi-generator/VERSION +++ b/samples/client/petstore/scalaz/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift4/default/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/default/PetstoreClient.xcodeproj/project.pbxproj index b606fe1ab100..94b4f451305e 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift4/default/PetstoreClient.xcodeproj/project.pbxproj @@ -299,6 +299,8 @@ isa = PBXProject; attributes = { LastUpgradeCheck = 1020; + TargetAttributes = { + }; }; buildConfigurationList = ECAB17FF35111B5E14DAAC08 /* Build configuration list for PBXProject "PetstoreClient" */; compatibilityVersion = "Xcode 10.0"; diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 75dea2439575..200070096800 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -22,7 +22,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" @@ -46,7 +46,7 @@ public struct APIHelper { } public static func mapValueToPathItem(_ source: Any) -> Any { - if let collection = source as? Array { + if let collection = source as? [Any?] { return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") } return source @@ -54,7 +54,7 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") result.append(URLQueryItem(name: item.key, value: value)) } else if let value = item.value { diff --git a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index b0b394aa06e0..8f5d7550f0c8 100644 --- a/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -226,7 +226,7 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - parameter number: (form) None - parameter double: (form) None @@ -255,9 +255,9 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - POST /fake - - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - BASIC: - type: http - name: http_basic_test diff --git a/samples/client/petstore/swift4/default/README.md b/samples/client/petstore/swift4/default/README.md index 0711eb870547..e00b3c99d2ae 100644 --- a/samples/client/petstore/swift4/default/README.md +++ b/samples/client/petstore/swift4/default/README.md @@ -33,7 +33,7 @@ Class | Method | HTTP request | Description *FakeAPI* | [**testBodyWithFileSchema**](docs/FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeAPI* | [**testBodyWithQueryParams**](docs/FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeAPI* | [**testClientModel**](docs/FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters *FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift deleted file mode 100644 index 036e1df7cd50..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Alamofire.swift +++ /dev/null @@ -1,456 +0,0 @@ -// -// Alamofire.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct -/// URL requests. -public protocol URLConvertible { - /// Returns a URL that conforms to RFC 2396 or throws an `Error`. - /// - /// - throws: An `Error` if the type cannot be converted to a `URL`. - /// - /// - returns: A URL or throws an `Error`. - func asURL() throws -> URL -} - -extension String: URLConvertible { - /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. - /// - /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. - /// - /// - returns: A URL or throws an `AFError`. - public func asURL() throws -> URL { - guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } - return url - } -} - -extension URL: URLConvertible { - /// Returns self. - public func asURL() throws -> URL { return self } -} - -extension URLComponents: URLConvertible { - /// Returns a URL if `url` is not nil, otherwise throws an `Error`. - /// - /// - throws: An `AFError.invalidURL` if `url` is `nil`. - /// - /// - returns: A URL or throws an `AFError`. - public func asURL() throws -> URL { - guard let url = url else { throw AFError.invalidURL(url: self) } - return url - } -} - -// MARK: - - -/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. -public protocol URLRequestConvertible { - /// Returns a URL request or throws if an `Error` was encountered. - /// - /// - throws: An `Error` if the underlying `URLRequest` is `nil`. - /// - /// - returns: A URL request. - func asURLRequest() throws -> URLRequest -} - -extension URLRequestConvertible { - /// The URL request. - public var urlRequest: URLRequest? { return try? asURLRequest() } -} - -extension URLRequest: URLRequestConvertible { - /// Returns a URL request or throws if an `Error` was encountered. - public func asURLRequest() throws -> URLRequest { return self } -} - -// MARK: - - -extension URLRequest { - /// Creates an instance with the specified `method`, `urlString` and `headers`. - /// - /// - parameter url: The URL. - /// - parameter method: The HTTP method. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The new `URLRequest` instance. - public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { - let url = try url.asURL() - - self.init(url: url) - - httpMethod = method.rawValue - - if let headers = headers { - for (headerField, headerValue) in headers { - setValue(headerValue, forHTTPHeaderField: headerField) - } - } - } - - func adapt(using adapter: RequestAdapter?) throws -> URLRequest { - guard let adapter = adapter else { return self } - return try adapter.adapt(self) - } -} - -// MARK: - Data Request - -/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, -/// `method`, `parameters`, `encoding` and `headers`. -/// -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.get` by default. -/// - parameter parameters: The parameters. `nil` by default. -/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `DataRequest`. -@discardableResult -public func request( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil) - -> DataRequest { - return SessionManager.default.request( - url, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers - ) -} - -/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the -/// specified `urlRequest`. -/// -/// - parameter urlRequest: The URL request -/// -/// - returns: The created `DataRequest`. -@discardableResult -public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { - return SessionManager.default.request(urlRequest) -} - -// MARK: - Download Request - -// MARK: URL Request - -/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, -/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. -/// -/// If `destination` is not specified, the contents will remain in the temporary location determined by the -/// underlying URL session. -/// -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.get` by default. -/// - parameter parameters: The parameters. `nil` by default. -/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. -/// -/// - returns: The created `DownloadRequest`. -@discardableResult -public func download( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - return SessionManager.default.download( - url, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers, - to: destination - ) -} - -/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the -/// specified `urlRequest` and save them to the `destination`. -/// -/// If `destination` is not specified, the contents will remain in the temporary location determined by the -/// underlying URL session. -/// -/// - parameter urlRequest: The URL request. -/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. -/// -/// - returns: The created `DownloadRequest`. -@discardableResult -public func download( - _ urlRequest: URLRequestConvertible, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - return SessionManager.default.download(urlRequest, to: destination) -} - -// MARK: Resume Data - -/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a -/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. -/// -/// If `destination` is not specified, the contents will remain in the temporary location determined by the -/// underlying URL session. -/// -/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken -/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the -/// data is written incorrectly and will always fail to resume the download. For more information about the bug and -/// possible workarounds, please refer to the following Stack Overflow post: -/// -/// - http://stackoverflow.com/a/39347461/1342462 -/// -/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` -/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional -/// information. -/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. -/// -/// - returns: The created `DownloadRequest`. -@discardableResult -public func download( - resumingWith resumeData: Data, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - return SessionManager.default.download(resumingWith: resumeData, to: destination) -} - -// MARK: - Upload Request - -// MARK: File - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` -/// for uploading the `file`. -/// -/// - parameter file: The file to upload. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload( - _ fileURL: URL, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) -} - -/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for -/// uploading the `file`. -/// -/// - parameter file: The file to upload. -/// - parameter urlRequest: The URL request. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { - return SessionManager.default.upload(fileURL, with: urlRequest) -} - -// MARK: Data - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` -/// for uploading the `data`. -/// -/// - parameter data: The data to upload. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload( - _ data: Data, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - return SessionManager.default.upload(data, to: url, method: method, headers: headers) -} - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for -/// uploading the `data`. -/// -/// - parameter data: The data to upload. -/// - parameter urlRequest: The URL request. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { - return SessionManager.default.upload(data, with: urlRequest) -} - -// MARK: InputStream - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` -/// for uploading the `stream`. -/// -/// - parameter stream: The stream to upload. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload( - _ stream: InputStream, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - return SessionManager.default.upload(stream, to: url, method: method, headers: headers) -} - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for -/// uploading the `stream`. -/// -/// - parameter urlRequest: The URL request. -/// - parameter stream: The stream to upload. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { - return SessionManager.default.upload(stream, with: urlRequest) -} - -// MARK: MultipartFormData - -/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls -/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. -/// -/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative -/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -/// used for larger payloads such as video content. -/// -/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory -/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, -/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -/// technique was used. -/// -/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. -/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. -/// `multipartFormDataEncodingMemoryThreshold` by default. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. -public func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { - return SessionManager.default.upload( - multipartFormData: multipartFormData, - usingThreshold: encodingMemoryThreshold, - to: url, - method: method, - headers: headers, - encodingCompletion: encodingCompletion - ) -} - -/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and -/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. -/// -/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative -/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -/// used for larger payloads such as video content. -/// -/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory -/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, -/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -/// technique was used. -/// -/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. -/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. -/// `multipartFormDataEncodingMemoryThreshold` by default. -/// - parameter urlRequest: The URL request. -/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. -public func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - with urlRequest: URLRequestConvertible, - encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { - return SessionManager.default.upload( - multipartFormData: multipartFormData, - usingThreshold: encodingMemoryThreshold, - with: urlRequest, - encodingCompletion: encodingCompletion - ) -} - -#if !os(watchOS) - -// MARK: - Stream Request - -// MARK: Hostname and Port - -/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` -/// and `port`. -/// -/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. -/// -/// - parameter hostName: The hostname of the server to connect to. -/// - parameter port: The port of the server to connect to. -/// -/// - returns: The created `StreamRequest`. -@discardableResult -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -public func stream(withHostName hostName: String, port: Int) -> StreamRequest { - return SessionManager.default.stream(withHostName: hostName, port: port) -} - -// MARK: NetService - -/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. -/// -/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. -/// -/// - parameter netService: The net service used to identify the endpoint. -/// -/// - returns: The created `StreamRequest`. -@discardableResult -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -public func stream(with netService: NetService) -> StreamRequest { - return SessionManager.default.stream(with: netService) -} - -#endif diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift deleted file mode 100644 index 7df468a011c8..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/MultipartFormData.swift +++ /dev/null @@ -1,578 +0,0 @@ -// -// MultipartFormData.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -#if os(iOS) || os(watchOS) || os(tvOS) -import MobileCoreServices -#elseif os(macOS) -import CoreServices -#endif - -/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode -/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead -/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the -/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for -/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. -/// -/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well -/// and the w3 form documentation. -/// -/// - https://www.ietf.org/rfc/rfc2388.txt -/// - https://www.ietf.org/rfc/rfc2045.txt -/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 -open class MultipartFormData { - - // MARK: - Helper Types - - struct EncodingCharacters { - static let crlf = "\r\n" - } - - struct BoundaryGenerator { - enum BoundaryType { - case initial, encapsulated, final - } - - static func randomBoundary() -> String { - return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) - } - - static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { - let boundaryText: String - - switch boundaryType { - case .initial: - boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" - case .encapsulated: - boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" - case .final: - boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" - } - - return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! - } - } - - class BodyPart { - let headers: HTTPHeaders - let bodyStream: InputStream - let bodyContentLength: UInt64 - var hasInitialBoundary = false - var hasFinalBoundary = false - - init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { - self.headers = headers - self.bodyStream = bodyStream - self.bodyContentLength = bodyContentLength - } - } - - // MARK: - Properties - - /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. - open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)" - - /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. - public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } - - /// The boundary used to separate the body parts in the encoded form data. - public var boundary: String - - private var bodyParts: [BodyPart] - private var bodyPartError: AFError? - private let streamBufferSize: Int - - // MARK: - Lifecycle - - /// Creates a multipart form data object. - /// - /// - returns: The multipart form data object. - public init() { - self.boundary = BoundaryGenerator.randomBoundary() - self.bodyParts = [] - - /// - /// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more - /// information, please refer to the following article: - /// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html - /// - - self.streamBufferSize = 1024 - } - - // MARK: - Body Parts - - /// Creates a body part from the data and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - /// - Encoded data - /// - Multipart form boundary - /// - /// - parameter data: The data to encode into the multipart form data. - /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - public func append(_ data: Data, withName name: String) { - let headers = contentHeaders(withName: name) - let stream = InputStream(data: data) - let length = UInt64(data.count) - - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part from the data and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - /// - `Content-Type: #{generated mimeType}` (HTTP Header) - /// - Encoded data - /// - Multipart form boundary - /// - /// - parameter data: The data to encode into the multipart form data. - /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. - public func append(_ data: Data, withName name: String, mimeType: String) { - let headers = contentHeaders(withName: name, mimeType: mimeType) - let stream = InputStream(data: data) - let length = UInt64(data.count) - - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part from the data and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - /// - `Content-Type: #{mimeType}` (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// - parameter data: The data to encode into the multipart form data. - /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. - public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - let stream = InputStream(data: data) - let length = UInt64(data.count) - - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part from the file and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) - /// - `Content-Type: #{generated mimeType}` (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the - /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the - /// system associated MIME type. - /// - /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. - public func append(_ fileURL: URL, withName name: String) { - let fileName = fileURL.lastPathComponent - let pathExtension = fileURL.pathExtension - - if !fileName.isEmpty && !pathExtension.isEmpty { - let mime = mimeType(forPathExtension: pathExtension) - append(fileURL, withName: name, fileName: fileName, mimeType: mime) - } else { - setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) - } - } - - /// Creates a body part from the file and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) - /// - Content-Type: #{mimeType} (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. - /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. - public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - - //============================================================ - // Check 1 - is file URL? - //============================================================ - - guard fileURL.isFileURL else { - setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) - return - } - - //============================================================ - // Check 2 - is file URL reachable? - //============================================================ - - do { - let isReachable = try fileURL.checkPromisedItemIsReachable() - guard isReachable else { - setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) - return - } - } catch { - setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) - return - } - - //============================================================ - // Check 3 - is file URL a directory? - //============================================================ - - var isDirectory: ObjCBool = false - let path = fileURL.path - - guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { - setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) - return - } - - //============================================================ - // Check 4 - can the file size be extracted? - //============================================================ - - let bodyContentLength: UInt64 - - do { - guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { - setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) - return - } - - bodyContentLength = fileSize.uint64Value - } catch { - setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) - return - } - - //============================================================ - // Check 5 - can a stream be created from file URL? - //============================================================ - - guard let stream = InputStream(url: fileURL) else { - setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) - return - } - - append(stream, withLength: bodyContentLength, headers: headers) - } - - /// Creates a body part from the stream and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - /// - `Content-Type: #{mimeType}` (HTTP Header) - /// - Encoded stream data - /// - Multipart form boundary - /// - /// - parameter stream: The input stream to encode in the multipart form data. - /// - parameter length: The content length of the stream. - /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. - /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. - public func append( - _ stream: InputStream, - withLength length: UInt64, - name: String, - fileName: String, - mimeType: String) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part with the headers, stream and length and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - HTTP headers - /// - Encoded stream data - /// - Multipart form boundary - /// - /// - parameter stream: The input stream to encode in the multipart form data. - /// - parameter length: The content length of the stream. - /// - parameter headers: The HTTP headers for the body part. - public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { - let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) - bodyParts.append(bodyPart) - } - - // MARK: - Data Encoding - - /// Encodes all the appended body parts into a single `Data` value. - /// - /// It is important to note that this method will load all the appended body parts into memory all at the same - /// time. This method should only be used when the encoded data will have a small memory footprint. For large data - /// cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. - /// - /// - throws: An `AFError` if encoding encounters an error. - /// - /// - returns: The encoded `Data` if encoding is successful. - public func encode() throws -> Data { - if let bodyPartError = bodyPartError { - throw bodyPartError - } - - var encoded = Data() - - bodyParts.first?.hasInitialBoundary = true - bodyParts.last?.hasFinalBoundary = true - - for bodyPart in bodyParts { - let encodedData = try encode(bodyPart) - encoded.append(encodedData) - } - - return encoded - } - - /// Writes the appended body parts into the given file URL. - /// - /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, - /// this approach is very memory efficient and should be used for large body part data. - /// - /// - parameter fileURL: The file URL to write the multipart form data into. - /// - /// - throws: An `AFError` if encoding encounters an error. - public func writeEncodedData(to fileURL: URL) throws { - if let bodyPartError = bodyPartError { - throw bodyPartError - } - - if FileManager.default.fileExists(atPath: fileURL.path) { - throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) - } else if !fileURL.isFileURL { - throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) - } - - guard let outputStream = OutputStream(url: fileURL, append: false) else { - throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) - } - - outputStream.open() - defer { outputStream.close() } - - self.bodyParts.first?.hasInitialBoundary = true - self.bodyParts.last?.hasFinalBoundary = true - - for bodyPart in self.bodyParts { - try write(bodyPart, to: outputStream) - } - } - - // MARK: - Private - Body Part Encoding - - private func encode(_ bodyPart: BodyPart) throws -> Data { - var encoded = Data() - - let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() - encoded.append(initialData) - - let headerData = encodeHeaders(for: bodyPart) - encoded.append(headerData) - - let bodyStreamData = try encodeBodyStream(for: bodyPart) - encoded.append(bodyStreamData) - - if bodyPart.hasFinalBoundary { - encoded.append(finalBoundaryData()) - } - - return encoded - } - - private func encodeHeaders(for bodyPart: BodyPart) -> Data { - var headerText = "" - - for (key, value) in bodyPart.headers { - headerText += "\(key): \(value)\(EncodingCharacters.crlf)" - } - headerText += EncodingCharacters.crlf - - return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! - } - - private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { - let inputStream = bodyPart.bodyStream - inputStream.open() - defer { inputStream.close() } - - var encoded = Data() - - while inputStream.hasBytesAvailable { - var buffer = [UInt8](repeating: 0, count: streamBufferSize) - let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) - - if let error = inputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) - } - - if bytesRead > 0 { - encoded.append(buffer, count: bytesRead) - } else { - break - } - } - - return encoded - } - - // MARK: - Private - Writing Body Part to Output Stream - - private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { - try writeInitialBoundaryData(for: bodyPart, to: outputStream) - try writeHeaderData(for: bodyPart, to: outputStream) - try writeBodyStream(for: bodyPart, to: outputStream) - try writeFinalBoundaryData(for: bodyPart, to: outputStream) - } - - private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() - return try write(initialData, to: outputStream) - } - - private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let headerData = encodeHeaders(for: bodyPart) - return try write(headerData, to: outputStream) - } - - private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let inputStream = bodyPart.bodyStream - - inputStream.open() - defer { inputStream.close() } - - while inputStream.hasBytesAvailable { - var buffer = [UInt8](repeating: 0, count: streamBufferSize) - let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) - - if let streamError = inputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) - } - - if bytesRead > 0 { - if buffer.count != bytesRead { - buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { - let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) - - if let error = outputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) - } - - bytesToWrite -= bytesWritten - - if bytesToWrite > 0 { - buffer = Array(buffer[bytesWritten.. String { - if - let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), - let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() - { - return contentType as String - } - - return "application/octet-stream" - } - - // MARK: - Private - Content Headers - - private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { - var disposition = "form-data; name=\"\(name)\"" - if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } - - var headers = ["Content-Disposition": disposition] - if let mimeType = mimeType { headers["Content-Type"] = mimeType } - - return headers - } - - // MARK: - Private - Boundary Encoding - - private func initialBoundaryData() -> Data { - return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) - } - - private func encapsulatedBoundaryData() -> Data { - return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) - } - - private func finalBoundaryData() -> Data { - return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) - } - - // MARK: - Private - Errors - - private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { - guard bodyPartError == nil else { return } - bodyPartError = AFError.multipartEncodingFailed(reason: reason) - } -} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift deleted file mode 100644 index fa0647934f67..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/NetworkReachabilityManager.swift +++ /dev/null @@ -1,236 +0,0 @@ -// -// NetworkReachabilityManager.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -#if !os(watchOS) - -import Foundation -import SystemConfiguration - -/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and -/// WiFi network interfaces. -/// -/// Reachability can be used to determine background information about why a network operation failed, or to retry -/// network requests when a connection is established. It should not be used to prevent a user from initiating a network -/// request, as it's possible that an initial request may be required to establish reachability. -open class NetworkReachabilityManager { - /// Defines the various states of network reachability. - /// - /// - unknown: It is unknown whether the network is reachable. - /// - notReachable: The network is not reachable. - /// - reachable: The network is reachable. - public enum NetworkReachabilityStatus { - case unknown - case notReachable - case reachable(ConnectionType) - } - - /// Defines the various connection types detected by reachability flags. - /// - /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. - /// - wwan: The connection type is a WWAN connection. - public enum ConnectionType { - case ethernetOrWiFi - case wwan - } - - /// A closure executed when the network reachability status changes. The closure takes a single argument: the - /// network reachability status. - public typealias Listener = (NetworkReachabilityStatus) -> Void - - // MARK: - Properties - - /// Whether the network is currently reachable. - open var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } - - /// Whether the network is currently reachable over the WWAN interface. - open var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } - - /// Whether the network is currently reachable over Ethernet or WiFi interface. - open var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } - - /// The current network reachability status. - open var networkReachabilityStatus: NetworkReachabilityStatus { - guard let flags = self.flags else { return .unknown } - return networkReachabilityStatusForFlags(flags) - } - - /// The dispatch queue to execute the `listener` closure on. - open var listenerQueue: DispatchQueue = DispatchQueue.main - - /// A closure executed when the network reachability status changes. - open var listener: Listener? - - open var flags: SCNetworkReachabilityFlags? { - var flags = SCNetworkReachabilityFlags() - - if SCNetworkReachabilityGetFlags(reachability, &flags) { - return flags - } - - return nil - } - - private let reachability: SCNetworkReachability - open var previousFlags: SCNetworkReachabilityFlags - - // MARK: - Initialization - - /// Creates a `NetworkReachabilityManager` instance with the specified host. - /// - /// - parameter host: The host used to evaluate network reachability. - /// - /// - returns: The new `NetworkReachabilityManager` instance. - public convenience init?(host: String) { - guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } - self.init(reachability: reachability) - } - - /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. - /// - /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing - /// status of the device, both IPv4 and IPv6. - /// - /// - returns: The new `NetworkReachabilityManager` instance. - public convenience init?() { - var address = sockaddr_in() - address.sin_len = UInt8(MemoryLayout.size) - address.sin_family = sa_family_t(AF_INET) - - guard let reachability = withUnsafePointer(to: &address, { pointer in - return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { - return SCNetworkReachabilityCreateWithAddress(nil, $0) - } - }) else { return nil } - - self.init(reachability: reachability) - } - - private init(reachability: SCNetworkReachability) { - self.reachability = reachability - - // Set the previous flags to an unreserved value to represent unknown status - self.previousFlags = SCNetworkReachabilityFlags(rawValue: 1 << 30) - } - - deinit { - stopListening() - } - - // MARK: - Listening - - /// Starts listening for changes in network reachability status. - /// - /// - returns: `true` if listening was started successfully, `false` otherwise. - @discardableResult - open func startListening() -> Bool { - var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) - context.info = Unmanaged.passUnretained(self).toOpaque() - - let callbackEnabled = SCNetworkReachabilitySetCallback( - reachability, { (_, flags, info) in - let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() - reachability.notifyListener(flags) - }, - &context - ) - - let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) - - listenerQueue.async { - self.previousFlags = SCNetworkReachabilityFlags(rawValue: 1 << 30) - - guard let flags = self.flags else { return } - - self.notifyListener(flags) - } - - return callbackEnabled && queueEnabled - } - - /// Stops listening for changes in network reachability status. - open func stopListening() { - SCNetworkReachabilitySetCallback(reachability, nil, nil) - SCNetworkReachabilitySetDispatchQueue(reachability, nil) - } - - // MARK: - Internal - Listener Notification - - func notifyListener(_ flags: SCNetworkReachabilityFlags) { - guard previousFlags != flags else { return } - previousFlags = flags - - listener?(networkReachabilityStatusForFlags(flags)) - } - - // MARK: - Internal - Network Reachability Status - - func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { - guard isNetworkReachable(with: flags) else { return .notReachable } - - var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) - - #if os(iOS) - if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } - #endif - - return networkStatus - } - - func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { - let isReachable = flags.contains(.reachable) - let needsConnection = flags.contains(.connectionRequired) - let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) - let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) - - return isReachable && (!needsConnection || canConnectWithoutUserInteraction) - } -} - -// MARK: - - -extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} - -/// Returns whether the two network reachability status values are equal. -/// -/// - parameter lhs: The left-hand side value to compare. -/// - parameter rhs: The right-hand side value to compare. -/// -/// - returns: `true` if the two values are equal, `false` otherwise. -public func ==( - lhs: NetworkReachabilityManager.NetworkReachabilityStatus, - rhs: NetworkReachabilityManager.NetworkReachabilityStatus) - -> Bool { - switch (lhs, rhs) { - case (.unknown, .unknown): - return true - case (.notReachable, .notReachable): - return true - case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): - return lhsConnectionType == rhsConnectionType - default: - return false - } -} - -#endif diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift deleted file mode 100644 index dc8e75e847df..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ParameterEncoding.swift +++ /dev/null @@ -1,482 +0,0 @@ -// -// ParameterEncoding.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// HTTP method definitions. -/// -/// See https://tools.ietf.org/html/rfc7231#section-4.3 -public enum HTTPMethod: String { - case options = "OPTIONS" - case get = "GET" - case head = "HEAD" - case post = "POST" - case put = "PUT" - case patch = "PATCH" - case delete = "DELETE" - case trace = "TRACE" - case connect = "CONNECT" -} - -// MARK: - - -/// A dictionary of parameters to apply to a `URLRequest`. -public typealias Parameters = [String: Any] - -/// A type used to define how a set of parameters are applied to a `URLRequest`. -public protocol ParameterEncoding { - /// Creates a URL request by encoding parameters and applying them onto an existing request. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. - /// - /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. - /// - /// - returns: The encoded request. - func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest -} - -// MARK: - - -/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP -/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as -/// the HTTP body depends on the destination of the encoding. -/// -/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to -/// `application/x-www-form-urlencoded; charset=utf-8`. -/// -/// There is no published specification for how to encode collection types. By default the convention of appending -/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for -/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the -/// square brackets appended to array keys. -/// -/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode -/// `true` as 1 and `false` as 0. -public struct URLEncoding: ParameterEncoding { - - // MARK: Helper Types - - /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the - /// resulting URL request. - /// - /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` - /// requests and sets as the HTTP body for requests with any other HTTP method. - /// - queryString: Sets or appends encoded query string result to existing query string. - /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. - public enum Destination { - case methodDependent, queryString, httpBody - } - - /// Configures how `Array` parameters are encoded. - /// - /// - brackets: An empty set of square brackets is appended to the key for every value. - /// This is the default behavior. - /// - noBrackets: No brackets are appended. The key is encoded as is. - public enum ArrayEncoding { - case brackets, noBrackets - - func encode(key: String) -> String { - switch self { - case .brackets: - return "\(key)[]" - case .noBrackets: - return key - } - } - } - - /// Configures how `Bool` parameters are encoded. - /// - /// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior. - /// - literal: Encode `true` and `false` as string literals. - public enum BoolEncoding { - case numeric, literal - - func encode(value: Bool) -> String { - switch self { - case .numeric: - return value ? "1" : "0" - case .literal: - return value ? "true" : "false" - } - } - } - - // MARK: Properties - - /// Returns a default `URLEncoding` instance. - public static var `default`: URLEncoding { return URLEncoding() } - - /// Returns a `URLEncoding` instance with a `.methodDependent` destination. - public static var methodDependent: URLEncoding { return URLEncoding() } - - /// Returns a `URLEncoding` instance with a `.queryString` destination. - public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } - - /// Returns a `URLEncoding` instance with an `.httpBody` destination. - public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } - - /// The destination defining where the encoded query string is to be applied to the URL request. - public let destination: Destination - - /// The encoding to use for `Array` parameters. - public let arrayEncoding: ArrayEncoding - - /// The encoding to use for `Bool` parameters. - public let boolEncoding: BoolEncoding - - // MARK: Initialization - - /// Creates a `URLEncoding` instance using the specified destination. - /// - /// - parameter destination: The destination defining where the encoded query string is to be applied. - /// - parameter arrayEncoding: The encoding to use for `Array` parameters. - /// - parameter boolEncoding: The encoding to use for `Bool` parameters. - /// - /// - returns: The new `URLEncoding` instance. - public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) { - self.destination = destination - self.arrayEncoding = arrayEncoding - self.boolEncoding = boolEncoding - } - - // MARK: Encoding - - /// Creates a URL request by encoding parameters and applying them onto an existing request. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. - /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - returns: The encoded request. - public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let parameters = parameters else { return urlRequest } - - if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { - guard let url = urlRequest.url else { - throw AFError.parameterEncodingFailed(reason: .missingURL) - } - - if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { - let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) - urlComponents.percentEncodedQuery = percentEncodedQuery - urlRequest.url = urlComponents.url - } - } else { - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) - } - - return urlRequest - } - - /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. - /// - /// - parameter key: The key of the query component. - /// - parameter value: The value of the query component. - /// - /// - returns: The percent-escaped, URL encoded query string components. - public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { - var components: [(String, String)] = [] - - if let dictionary = value as? [String: Any] { - for (nestedKey, value) in dictionary { - components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) - } - } else if let array = value as? [Any] { - for value in array { - components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value) - } - } else if let value = value as? NSNumber { - if value.isBool { - components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue)))) - } else { - components.append((escape(key), escape("\(value)"))) - } - } else if let bool = value as? Bool { - components.append((escape(key), escape(boolEncoding.encode(value: bool)))) - } else { - components.append((escape(key), escape("\(value)"))) - } - - return components - } - - /// Returns a percent-escaped string following RFC 3986 for a query string key or value. - /// - /// RFC 3986 states that the following characters are "reserved" characters. - /// - /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" - /// - /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow - /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" - /// should be percent-escaped in the query string. - /// - /// - parameter string: The string to be percent-escaped. - /// - /// - returns: The percent-escaped string. - public func escape(_ string: String) -> String { - let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 - let subDelimitersToEncode = "!$&'()*+,;=" - - var allowedCharacterSet = CharacterSet.urlQueryAllowed - allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") - - var escaped = "" - - //========================================================================================================== - // - // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few - // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no - // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more - // info, please refer to: - // - // - https://github.com/Alamofire/Alamofire/issues/206 - // - //========================================================================================================== - - if #available(iOS 8.3, *) { - escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string - } else { - let batchSize = 50 - var index = string.startIndex - - while index != string.endIndex { - let startIndex = index - let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex - let range = startIndex.. String { - var components: [(String, String)] = [] - - for key in parameters.keys.sorted(by: <) { - let value = parameters[key]! - components += queryComponents(fromKey: key, value: value) - } - return components.map { "\($0)=\($1)" }.joined(separator: "&") - } - - private func encodesParametersInURL(with method: HTTPMethod) -> Bool { - switch destination { - case .queryString: - return true - case .httpBody: - return false - default: - break - } - - switch method { - case .get, .head, .delete: - return true - default: - return false - } - } -} - -// MARK: - - -/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the -/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. -public struct JSONEncoding: ParameterEncoding { - - // MARK: Properties - - /// Returns a `JSONEncoding` instance with default writing options. - public static var `default`: JSONEncoding { return JSONEncoding() } - - /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. - public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } - - /// The options for writing the parameters as JSON data. - public let options: JSONSerialization.WritingOptions - - // MARK: Initialization - - /// Creates a `JSONEncoding` instance using the specified options. - /// - /// - parameter options: The options for writing the parameters as JSON data. - /// - /// - returns: The new `JSONEncoding` instance. - public init(options: JSONSerialization.WritingOptions = []) { - self.options = options - } - - // MARK: Encoding - - /// Creates a URL request by encoding parameters and applying them onto an existing request. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. - /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - returns: The encoded request. - public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let parameters = parameters else { return urlRequest } - - do { - let data = try JSONSerialization.data(withJSONObject: parameters, options: options) - - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = data - } catch { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) - } - - return urlRequest - } - - /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. - /// - /// - parameter urlRequest: The request to apply the JSON object to. - /// - parameter jsonObject: The JSON object to apply to the request. - /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - returns: The encoded request. - public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let jsonObject = jsonObject else { return urlRequest } - - do { - let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) - - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = data - } catch { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) - } - - return urlRequest - } -} - -// MARK: - - -/// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the -/// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header -/// field of an encoded request is set to `application/x-plist`. -public struct PropertyListEncoding: ParameterEncoding { - - // MARK: Properties - - /// Returns a default `PropertyListEncoding` instance. - public static var `default`: PropertyListEncoding { return PropertyListEncoding() } - - /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. - public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } - - /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. - public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } - - /// The property list serialization format. - public let format: PropertyListSerialization.PropertyListFormat - - /// The options for writing the parameters as plist data. - public let options: PropertyListSerialization.WriteOptions - - // MARK: Initialization - - /// Creates a `PropertyListEncoding` instance using the specified format and options. - /// - /// - parameter format: The property list serialization format. - /// - parameter options: The options for writing the parameters as plist data. - /// - /// - returns: The new `PropertyListEncoding` instance. - public init( - format: PropertyListSerialization.PropertyListFormat = .xml, - options: PropertyListSerialization.WriteOptions = 0) { - self.format = format - self.options = options - } - - // MARK: Encoding - - /// Creates a URL request by encoding parameters and applying them onto an existing request. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. - /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - returns: The encoded request. - public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let parameters = parameters else { return urlRequest } - - do { - let data = try PropertyListSerialization.data( - fromPropertyList: parameters, - format: format, - options: options - ) - - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = data - } catch { - throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) - } - - return urlRequest - } -} - -// MARK: - - -extension NSNumber { - fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } -} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Request.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Request.swift deleted file mode 100644 index 9cd75057cae2..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Request.swift +++ /dev/null @@ -1,658 +0,0 @@ -// -// Request.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. -public protocol RequestAdapter { - /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. - /// - /// - parameter urlRequest: The URL request to adapt. - /// - /// - throws: An `Error` if the adaptation encounters an error. - /// - /// - returns: The adapted `URLRequest`. - func adapt(_ urlRequest: URLRequest) throws -> URLRequest -} - -// MARK: - - -/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. -public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void - -/// A type that determines whether a request should be retried after being executed by the specified session manager -/// and encountering an error. -public protocol RequestRetrier { - /// Determines whether the `Request` should be retried by calling the `completion` closure. - /// - /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs - /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly - /// cleaned up after. - /// - /// - parameter manager: The session manager the request was executed on. - /// - parameter request: The request that failed due to the encountered error. - /// - parameter error: The error encountered when executing the request. - /// - parameter completion: The completion closure to be executed when retry decision has been determined. - func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) -} - -// MARK: - - -protocol TaskConvertible { - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask -} - -/// A dictionary of headers to apply to a `URLRequest`. -public typealias HTTPHeaders = [String: String] - -// MARK: - - -/// Responsible for sending a request and receiving the response and associated data from the server, as well as -/// managing its underlying `URLSessionTask`. -open class Request { - - // MARK: Helper Types - - /// A closure executed when monitoring upload or download progress of a request. - public typealias ProgressHandler = (Progress) -> Void - - enum RequestTask { - case data(TaskConvertible?, URLSessionTask?) - case download(TaskConvertible?, URLSessionTask?) - case upload(TaskConvertible?, URLSessionTask?) - case stream(TaskConvertible?, URLSessionTask?) - } - - // MARK: Properties - - /// The delegate for the underlying task. - open internal(set) var delegate: TaskDelegate { - get { - taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } - return taskDelegate - } - set { - taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } - taskDelegate = newValue - } - } - - /// The underlying task. - open var task: URLSessionTask? { return delegate.task } - - /// The session belonging to the underlying task. - public let session: URLSession - - /// The request sent or to be sent to the server. - open var request: URLRequest? { return task?.originalRequest } - - /// The response received from the server, if any. - open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } - - /// The number of times the request has been retried. - open internal(set) var retryCount: UInt = 0 - - let originalTask: TaskConvertible? - - var startTime: CFAbsoluteTime? - var endTime: CFAbsoluteTime? - - var validations: [() -> Void] = [] - - private var taskDelegate: TaskDelegate - private var taskDelegateLock = NSLock() - - // MARK: Lifecycle - - init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { - self.session = session - - switch requestTask { - case .data(let originalTask, let task): - taskDelegate = DataTaskDelegate(task: task) - self.originalTask = originalTask - case .download(let originalTask, let task): - taskDelegate = DownloadTaskDelegate(task: task) - self.originalTask = originalTask - case .upload(let originalTask, let task): - taskDelegate = UploadTaskDelegate(task: task) - self.originalTask = originalTask - case .stream(let originalTask, let task): - taskDelegate = TaskDelegate(task: task) - self.originalTask = originalTask - } - - delegate.error = error - delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } - } - - // MARK: Authentication - - /// Associates an HTTP Basic credential with the request. - /// - /// - parameter user: The user. - /// - parameter password: The password. - /// - parameter persistence: The URL credential persistence. `.ForSession` by default. - /// - /// - returns: The request. - @discardableResult - open func authenticate( - user: String, - password: String, - persistence: URLCredential.Persistence = .forSession) - -> Self { - let credential = URLCredential(user: user, password: password, persistence: persistence) - return authenticate(usingCredential: credential) - } - - /// Associates a specified credential with the request. - /// - /// - parameter credential: The credential. - /// - /// - returns: The request. - @discardableResult - open func authenticate(usingCredential credential: URLCredential) -> Self { - delegate.credential = credential - return self - } - - /// Returns a base64 encoded basic authentication credential as an authorization header tuple. - /// - /// - parameter user: The user. - /// - parameter password: The password. - /// - /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. - open class func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { - guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } - - let credential = data.base64EncodedString(options: []) - - return (key: "Authorization", value: "Basic \(credential)") - } - - // MARK: State - - /// Resumes the request. - open func resume() { - guard let task = task else { delegate.queue.isSuspended = false ; return } - - if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } - - task.resume() - - NotificationCenter.default.post( - name: Notification.Name.Task.DidResume, - object: self, - userInfo: [Notification.Key.Task: task] - ) - } - - /// Suspends the request. - open func suspend() { - guard let task = task else { return } - - task.suspend() - - NotificationCenter.default.post( - name: Notification.Name.Task.DidSuspend, - object: self, - userInfo: [Notification.Key.Task: task] - ) - } - - /// Cancels the request. - open func cancel() { - guard let task = task else { return } - - task.cancel() - - NotificationCenter.default.post( - name: Notification.Name.Task.DidCancel, - object: self, - userInfo: [Notification.Key.Task: task] - ) - } -} - -// MARK: - CustomStringConvertible - -extension Request: CustomStringConvertible { - /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as - /// well as the response status code if a response has been received. - open var description: String { - var components: [String] = [] - - if let HTTPMethod = request?.httpMethod { - components.append(HTTPMethod) - } - - if let urlString = request?.url?.absoluteString { - components.append(urlString) - } - - if let response = response { - components.append("(\(response.statusCode))") - } - - return components.joined(separator: " ") - } -} - -// MARK: - CustomDebugStringConvertible - -extension Request: CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, in the form of a cURL command. - open var debugDescription: String { - return cURLRepresentation() - } - - func cURLRepresentation() -> String { - var components = ["$ curl -v"] - - guard let request = self.request, - let url = request.url, - let host = url.host - else { - return "$ curl command could not be created" - } - - if let httpMethod = request.httpMethod, httpMethod != "GET" { - components.append("-X \(httpMethod)") - } - - if let credentialStorage = self.session.configuration.urlCredentialStorage { - let protectionSpace = URLProtectionSpace( - host: host, - port: url.port ?? 0, - protocol: url.scheme, - realm: host, - authenticationMethod: NSURLAuthenticationMethodHTTPBasic - ) - - if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { - for credential in credentials { - guard let user = credential.user, let password = credential.password else { continue } - components.append("-u \(user):\(password)") - } - } else { - if let credential = delegate.credential, let user = credential.user, let password = credential.password { - components.append("-u \(user):\(password)") - } - } - } - - if session.configuration.httpShouldSetCookies { - if - let cookieStorage = session.configuration.httpCookieStorage, - let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty - { - let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } - - #if swift(>=3.2) - components.append("-b \"\(string[.. URLSessionTask { - do { - let urlRequest = try self.urlRequest.adapt(using: adapter) - return queue.sync { session.dataTask(with: urlRequest) } - } catch { - throw AdaptError(error: error) - } - } - } - - // MARK: Properties - - /// The request sent or to be sent to the server. - open override var request: URLRequest? { - if let request = super.request { return request } - if let requestable = originalTask as? Requestable { return requestable.urlRequest } - - return nil - } - - /// The progress of fetching the response data from the server for the request. - open var progress: Progress { return dataDelegate.progress } - - var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } - - // MARK: Stream - - /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. - /// - /// This closure returns the bytes most recently received from the server, not including data from previous calls. - /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is - /// also important to note that the server data in any `Response` object will be `nil`. - /// - /// - parameter closure: The code to be executed periodically during the lifecycle of the request. - /// - /// - returns: The request. - @discardableResult - open func stream(closure: ((Data) -> Void)? = nil) -> Self { - dataDelegate.dataStream = closure - return self - } - - // MARK: Progress - - /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. - /// - /// - parameter queue: The dispatch queue to execute the closure on. - /// - parameter closure: The code to be executed periodically as data is read from the server. - /// - /// - returns: The request. - @discardableResult - open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { - dataDelegate.progressHandler = (closure, queue) - return self - } -} - -// MARK: - - -/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. -open class DownloadRequest: Request { - - // MARK: Helper Types - - /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the - /// destination URL. - public struct DownloadOptions: OptionSet { - /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. - public let rawValue: UInt - - /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. - public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) - - /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. - public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) - - /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. - /// - /// - parameter rawValue: The raw bitmask value for the option. - /// - /// - returns: A new log level instance. - public init(rawValue: UInt) { - self.rawValue = rawValue - } - } - - /// A closure executed once a download request has successfully completed in order to determine where to move the - /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL - /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and - /// the options defining how the file should be moved. - public typealias DownloadFileDestination = ( - _ temporaryURL: URL, - _ response: HTTPURLResponse) - -> (destinationURL: URL, options: DownloadOptions) - - enum Downloadable: TaskConvertible { - case request(URLRequest) - case resumeData(Data) - - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - do { - let task: URLSessionTask - - switch self { - case let .request(urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.downloadTask(with: urlRequest) } - case let .resumeData(resumeData): - task = queue.sync { session.downloadTask(withResumeData: resumeData) } - } - - return task - } catch { - throw AdaptError(error: error) - } - } - } - - // MARK: Properties - - /// The request sent or to be sent to the server. - open override var request: URLRequest? { - if let request = super.request { return request } - - if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { - return urlRequest - } - - return nil - } - - /// The resume data of the underlying download task if available after a failure. - open var resumeData: Data? { return downloadDelegate.resumeData } - - /// The progress of downloading the response data from the server for the request. - open var progress: Progress { return downloadDelegate.progress } - - var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } - - // MARK: State - - /// Cancels the request. - override open func cancel() { - cancel(createResumeData: true) - } - - /// Cancels the request. - /// - /// - parameter createResumeData: Determines whether resume data is created via the underlying download task or not. - open func cancel(createResumeData: Bool) { - if createResumeData { - downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } - } else { - downloadDelegate.downloadTask.cancel() - } - - NotificationCenter.default.post( - name: Notification.Name.Task.DidCancel, - object: self, - userInfo: [Notification.Key.Task: task as Any] - ) - } - - // MARK: Progress - - /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. - /// - /// - parameter queue: The dispatch queue to execute the closure on. - /// - parameter closure: The code to be executed periodically as data is read from the server. - /// - /// - returns: The request. - @discardableResult - open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { - downloadDelegate.progressHandler = (closure, queue) - return self - } - - // MARK: Destination - - /// Creates a download file destination closure which uses the default file manager to move the temporary file to a - /// file URL in the first available directory with the specified search path directory and search path domain mask. - /// - /// - parameter directory: The search path directory. `.DocumentDirectory` by default. - /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. - /// - /// - returns: A download file destination closure. - open class func suggestedDownloadDestination( - for directory: FileManager.SearchPathDirectory = .documentDirectory, - in domain: FileManager.SearchPathDomainMask = .userDomainMask) - -> DownloadFileDestination { - return { temporaryURL, response in - let directoryURLs = FileManager.default.urls(for: directory, in: domain) - - if !directoryURLs.isEmpty { - return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) - } - - return (temporaryURL, []) - } - } -} - -// MARK: - - -/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. -open class UploadRequest: DataRequest { - - // MARK: Helper Types - - enum Uploadable: TaskConvertible { - case data(Data, URLRequest) - case file(URL, URLRequest) - case stream(InputStream, URLRequest) - - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - do { - let task: URLSessionTask - - switch self { - case let .data(data, urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.uploadTask(with: urlRequest, from: data) } - case let .file(url, urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } - case let .stream(_, urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } - } - - return task - } catch { - throw AdaptError(error: error) - } - } - } - - // MARK: Properties - - /// The request sent or to be sent to the server. - open override var request: URLRequest? { - if let request = super.request { return request } - - guard let uploadable = originalTask as? Uploadable else { return nil } - - switch uploadable { - case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): - return urlRequest - } - } - - /// The progress of uploading the payload to the server for the upload request. - open var uploadProgress: Progress { return uploadDelegate.uploadProgress } - - var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } - - // MARK: Upload Progress - - /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to - /// the server. - /// - /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress - /// of data being read from the server. - /// - /// - parameter queue: The dispatch queue to execute the closure on. - /// - parameter closure: The code to be executed periodically as data is sent to the server. - /// - /// - returns: The request. - @discardableResult - open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { - uploadDelegate.uploadProgressHandler = (closure, queue) - return self - } -} - -// MARK: - - -#if !os(watchOS) - -/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -open class StreamRequest: Request { - enum Streamable: TaskConvertible { - case stream(hostName: String, port: Int) - case netService(NetService) - - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - let task: URLSessionTask - - switch self { - case let .stream(hostName, port): - task = queue.sync { session.streamTask(withHostName: hostName, port: port) } - case let .netService(netService): - task = queue.sync { session.streamTask(with: netService) } - } - - return task - } - } -} - -#endif diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift deleted file mode 100644 index 88d09e33ff8e..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Response.swift +++ /dev/null @@ -1,563 +0,0 @@ -// -// Response.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Used to store all data associated with an non-serialized response of a data or upload request. -public struct DefaultDataResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The data returned by the server. - public let data: Data? - - /// The error encountered while executing or validating the request. - public let error: Error? - - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline - - var _metrics: AnyObject? - - /// Creates a `DefaultDataResponse` instance from the specified parameters. - /// - /// - Parameters: - /// - request: The URL request sent to the server. - /// - response: The server's response to the URL request. - /// - data: The data returned by the server. - /// - error: The error encountered while executing or validating the request. - /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. - /// - metrics: The task metrics containing the request / response statistics. `nil` by default. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - data: Data?, - error: Error?, - timeline: Timeline = Timeline(), - metrics: AnyObject? = nil) { - self.request = request - self.response = response - self.data = data - self.error = error - self.timeline = timeline - } -} - -// MARK: - - -/// Used to store all data associated with a serialized response of a data or upload request. -public struct DataResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The data returned by the server. - public let data: Data? - - /// The result of response serialization. - public let result: Result - - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline - - /// Returns the associated value of the result if it is a success, `nil` otherwise. - public var value: Value? { return result.value } - - /// Returns the associated error value if the result if it is a failure, `nil` otherwise. - public var error: Error? { return result.error } - - var _metrics: AnyObject? - - /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. - /// - /// - parameter request: The URL request sent to the server. - /// - parameter response: The server's response to the URL request. - /// - parameter data: The data returned by the server. - /// - parameter result: The result of response serialization. - /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. - /// - /// - returns: The new `DataResponse` instance. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - data: Data?, - result: Result, - timeline: Timeline = Timeline()) { - self.request = request - self.response = response - self.data = data - self.result = result - self.timeline = timeline - } -} - -// MARK: - - -extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a - /// success or failure. - public var description: String { - return result.debugDescription - } - - /// The debug textual representation used when written to an output stream, which includes the URL request, the URL - /// response, the server data, the response serialization result and the timeline. - public var debugDescription: String { - var output: [String] = [] - - output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") - output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") - output.append("[Data]: \(data?.count ?? 0) bytes") - output.append("[Result]: \(result.debugDescription)") - output.append("[Timeline]: \(timeline.debugDescription)") - - return output.joined(separator: "\n") - } -} - -// MARK: - - -extension DataResponse { - /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `map` method with a closure that does not throw. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleInt = possibleData.map { $0.count } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's - /// result is a failure, returns a response wrapping the same failure. - public func map(_ transform: (Value) -> T) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.map(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result - /// value as a parameter. - /// - /// Use the `flatMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleObject = possibleData.flatMap { - /// try JSONSerialization.jsonObject(with: $0) - /// } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's - /// result is a failure, returns the same failure. - public func flatMap(_ transform: (Value) throws -> T) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.flatMap(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `mapError` function with a closure that does not throw. For example: - /// - /// let possibleData: DataResponse = ... - /// let withMyError = possibleData.mapError { MyError.error($0) } - /// - /// - Parameter transform: A closure that takes the error of the instance. - /// - Returns: A `DataResponse` instance containing the result of the transform. - public func mapError(_ transform: (Error) -> E) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.mapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `flatMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleObject = possibleData.flatMapError { - /// try someFailableFunction(taking: $0) - /// } - /// - /// - Parameter transform: A throwing closure that takes the error of the instance. - /// - /// - Returns: A `DataResponse` instance containing the result of the transform. - public func flatMapError(_ transform: (Error) throws -> E) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.flatMapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } -} - -// MARK: - - -/// Used to store all data associated with an non-serialized response of a download request. -public struct DefaultDownloadResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The temporary destination URL of the data returned from the server. - public let temporaryURL: URL? - - /// The final destination URL of the data returned from the server if it was moved. - public let destinationURL: URL? - - /// The resume data generated if the request was cancelled. - public let resumeData: Data? - - /// The error encountered while executing or validating the request. - public let error: Error? - - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline - - var _metrics: AnyObject? - - /// Creates a `DefaultDownloadResponse` instance from the specified parameters. - /// - /// - Parameters: - /// - request: The URL request sent to the server. - /// - response: The server's response to the URL request. - /// - temporaryURL: The temporary destination URL of the data returned from the server. - /// - destinationURL: The final destination URL of the data returned from the server if it was moved. - /// - resumeData: The resume data generated if the request was cancelled. - /// - error: The error encountered while executing or validating the request. - /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. - /// - metrics: The task metrics containing the request / response statistics. `nil` by default. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - temporaryURL: URL?, - destinationURL: URL?, - resumeData: Data?, - error: Error?, - timeline: Timeline = Timeline(), - metrics: AnyObject? = nil) { - self.request = request - self.response = response - self.temporaryURL = temporaryURL - self.destinationURL = destinationURL - self.resumeData = resumeData - self.error = error - self.timeline = timeline - } -} - -// MARK: - - -/// Used to store all data associated with a serialized response of a download request. -public struct DownloadResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The temporary destination URL of the data returned from the server. - public let temporaryURL: URL? - - /// The final destination URL of the data returned from the server if it was moved. - public let destinationURL: URL? - - /// The resume data generated if the request was cancelled. - public let resumeData: Data? - - /// The result of response serialization. - public let result: Result - - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline - - /// Returns the associated value of the result if it is a success, `nil` otherwise. - public var value: Value? { return result.value } - - /// Returns the associated error value if the result if it is a failure, `nil` otherwise. - public var error: Error? { return result.error } - - var _metrics: AnyObject? - - /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. - /// - /// - parameter request: The URL request sent to the server. - /// - parameter response: The server's response to the URL request. - /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. - /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. - /// - parameter resumeData: The resume data generated if the request was cancelled. - /// - parameter result: The result of response serialization. - /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. - /// - /// - returns: The new `DownloadResponse` instance. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - temporaryURL: URL?, - destinationURL: URL?, - resumeData: Data?, - result: Result, - timeline: Timeline = Timeline()) { - self.request = request - self.response = response - self.temporaryURL = temporaryURL - self.destinationURL = destinationURL - self.resumeData = resumeData - self.result = result - self.timeline = timeline - } -} - -// MARK: - - -extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a - /// success or failure. - public var description: String { - return result.debugDescription - } - - /// The debug textual representation used when written to an output stream, which includes the URL request, the URL - /// response, the temporary and destination URLs, the resume data, the response serialization result and the - /// timeline. - public var debugDescription: String { - var output: [String] = [] - - output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") - output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") - output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") - output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") - output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") - output.append("[Result]: \(result.debugDescription)") - output.append("[Timeline]: \(timeline.debugDescription)") - - return output.joined(separator: "\n") - } -} - -// MARK: - - -extension DownloadResponse { - /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `map` method with a closure that does not throw. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleInt = possibleData.map { $0.count } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's - /// result is a failure, returns a response wrapping the same failure. - public func map(_ transform: (Value) -> T) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.map(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `flatMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleObject = possibleData.flatMap { - /// try JSONSerialization.jsonObject(with: $0) - /// } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this - /// instance's result is a failure, returns the same failure. - public func flatMap(_ transform: (Value) throws -> T) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.flatMap(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `mapError` function with a closure that does not throw. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let withMyError = possibleData.mapError { MyError.error($0) } - /// - /// - Parameter transform: A closure that takes the error of the instance. - /// - Returns: A `DownloadResponse` instance containing the result of the transform. - public func mapError(_ transform: (Error) -> E) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.mapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `flatMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleObject = possibleData.flatMapError { - /// try someFailableFunction(taking: $0) - /// } - /// - /// - Parameter transform: A throwing closure that takes the error of the instance. - /// - /// - Returns: A `DownloadResponse` instance containing the result of the transform. - public func flatMapError(_ transform: (Error) throws -> E) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.flatMapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } -} - -// MARK: - - -protocol Response { - /// The task metrics containing the request / response statistics. - var _metrics: AnyObject? { get set } - mutating func add(_ metrics: AnyObject?) -} - -extension Response { - mutating func add(_ metrics: AnyObject?) { - #if !os(watchOS) - guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } - guard let metrics = metrics as? URLSessionTaskMetrics else { return } - - _metrics = metrics - #endif - } -} - -// MARK: - - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DefaultDataResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DataResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DefaultDownloadResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DownloadResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift deleted file mode 100644 index b8f5b65b204d..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ResponseSerialization.swift +++ /dev/null @@ -1,697 +0,0 @@ -// -// ResponseSerialization.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// The type in which all data response serializers must conform to in order to serialize a response. -public protocol DataResponseSerializerProtocol { - /// The type of serialized object to be created by this `DataResponseSerializerType`. - associatedtype SerializedObject - - /// A closure used by response handlers that takes a request, response, data and error and returns a result. - var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } -} - -// MARK: - - -/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. -public struct DataResponseSerializer: DataResponseSerializerProtocol { - /// The type of serialized object to be created by this `DataResponseSerializer`. - public typealias SerializedObject = Value - - /// A closure used by response handlers that takes a request, response, data and error and returns a result. - public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result - - /// Initializes the `ResponseSerializer` instance with the given serialize response closure. - /// - /// - parameter serializeResponse: The closure used to serialize the response. - /// - /// - returns: The new generic response serializer instance. - public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { - self.serializeResponse = serializeResponse - } -} - -// MARK: - - -/// The type in which all download response serializers must conform to in order to serialize a response. -public protocol DownloadResponseSerializerProtocol { - /// The type of serialized object to be created by this `DownloadResponseSerializerType`. - associatedtype SerializedObject - - /// A closure used by response handlers that takes a request, response, url and error and returns a result. - var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } -} - -// MARK: - - -/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. -public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { - /// The type of serialized object to be created by this `DownloadResponseSerializer`. - public typealias SerializedObject = Value - - /// A closure used by response handlers that takes a request, response, url and error and returns a result. - public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result - - /// Initializes the `ResponseSerializer` instance with the given serialize response closure. - /// - /// - parameter serializeResponse: The closure used to serialize the response. - /// - /// - returns: The new generic response serializer instance. - public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { - self.serializeResponse = serializeResponse - } -} - -// MARK: - Timeline - -extension Request { - var timeline: Timeline { - let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() - let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() - let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime - - return Timeline( - requestStartTime: requestStartTime, - initialResponseTime: initialResponseTime, - requestCompletedTime: requestCompletedTime, - serializationCompletedTime: CFAbsoluteTimeGetCurrent() - ) - } -} - -// MARK: - Default - -extension DataRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { - delegate.queue.addOperation { - (queue ?? DispatchQueue.main).async { - var dataResponse = DefaultDataResponse( - request: self.request, - response: self.response, - data: self.delegate.data, - error: self.delegate.error, - timeline: self.timeline - ) - - dataResponse.add(self.delegate.metrics) - - completionHandler(dataResponse) - } - } - - return self - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, - /// and data. - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func response( - queue: DispatchQueue? = nil, - responseSerializer: T, - completionHandler: @escaping (DataResponse) -> Void) - -> Self { - delegate.queue.addOperation { - let result = responseSerializer.serializeResponse( - self.request, - self.response, - self.delegate.data, - self.delegate.error - ) - - var dataResponse = DataResponse( - request: self.request, - response: self.response, - data: self.delegate.data, - result: result, - timeline: self.timeline - ) - - dataResponse.add(self.delegate.metrics) - - (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } - } - - return self - } -} - -extension DownloadRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func response( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DefaultDownloadResponse) -> Void) - -> Self { - delegate.queue.addOperation { - (queue ?? DispatchQueue.main).async { - var downloadResponse = DefaultDownloadResponse( - request: self.request, - response: self.response, - temporaryURL: self.downloadDelegate.temporaryURL, - destinationURL: self.downloadDelegate.destinationURL, - resumeData: self.downloadDelegate.resumeData, - error: self.downloadDelegate.error, - timeline: self.timeline - ) - - downloadResponse.add(self.delegate.metrics) - - completionHandler(downloadResponse) - } - } - - return self - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, - /// and data contained in the destination url. - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func response( - queue: DispatchQueue? = nil, - responseSerializer: T, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self { - delegate.queue.addOperation { - let result = responseSerializer.serializeResponse( - self.request, - self.response, - self.downloadDelegate.fileURL, - self.downloadDelegate.error - ) - - var downloadResponse = DownloadResponse( - request: self.request, - response: self.response, - temporaryURL: self.downloadDelegate.temporaryURL, - destinationURL: self.downloadDelegate.destinationURL, - resumeData: self.downloadDelegate.resumeData, - result: result, - timeline: self.timeline - ) - - downloadResponse.add(self.delegate.metrics) - - (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } - } - - return self - } -} - -// MARK: - Data - -extension Request { - /// Returns a result data type that contains the response data as-is. - /// - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. - /// - /// - returns: The result data type. - public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } - - guard let validData = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - return .success(validData) - } -} - -extension DataRequest { - /// Creates a response serializer that returns the associated data as-is. - /// - /// - returns: A data response serializer. - public static func dataResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponseData(response: response, data: data, error: error) - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseData( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DataResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DataRequest.dataResponseSerializer(), - completionHandler: completionHandler - ) - } -} - -extension DownloadRequest { - /// Creates a response serializer that returns the associated data as-is. - /// - /// - returns: A data response serializer. - public static func dataResponseSerializer() -> DownloadResponseSerializer { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } - - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } - - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponseData(response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) - } - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseData( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DownloadRequest.dataResponseSerializer(), - completionHandler: completionHandler - ) - } -} - -// MARK: - String - -extension Request { - /// Returns a result string type initialized from the response data with the specified string encoding. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server - /// response, falling back to the default HTTP default character set, ISO-8859-1. - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. - /// - /// - returns: The result data type. - public static func serializeResponseString( - encoding: String.Encoding?, - response: HTTPURLResponse?, - data: Data?, - error: Error?) - -> Result { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } - - guard let validData = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - var convertedEncoding = encoding - - if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil { - convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( - CFStringConvertIANACharSetNameToEncoding(encodingName)) - ) - } - - let actualEncoding = convertedEncoding ?? .isoLatin1 - - if let string = String(data: validData, encoding: actualEncoding) { - return .success(string) - } else { - return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) - } - } -} - -extension DataRequest { - /// Creates a response serializer that returns a result string type initialized from the response data with - /// the specified string encoding. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server - /// response, falling back to the default HTTP default character set, ISO-8859-1. - /// - /// - returns: A string response serializer. - public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the - /// server response, falling back to the default HTTP default character set, - /// ISO-8859-1. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseString( - queue: DispatchQueue? = nil, - encoding: String.Encoding? = nil, - completionHandler: @escaping (DataResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), - completionHandler: completionHandler - ) - } -} - -extension DownloadRequest { - /// Creates a response serializer that returns a result string type initialized from the response data with - /// the specified string encoding. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server - /// response, falling back to the default HTTP default character set, ISO-8859-1. - /// - /// - returns: A string response serializer. - public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } - - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } - - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) - } - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the - /// server response, falling back to the default HTTP default character set, - /// ISO-8859-1. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseString( - queue: DispatchQueue? = nil, - encoding: String.Encoding? = nil, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), - completionHandler: completionHandler - ) - } -} - -// MARK: - JSON - -extension Request { - /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` - /// with the specified reading options. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. - /// - /// - returns: The result data type. - public static func serializeResponseJSON( - options: JSONSerialization.ReadingOptions, - response: HTTPURLResponse?, - data: Data?, - error: Error?) - -> Result { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } - - guard let validData = data, validData.count > 0 else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) - } - - do { - let json = try JSONSerialization.jsonObject(with: validData, options: options) - return .success(json) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) - } - } -} - -extension DataRequest { - /// Creates a response serializer that returns a JSON object result type constructed from the response data using - /// `JSONSerialization` with the specified reading options. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - /// - returns: A JSON object response serializer. - public static func jsonResponseSerializer( - options: JSONSerialization.ReadingOptions = .allowFragments) - -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseJSON( - queue: DispatchQueue? = nil, - options: JSONSerialization.ReadingOptions = .allowFragments, - completionHandler: @escaping (DataResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DataRequest.jsonResponseSerializer(options: options), - completionHandler: completionHandler - ) - } -} - -extension DownloadRequest { - /// Creates a response serializer that returns a JSON object result type constructed from the response data using - /// `JSONSerialization` with the specified reading options. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - /// - returns: A JSON object response serializer. - public static func jsonResponseSerializer( - options: JSONSerialization.ReadingOptions = .allowFragments) - -> DownloadResponseSerializer { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } - - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } - - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) - } - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseJSON( - queue: DispatchQueue? = nil, - options: JSONSerialization.ReadingOptions = .allowFragments, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), - completionHandler: completionHandler - ) - } -} - -// MARK: - Property List - -extension Request { - /// Returns a plist object contained in a result type constructed from the response data using - /// `PropertyListSerialization` with the specified reading options. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. - /// - /// - returns: The result data type. - public static func serializeResponsePropertyList( - options: PropertyListSerialization.ReadOptions, - response: HTTPURLResponse?, - data: Data?, - error: Error?) - -> Result { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } - - guard let validData = data, validData.count > 0 else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) - } - - do { - let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) - return .success(plist) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) - } - } -} - -extension DataRequest { - /// Creates a response serializer that returns an object constructed from the response data using - /// `PropertyListSerialization` with the specified reading options. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - /// - returns: A property list object response serializer. - public static func propertyListResponseSerializer( - options: PropertyListSerialization.ReadOptions = []) - -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responsePropertyList( - queue: DispatchQueue? = nil, - options: PropertyListSerialization.ReadOptions = [], - completionHandler: @escaping (DataResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DataRequest.propertyListResponseSerializer(options: options), - completionHandler: completionHandler - ) - } -} - -extension DownloadRequest { - /// Creates a response serializer that returns an object constructed from the response data using - /// `PropertyListSerialization` with the specified reading options. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - /// - returns: A property list object response serializer. - public static func propertyListResponseSerializer( - options: PropertyListSerialization.ReadOptions = []) - -> DownloadResponseSerializer { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } - - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } - - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) - } - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responsePropertyList( - queue: DispatchQueue? = nil, - options: PropertyListSerialization.ReadOptions = [], - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), - completionHandler: completionHandler - ) - } -} - -/// A set of HTTP response status code that do not contain response data. -private let emptyDataStatusCodes: Set = [204, 205] diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift deleted file mode 100644 index ad4d5632a019..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/ServerTrustPolicy.swift +++ /dev/null @@ -1,306 +0,0 @@ -// -// ServerTrustPolicy.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. -open class ServerTrustPolicyManager { - /// The dictionary of policies mapped to a particular host. - public let policies: [String: ServerTrustPolicy] - - /// Initializes the `ServerTrustPolicyManager` instance with the given policies. - /// - /// Since different servers and web services can have different leaf certificates, intermediate and even root - /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This - /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key - /// pinning for host3 and disabling evaluation for host4. - /// - /// - parameter policies: A dictionary of all policies mapped to a particular host. - /// - /// - returns: The new `ServerTrustPolicyManager` instance. - public init(policies: [String: ServerTrustPolicy]) { - self.policies = policies - } - - /// Returns the `ServerTrustPolicy` for the given host if applicable. - /// - /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override - /// this method and implement more complex mapping implementations such as wildcards. - /// - /// - parameter host: The host to use when searching for a matching policy. - /// - /// - returns: The server trust policy for the given host if found. - open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { - return policies[host] - } -} - -// MARK: - - -extension URLSession { - private struct AssociatedKeys { - static var managerKey = "URLSession.ServerTrustPolicyManager" - } - - var serverTrustPolicyManager: ServerTrustPolicyManager? { - get { - return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager - } - set (manager) { - objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - } -} - -// MARK: - ServerTrustPolicy - -/// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when -/// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust -/// with a given set of criteria to determine whether the server trust is valid and the connection should be made. -/// -/// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other -/// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged -/// to route all communication over an HTTPS connection with pinning enabled. -/// -/// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to -/// validate the host provided by the challenge. Applications are encouraged to always -/// validate the host in production environments to guarantee the validity of the server's -/// certificate chain. -/// -/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to -/// validate the host provided by the challenge as well as specify the revocation flags for -/// testing for revoked certificates. Apple platforms did not start testing for revoked -/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is -/// demonstrated in our TLS tests. Applications are encouraged to always validate the host -/// in production environments to guarantee the validity of the server's certificate chain. -/// -/// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is -/// considered valid if one of the pinned certificates match one of the server certificates. -/// By validating both the certificate chain and host, certificate pinning provides a very -/// secure form of server trust validation mitigating most, if not all, MITM attacks. -/// Applications are encouraged to always validate the host and require a valid certificate -/// chain in production environments. -/// -/// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered -/// valid if one of the pinned public keys match one of the server certificate public keys. -/// By validating both the certificate chain and host, public key pinning provides a very -/// secure form of server trust validation mitigating most, if not all, MITM attacks. -/// Applications are encouraged to always validate the host and require a valid certificate -/// chain in production environments. -/// -/// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. -/// -/// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. -public enum ServerTrustPolicy { - case performDefaultEvaluation(validateHost: Bool) - case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) - case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) - case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) - case disableEvaluation - case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) - - // MARK: - Bundle Location - - /// Returns all certificates within the given bundle with a `.cer` file extension. - /// - /// - parameter bundle: The bundle to search for all `.cer` files. - /// - /// - returns: All certificates within the given bundle. - public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { - var certificates: [SecCertificate] = [] - - let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in - bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) - }.joined()) - - for path in paths { - if - let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, - let certificate = SecCertificateCreateWithData(nil, certificateData) - { - certificates.append(certificate) - } - } - - return certificates - } - - /// Returns all public keys within the given bundle with a `.cer` file extension. - /// - /// - parameter bundle: The bundle to search for all `*.cer` files. - /// - /// - returns: All public keys within the given bundle. - public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { - var publicKeys: [SecKey] = [] - - for certificate in certificates(in: bundle) { - if let publicKey = publicKey(for: certificate) { - publicKeys.append(publicKey) - } - } - - return publicKeys - } - - // MARK: - Evaluation - - /// Evaluates whether the server trust is valid for the given host. - /// - /// - parameter serverTrust: The server trust to evaluate. - /// - parameter host: The host of the challenge protection space. - /// - /// - returns: Whether the server trust is valid. - public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { - var serverTrustIsValid = false - - switch self { - case let .performDefaultEvaluation(validateHost): - let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, policy) - - serverTrustIsValid = trustIsValid(serverTrust) - case let .performRevokedEvaluation(validateHost, revocationFlags): - let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) - SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) - - serverTrustIsValid = trustIsValid(serverTrust) - case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): - if validateCertificateChain { - let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, policy) - - SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) - SecTrustSetAnchorCertificatesOnly(serverTrust, true) - - serverTrustIsValid = trustIsValid(serverTrust) - } else { - let serverCertificatesDataArray = certificateData(for: serverTrust) - let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) - - outerLoop: for serverCertificateData in serverCertificatesDataArray { - for pinnedCertificateData in pinnedCertificatesDataArray { - if serverCertificateData == pinnedCertificateData { - serverTrustIsValid = true - break outerLoop - } - } - } - } - case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): - var certificateChainEvaluationPassed = true - - if validateCertificateChain { - let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, policy) - - certificateChainEvaluationPassed = trustIsValid(serverTrust) - } - - if certificateChainEvaluationPassed { - outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { - for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { - if serverPublicKey.isEqual(pinnedPublicKey) { - serverTrustIsValid = true - break outerLoop - } - } - } - } - case .disableEvaluation: - serverTrustIsValid = true - case let .customEvaluation(closure): - serverTrustIsValid = closure(serverTrust, host) - } - - return serverTrustIsValid - } - - // MARK: - Private - Trust Validation - - private func trustIsValid(_ trust: SecTrust) -> Bool { - var isValid = false - - var result = SecTrustResultType.invalid - let status = SecTrustEvaluate(trust, &result) - - if status == errSecSuccess { - let unspecified = SecTrustResultType.unspecified - let proceed = SecTrustResultType.proceed - - isValid = result == unspecified || result == proceed - } - - return isValid - } - - // MARK: - Private - Certificate Data - - private func certificateData(for trust: SecTrust) -> [Data] { - var certificates: [SecCertificate] = [] - - for index in 0.. [Data] { - return certificates.map { SecCertificateCopyData($0) as Data } - } - - // MARK: - Private - Public Key Extraction - - private static func publicKeys(for trust: SecTrust) -> [SecKey] { - var publicKeys: [SecKey] = [] - - for index in 0.. SecKey? { - var publicKey: SecKey? - - let policy = SecPolicyCreateBasicX509() - var trust: SecTrust? - let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) - - if let trust = trust, trustCreationStatus == errSecSuccess { - publicKey = SecTrustCopyPublicKey(trust) - } - - return publicKey - } -} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift deleted file mode 100644 index 5cf4a385b2a5..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionDelegate.swift +++ /dev/null @@ -1,713 +0,0 @@ -// -// SessionDelegate.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Responsible for handling all delegate callbacks for the underlying session. -open class SessionDelegate: NSObject { - - // MARK: URLSessionDelegate Overrides - - /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. - open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? - - /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. - open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? - - /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. - open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. - open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? - - // MARK: URLSessionTaskDelegate Overrides - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. - open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? - - /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and - /// requires the caller to call the `completionHandler`. - open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. - open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? - - /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and - /// requires the caller to call the `completionHandler`. - open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. - open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? - - /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and - /// requires the caller to call the `completionHandler`. - open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. - open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. - open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? - - // MARK: URLSessionDataDelegate Overrides - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. - open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? - - /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and - /// requires caller to call the `completionHandler`. - open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. - open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. - open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. - open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? - - /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and - /// requires caller to call the `completionHandler`. - open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)? - - // MARK: URLSessionDownloadDelegate Overrides - - /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. - open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? - - /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. - open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? - - /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. - open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? - - // MARK: URLSessionStreamDelegate Overrides - -#if !os(watchOS) - - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { - get { - return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void - } - set { - _streamTaskReadClosed = newValue - } - } - - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { - get { - return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void - } - set { - _streamTaskWriteClosed = newValue - } - } - - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { - get { - return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void - } - set { - _streamTaskBetterRouteDiscovered = newValue - } - } - - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { - get { - return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void - } - set { - _streamTaskDidBecomeInputStream = newValue - } - } - - var _streamTaskReadClosed: Any? - var _streamTaskWriteClosed: Any? - var _streamTaskBetterRouteDiscovered: Any? - var _streamTaskDidBecomeInputStream: Any? - -#endif - - // MARK: Properties - - var retrier: RequestRetrier? - weak var sessionManager: SessionManager? - - var requests: [Int: Request] = [:] - private let lock = NSLock() - - /// Access the task delegate for the specified task in a thread-safe manner. - open subscript(task: URLSessionTask) -> Request? { - get { - lock.lock() ; defer { lock.unlock() } - return requests[task.taskIdentifier] - } - set { - lock.lock() ; defer { lock.unlock() } - requests[task.taskIdentifier] = newValue - } - } - - // MARK: Lifecycle - - /// Initializes the `SessionDelegate` instance. - /// - /// - returns: The new `SessionDelegate` instance. - public override init() { - super.init() - } - - // MARK: NSObject Overrides - - /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond - /// to a specified message. - /// - /// - parameter selector: A selector that identifies a message. - /// - /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. - open override func responds(to selector: Selector) -> Bool { - #if !os(macOS) - if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { - return sessionDidFinishEventsForBackgroundURLSession != nil - } - #endif - - #if !os(watchOS) - if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { - switch selector { - case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): - return streamTaskReadClosed != nil - case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): - return streamTaskWriteClosed != nil - case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): - return streamTaskBetterRouteDiscovered != nil - case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): - return streamTaskDidBecomeInputAndOutputStreams != nil - default: - break - } - } - #endif - - switch selector { - case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): - return sessionDidBecomeInvalidWithError != nil - case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): - return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) - case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): - return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) - case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): - return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) - default: - return type(of: self).instancesRespond(to: selector) - } - } -} - -// MARK: - URLSessionDelegate - -extension SessionDelegate: URLSessionDelegate { - /// Tells the delegate that the session has been invalidated. - /// - /// - parameter session: The session object that was invalidated. - /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. - open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { - sessionDidBecomeInvalidWithError?(session, error) - } - - /// Requests credentials from the delegate in response to a session-level authentication request from the - /// remote server. - /// - /// - parameter session: The session containing the task that requested authentication. - /// - parameter challenge: An object that contains the request for authentication. - /// - parameter completionHandler: A handler that your delegate method must call providing the disposition - /// and credential. - open func urlSession( - _ session: URLSession, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { - guard sessionDidReceiveChallengeWithCompletion == nil else { - sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) - return - } - - var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling - var credential: URLCredential? - - if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { - (disposition, credential) = sessionDidReceiveChallenge(session, challenge) - } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { - let host = challenge.protectionSpace.host - - if - let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), - let serverTrust = challenge.protectionSpace.serverTrust - { - if serverTrustPolicy.evaluate(serverTrust, forHost: host) { - disposition = .useCredential - credential = URLCredential(trust: serverTrust) - } else { - disposition = .cancelAuthenticationChallenge - } - } - } - - completionHandler(disposition, credential) - } - -#if !os(macOS) - - /// Tells the delegate that all messages enqueued for a session have been delivered. - /// - /// - parameter session: The session that no longer has any outstanding requests. - open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { - sessionDidFinishEventsForBackgroundURLSession?(session) - } - -#endif -} - -// MARK: - URLSessionTaskDelegate - -extension SessionDelegate: URLSessionTaskDelegate { - /// Tells the delegate that the remote server requested an HTTP redirect. - /// - /// - parameter session: The session containing the task whose request resulted in a redirect. - /// - parameter task: The task whose request resulted in a redirect. - /// - parameter response: An object containing the server’s response to the original request. - /// - parameter request: A URL request object filled out with the new location. - /// - parameter completionHandler: A closure that your handler should call with either the value of the request - /// parameter, a modified URL request object, or NULL to refuse the redirect and - /// return the body of the redirect response. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest, - completionHandler: @escaping (URLRequest?) -> Void) { - guard taskWillPerformHTTPRedirectionWithCompletion == nil else { - taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) - return - } - - var redirectRequest: URLRequest? = request - - if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { - redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) - } - - completionHandler(redirectRequest) - } - - /// Requests credentials from the delegate in response to an authentication request from the remote server. - /// - /// - parameter session: The session containing the task whose request requires authentication. - /// - parameter task: The task whose request requires authentication. - /// - parameter challenge: An object that contains the request for authentication. - /// - parameter completionHandler: A handler that your delegate method must call providing the disposition - /// and credential. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { - guard taskDidReceiveChallengeWithCompletion == nil else { - taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) - return - } - - if let taskDidReceiveChallenge = taskDidReceiveChallenge { - let result = taskDidReceiveChallenge(session, task, challenge) - completionHandler(result.0, result.1) - } else if let delegate = self[task]?.delegate { - delegate.urlSession( - session, - task: task, - didReceive: challenge, - completionHandler: completionHandler - ) - } else { - urlSession(session, didReceive: challenge, completionHandler: completionHandler) - } - } - - /// Tells the delegate when a task requires a new request body stream to send to the remote server. - /// - /// - parameter session: The session containing the task that needs a new body stream. - /// - parameter task: The task that needs a new body stream. - /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { - guard taskNeedNewBodyStreamWithCompletion == nil else { - taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) - return - } - - if let taskNeedNewBodyStream = taskNeedNewBodyStream { - completionHandler(taskNeedNewBodyStream(session, task)) - } else if let delegate = self[task]?.delegate { - delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) - } - } - - /// Periodically informs the delegate of the progress of sending body content to the server. - /// - /// - parameter session: The session containing the data task. - /// - parameter task: The data task. - /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. - /// - parameter totalBytesSent: The total number of bytes sent so far. - /// - parameter totalBytesExpectedToSend: The expected length of the body data. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) { - if let taskDidSendBodyData = taskDidSendBodyData { - taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) - } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { - delegate.URLSession( - session, - task: task, - didSendBodyData: bytesSent, - totalBytesSent: totalBytesSent, - totalBytesExpectedToSend: totalBytesExpectedToSend - ) - } - } - -#if !os(watchOS) - - /// Tells the delegate that the session finished collecting metrics for the task. - /// - /// - parameter session: The session collecting the metrics. - /// - parameter task: The task whose metrics have been collected. - /// - parameter metrics: The collected metrics. - @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) - @objc(URLSession:task:didFinishCollectingMetrics:) - open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { - self[task]?.delegate.metrics = metrics - } - -#endif - - /// Tells the delegate that the task finished transferring data. - /// - /// - parameter session: The session containing the task whose request finished transferring data. - /// - parameter task: The task whose request finished transferring data. - /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. - open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - /// Executed after it is determined that the request is not going to be retried - let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in - guard let strongSelf = self else { return } - - strongSelf.taskDidComplete?(session, task, error) - - strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) - - var userInfo: [String: Any] = [Notification.Key.Task: task] - - if let data = (strongSelf[task]?.delegate as? DataTaskDelegate)?.data { - userInfo[Notification.Key.ResponseData] = data - } - - NotificationCenter.default.post( - name: Notification.Name.Task.DidComplete, - object: strongSelf, - userInfo: userInfo - ) - - strongSelf[task] = nil - } - - guard let request = self[task], let sessionManager = sessionManager else { - completeTask(session, task, error) - return - } - - // Run all validations on the request before checking if an error occurred - request.validations.forEach { $0() } - - // Determine whether an error has occurred - var error: Error? = error - - if request.delegate.error != nil { - error = request.delegate.error - } - - /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request - /// should be retried. Otherwise, complete the task by notifying the task delegate. - if let retrier = retrier, let error = error { - retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in - guard shouldRetry else { completeTask(session, task, error) ; return } - - DispatchQueue.utility.after(timeDelay) { [weak self] in - guard let strongSelf = self else { return } - - let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false - - if retrySucceeded, let task = request.task { - strongSelf[task] = request - return - } else { - completeTask(session, task, error) - } - } - } - } else { - completeTask(session, task, error) - } - } -} - -// MARK: - URLSessionDataDelegate - -extension SessionDelegate: URLSessionDataDelegate { - /// Tells the delegate that the data task received the initial reply (headers) from the server. - /// - /// - parameter session: The session containing the data task that received an initial reply. - /// - parameter dataTask: The data task that received an initial reply. - /// - parameter response: A URL response object populated with headers. - /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a - /// constant to indicate whether the transfer should continue as a data task or - /// should become a download task. - open func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didReceive response: URLResponse, - completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { - guard dataTaskDidReceiveResponseWithCompletion == nil else { - dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) - return - } - - var disposition: URLSession.ResponseDisposition = .allow - - if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { - disposition = dataTaskDidReceiveResponse(session, dataTask, response) - } - - completionHandler(disposition) - } - - /// Tells the delegate that the data task was changed to a download task. - /// - /// - parameter session: The session containing the task that was replaced by a download task. - /// - parameter dataTask: The data task that was replaced by a download task. - /// - parameter downloadTask: The new download task that replaced the data task. - open func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didBecome downloadTask: URLSessionDownloadTask) { - if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { - dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) - } else { - self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) - } - } - - /// Tells the delegate that the data task has received some of the expected data. - /// - /// - parameter session: The session containing the data task that provided data. - /// - parameter dataTask: The data task that provided data. - /// - parameter data: A data object containing the transferred data. - open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - if let dataTaskDidReceiveData = dataTaskDidReceiveData { - dataTaskDidReceiveData(session, dataTask, data) - } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { - delegate.urlSession(session, dataTask: dataTask, didReceive: data) - } - } - - /// Asks the delegate whether the data (or upload) task should store the response in the cache. - /// - /// - parameter session: The session containing the data (or upload) task. - /// - parameter dataTask: The data (or upload) task. - /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current - /// caching policy and the values of certain received headers, such as the Pragma - /// and Cache-Control headers. - /// - parameter completionHandler: A block that your handler must call, providing either the original proposed - /// response, a modified version of that response, or NULL to prevent caching the - /// response. If your delegate implements this method, it must call this completion - /// handler; otherwise, your app leaks memory. - open func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse, - completionHandler: @escaping (CachedURLResponse?) -> Void) { - guard dataTaskWillCacheResponseWithCompletion == nil else { - dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) - return - } - - if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { - completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) - } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { - delegate.urlSession( - session, - dataTask: dataTask, - willCacheResponse: proposedResponse, - completionHandler: completionHandler - ) - } else { - completionHandler(proposedResponse) - } - } -} - -// MARK: - URLSessionDownloadDelegate - -extension SessionDelegate: URLSessionDownloadDelegate { - /// Tells the delegate that a download task has finished downloading. - /// - /// - parameter session: The session containing the download task that finished. - /// - parameter downloadTask: The download task that finished. - /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either - /// open the file for reading or move it to a permanent location in your app’s sandbox - /// container directory before returning from this delegate method. - open func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) { - if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { - downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) - } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { - delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) - } - } - - /// Periodically informs the delegate about the download’s progress. - /// - /// - parameter session: The session containing the download task. - /// - parameter downloadTask: The download task. - /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate - /// method was called. - /// - parameter totalBytesWritten: The total number of bytes transferred so far. - /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length - /// header. If this header was not provided, the value is - /// `NSURLSessionTransferSizeUnknown`. - open func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) { - if let downloadTaskDidWriteData = downloadTaskDidWriteData { - downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) - } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { - delegate.urlSession( - session, - downloadTask: downloadTask, - didWriteData: bytesWritten, - totalBytesWritten: totalBytesWritten, - totalBytesExpectedToWrite: totalBytesExpectedToWrite - ) - } - } - - /// Tells the delegate that the download task has resumed downloading. - /// - /// - parameter session: The session containing the download task that finished. - /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. - /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the - /// existing content, then this value is zero. Otherwise, this value is an - /// integer representing the number of bytes on disk that do not need to be - /// retrieved again. - /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. - /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. - open func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) { - if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { - downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) - } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { - delegate.urlSession( - session, - downloadTask: downloadTask, - didResumeAtOffset: fileOffset, - expectedTotalBytes: expectedTotalBytes - ) - } - } -} - -// MARK: - URLSessionStreamDelegate - -#if !os(watchOS) - -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -extension SessionDelegate: URLSessionStreamDelegate { - /// Tells the delegate that the read side of the connection has been closed. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { - streamTaskReadClosed?(session, streamTask) - } - - /// Tells the delegate that the write side of the connection has been closed. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { - streamTaskWriteClosed?(session, streamTask) - } - - /// Tells the delegate that the system has determined that a better route to the host is available. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { - streamTaskBetterRouteDiscovered?(session, streamTask) - } - - /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - /// - parameter inputStream: The new input stream. - /// - parameter outputStream: The new output stream. - open func urlSession( - _ session: URLSession, - streamTask: URLSessionStreamTask, - didBecome inputStream: InputStream, - outputStream: OutputStream) { - streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) - } -} - -#endif diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift deleted file mode 100644 index 19725f287e0c..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/SessionManager.swift +++ /dev/null @@ -1,886 +0,0 @@ -// -// SessionManager.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. -open class SessionManager { - - // MARK: - Helper Types - - /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as - /// associated values. - /// - /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with - /// streaming information. - /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding - /// error. - public enum MultipartFormDataEncodingResult { - case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) - case failure(Error) - } - - // MARK: - Properties - - /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use - /// directly for any ad hoc requests. - public static let `default`: SessionManager = { - let configuration = URLSessionConfiguration.default - configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders - - return SessionManager(configuration: configuration) - }() - - /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. - public static let defaultHTTPHeaders: HTTPHeaders = { - // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 - let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" - - // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 - let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in - let quality = 1.0 - (Double(index) * 0.1) - return "\(languageCode);q=\(quality)" - }.joined(separator: ", ") - - // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 - // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` - let userAgent: String = { - if let info = Bundle.main.infoDictionary { - let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" - let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" - let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" - let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" - - let osNameVersion: String = { - let version = ProcessInfo.processInfo.operatingSystemVersion - let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" - - let osName: String = { - #if os(iOS) - return "iOS" - #elseif os(watchOS) - return "watchOS" - #elseif os(tvOS) - return "tvOS" - #elseif os(macOS) - return "OS X" - #elseif os(Linux) - return "Linux" - #else - return "Unknown" - #endif - }() - - return "\(osName) \(versionString)" - }() - - let alamofireVersion: String = { - guard - let afInfo = Bundle(for: SessionManager.self).infoDictionary, - let build = afInfo["CFBundleShortVersionString"] - else { return "Unknown" } - - return "Alamofire/\(build)" - }() - - return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" - } - - return "Alamofire" - }() - - return [ - "Accept-Encoding": acceptEncoding, - "Accept-Language": acceptLanguage, - "User-Agent": userAgent - ] - }() - - /// Default memory threshold used when encoding `MultipartFormData` in bytes. - public static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 - - /// The underlying session. - public let session: URLSession - - /// The session delegate handling all the task and session delegate callbacks. - public let delegate: SessionDelegate - - /// Whether to start requests immediately after being constructed. `true` by default. - open var startRequestsImmediately: Bool = true - - /// The request adapter called each time a new request is created. - open var adapter: RequestAdapter? - - /// The request retrier called each time a request encounters an error to determine whether to retry the request. - open var retrier: RequestRetrier? { - get { return delegate.retrier } - set { delegate.retrier = newValue } - } - - /// The background completion handler closure provided by the UIApplicationDelegate - /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background - /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation - /// will automatically call the handler. - /// - /// If you need to handle your own events before the handler is called, then you need to override the - /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. - /// - /// `nil` by default. - open var backgroundCompletionHandler: (() -> Void)? - - let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) - - // MARK: - Lifecycle - - /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. - /// - /// - parameter configuration: The configuration used to construct the managed session. - /// `URLSessionConfiguration.default` by default. - /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by - /// default. - /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust - /// challenges. `nil` by default. - /// - /// - returns: The new `SessionManager` instance. - public init( - configuration: URLSessionConfiguration = URLSessionConfiguration.default, - delegate: SessionDelegate = SessionDelegate(), - serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { - self.delegate = delegate - self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) - - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) - } - - /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. - /// - /// - parameter session: The URL session. - /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. - /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust - /// challenges. `nil` by default. - /// - /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. - public init?( - session: URLSession, - delegate: SessionDelegate, - serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { - guard delegate === session.delegate else { return nil } - - self.delegate = delegate - self.session = session - - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) - } - - private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { - session.serverTrustPolicyManager = serverTrustPolicyManager - - delegate.sessionManager = self - - delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in - guard let strongSelf = self else { return } - DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } - } - } - - deinit { - session.invalidateAndCancel() - } - - // MARK: - Data Request - - /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` - /// and `headers`. - /// - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.get` by default. - /// - parameter parameters: The parameters. `nil` by default. - /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `DataRequest`. - @discardableResult - open func request( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil) - -> DataRequest { - var originalRequest: URLRequest? - - do { - originalRequest = try URLRequest(url: url, method: method, headers: headers) - let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) - return request(encodedURLRequest) - } catch { - return request(originalRequest, failedWith: error) - } - } - - /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `DataRequest`. - @discardableResult - open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { - var originalRequest: URLRequest? - - do { - originalRequest = try urlRequest.asURLRequest() - let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) - - let task = try originalTask.task(session: session, adapter: adapter, queue: queue) - let request = DataRequest(session: session, requestTask: .data(originalTask, task)) - - delegate[task] = request - - if startRequestsImmediately { request.resume() } - - return request - } catch { - return request(originalRequest, failedWith: error) - } - } - - // MARK: Private - Request Implementation - - private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { - var requestTask: Request.RequestTask = .data(nil, nil) - - if let urlRequest = urlRequest { - let originalTask = DataRequest.Requestable(urlRequest: urlRequest) - requestTask = .data(originalTask, nil) - } - - let underlyingError = error.underlyingAdaptError ?? error - let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) - - if let retrier = retrier, error is AdaptError { - allowRetrier(retrier, toRetry: request, with: underlyingError) - } else { - if startRequestsImmediately { request.resume() } - } - - return request - } - - // MARK: - Download Request - - // MARK: URL Request - - /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, - /// `headers` and save them to the `destination`. - /// - /// If `destination` is not specified, the contents will remain in the temporary location determined by the - /// underlying URL session. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.get` by default. - /// - parameter parameters: The parameters. `nil` by default. - /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. - /// - /// - returns: The created `DownloadRequest`. - @discardableResult - open func download( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) - return download(encodedURLRequest, to: destination) - } catch { - return download(nil, to: destination, failedWith: error) - } - } - - /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save - /// them to the `destination`. - /// - /// If `destination` is not specified, the contents will remain in the temporary location determined by the - /// underlying URL session. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter urlRequest: The URL request - /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. - /// - /// - returns: The created `DownloadRequest`. - @discardableResult - open func download( - _ urlRequest: URLRequestConvertible, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - do { - let urlRequest = try urlRequest.asURLRequest() - return download(.request(urlRequest), to: destination) - } catch { - return download(nil, to: destination, failedWith: error) - } - } - - // MARK: Resume Data - - /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve - /// the contents of the original request and save them to the `destination`. - /// - /// If `destination` is not specified, the contents will remain in the temporary location determined by the - /// underlying URL session. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken - /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the - /// data is written incorrectly and will always fail to resume the download. For more information about the bug and - /// possible workarounds, please refer to the following Stack Overflow post: - /// - /// - http://stackoverflow.com/a/39347461/1342462 - /// - /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` - /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for - /// additional information. - /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. - /// - /// - returns: The created `DownloadRequest`. - @discardableResult - open func download( - resumingWith resumeData: Data, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - return download(.resumeData(resumeData), to: destination) - } - - // MARK: Private - Download Implementation - - private func download( - _ downloadable: DownloadRequest.Downloadable, - to destination: DownloadRequest.DownloadFileDestination?) - -> DownloadRequest { - do { - let task = try downloadable.task(session: session, adapter: adapter, queue: queue) - let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) - - download.downloadDelegate.destination = destination - - delegate[task] = download - - if startRequestsImmediately { download.resume() } - - return download - } catch { - return download(downloadable, to: destination, failedWith: error) - } - } - - private func download( - _ downloadable: DownloadRequest.Downloadable?, - to destination: DownloadRequest.DownloadFileDestination?, - failedWith error: Error) - -> DownloadRequest { - var downloadTask: Request.RequestTask = .download(nil, nil) - - if let downloadable = downloadable { - downloadTask = .download(downloadable, nil) - } - - let underlyingError = error.underlyingAdaptError ?? error - - let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) - download.downloadDelegate.destination = destination - - if let retrier = retrier, error is AdaptError { - allowRetrier(retrier, toRetry: download, with: underlyingError) - } else { - if startRequestsImmediately { download.resume() } - } - - return download - } - - // MARK: - Upload Request - - // MARK: File - - /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter file: The file to upload. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload( - _ fileURL: URL, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - return upload(fileURL, with: urlRequest) - } catch { - return upload(nil, failedWith: error) - } - } - - /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter file: The file to upload. - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { - do { - let urlRequest = try urlRequest.asURLRequest() - return upload(.file(fileURL, urlRequest)) - } catch { - return upload(nil, failedWith: error) - } - } - - // MARK: Data - - /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter data: The data to upload. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload( - _ data: Data, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - return upload(data, with: urlRequest) - } catch { - return upload(nil, failedWith: error) - } - } - - /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter data: The data to upload. - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { - do { - let urlRequest = try urlRequest.asURLRequest() - return upload(.data(data, urlRequest)) - } catch { - return upload(nil, failedWith: error) - } - } - - // MARK: InputStream - - /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter stream: The stream to upload. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload( - _ stream: InputStream, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - return upload(stream, with: urlRequest) - } catch { - return upload(nil, failedWith: error) - } - } - - /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter stream: The stream to upload. - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { - do { - let urlRequest = try urlRequest.asURLRequest() - return upload(.stream(stream, urlRequest)) - } catch { - return upload(nil, failedWith: error) - } - } - - // MARK: MultipartFormData - - /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new - /// `UploadRequest` using the `url`, `method` and `headers`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. - /// `multipartFormDataEncodingMemoryThreshold` by default. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. - open func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - queue: DispatchQueue? = nil, - encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - - return upload( - multipartFormData: multipartFormData, - usingThreshold: encodingMemoryThreshold, - with: urlRequest, - queue: queue, - encodingCompletion: encodingCompletion - ) - } catch { - (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } - } - } - - /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new - /// `UploadRequest` using the `urlRequest`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. - /// `multipartFormDataEncodingMemoryThreshold` by default. - /// - parameter urlRequest: The URL request. - /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. - open func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - with urlRequest: URLRequestConvertible, - queue: DispatchQueue? = nil, - encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { - DispatchQueue.global(qos: .utility).async { - let formData = MultipartFormData() - multipartFormData(formData) - - var tempFileURL: URL? - - do { - var urlRequestWithContentType = try urlRequest.asURLRequest() - urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") - - let isBackgroundSession = self.session.configuration.identifier != nil - - if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { - let data = try formData.encode() - - let encodingResult = MultipartFormDataEncodingResult.success( - request: self.upload(data, with: urlRequestWithContentType), - streamingFromDisk: false, - streamFileURL: nil - ) - - (queue ?? DispatchQueue.main).async { encodingCompletion?(encodingResult) } - } else { - let fileManager = FileManager.default - let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) - let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") - let fileName = UUID().uuidString - let fileURL = directoryURL.appendingPathComponent(fileName) - - tempFileURL = fileURL - - var directoryError: Error? - - // Create directory inside serial queue to ensure two threads don't do this in parallel - self.queue.sync { - do { - try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) - } catch { - directoryError = error - } - } - - if let directoryError = directoryError { throw directoryError } - - try formData.writeEncodedData(to: fileURL) - - let upload = self.upload(fileURL, with: urlRequestWithContentType) - - // Cleanup the temp file once the upload is complete - upload.delegate.queue.addOperation { - do { - try FileManager.default.removeItem(at: fileURL) - } catch { - // No-op - } - } - - (queue ?? DispatchQueue.main).async { - let encodingResult = MultipartFormDataEncodingResult.success( - request: upload, - streamingFromDisk: true, - streamFileURL: fileURL - ) - - encodingCompletion?(encodingResult) - } - } - } catch { - // Cleanup the temp file in the event that the multipart form data encoding failed - if let tempFileURL = tempFileURL { - do { - try FileManager.default.removeItem(at: tempFileURL) - } catch { - // No-op - } - } - - (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } - } - } - } - - // MARK: Private - Upload Implementation - - private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { - do { - let task = try uploadable.task(session: session, adapter: adapter, queue: queue) - let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) - - if case let .stream(inputStream, _) = uploadable { - upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } - } - - delegate[task] = upload - - if startRequestsImmediately { upload.resume() } - - return upload - } catch { - return upload(uploadable, failedWith: error) - } - } - - private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { - var uploadTask: Request.RequestTask = .upload(nil, nil) - - if let uploadable = uploadable { - uploadTask = .upload(uploadable, nil) - } - - let underlyingError = error.underlyingAdaptError ?? error - let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) - - if let retrier = retrier, error is AdaptError { - allowRetrier(retrier, toRetry: upload, with: underlyingError) - } else { - if startRequestsImmediately { upload.resume() } - } - - return upload - } - -#if !os(watchOS) - - // MARK: - Stream Request - - // MARK: Hostname and Port - - /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter hostName: The hostname of the server to connect to. - /// - parameter port: The port of the server to connect to. - /// - /// - returns: The created `StreamRequest`. - @discardableResult - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open func stream(withHostName hostName: String, port: Int) -> StreamRequest { - return stream(.stream(hostName: hostName, port: port)) - } - - // MARK: NetService - - /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter netService: The net service used to identify the endpoint. - /// - /// - returns: The created `StreamRequest`. - @discardableResult - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open func stream(with netService: NetService) -> StreamRequest { - return stream(.netService(netService)) - } - - // MARK: Private - Stream Implementation - - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { - do { - let task = try streamable.task(session: session, adapter: adapter, queue: queue) - let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) - - delegate[task] = request - - if startRequestsImmediately { request.resume() } - - return request - } catch { - return stream(failedWith: error) - } - } - - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - private func stream(failedWith error: Error) -> StreamRequest { - let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) - if startRequestsImmediately { stream.resume() } - return stream - } - -#endif - - // MARK: - Internal - Retry Request - - func retry(_ request: Request) -> Bool { - guard let originalTask = request.originalTask else { return false } - - do { - let task = try originalTask.task(session: session, adapter: adapter, queue: queue) - - if let originalTask = request.task { - delegate[originalTask] = nil // removes the old request to avoid endless growth - } - - request.delegate.task = task // resets all task delegate data - - request.retryCount += 1 - request.startTime = CFAbsoluteTimeGetCurrent() - request.endTime = nil - - task.resume() - - return true - } catch { - request.delegate.error = error.underlyingAdaptError ?? error - return false - } - } - - private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { - DispatchQueue.utility.async { [weak self] in - guard let strongSelf = self else { return } - - retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in - guard let strongSelf = self else { return } - - guard shouldRetry else { - if strongSelf.startRequestsImmediately { request.resume() } - return - } - - DispatchQueue.utility.after(timeDelay) { - guard let strongSelf = self else { return } - - let retrySucceeded = strongSelf.retry(request) - - if retrySucceeded, let task = request.task { - strongSelf.delegate[task] = request - } else { - if strongSelf.startRequestsImmediately { request.resume() } - } - } - } - } - } -} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift deleted file mode 100644 index a25d80271d31..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/TaskDelegate.swift +++ /dev/null @@ -1,456 +0,0 @@ -// -// TaskDelegate.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as -/// executing all operations attached to the serial operation queue upon task completion. -open class TaskDelegate: NSObject { - - // MARK: Properties - - /// The serial operation queue used to execute all operations after the task completes. - public let queue: OperationQueue - - /// The data returned by the server. - public var data: Data? { return nil } - - /// The error generated throughout the lifecyle of the task. - public var error: Error? - - var task: URLSessionTask? { - set { - taskLock.lock(); defer { taskLock.unlock() } - _task = newValue - } - get { - taskLock.lock(); defer { taskLock.unlock() } - return _task - } - } - - var initialResponseTime: CFAbsoluteTime? - var credential: URLCredential? - var metrics: AnyObject? // URLSessionTaskMetrics - - private var _task: URLSessionTask? { - didSet { reset() } - } - - private let taskLock = NSLock() - - // MARK: Lifecycle - - init(task: URLSessionTask?) { - _task = task - - self.queue = { - let operationQueue = OperationQueue() - - operationQueue.maxConcurrentOperationCount = 1 - operationQueue.isSuspended = true - operationQueue.qualityOfService = .utility - - return operationQueue - }() - } - - func reset() { - error = nil - initialResponseTime = nil - } - - // MARK: URLSessionTaskDelegate - - var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? - var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? - var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? - var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? - - @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) - func urlSession( - _ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest, - completionHandler: @escaping (URLRequest?) -> Void) { - var redirectRequest: URLRequest? = request - - if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { - redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) - } - - completionHandler(redirectRequest) - } - - @objc(URLSession:task:didReceiveChallenge:completionHandler:) - func urlSession( - _ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { - var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling - var credential: URLCredential? - - if let taskDidReceiveChallenge = taskDidReceiveChallenge { - (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) - } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { - let host = challenge.protectionSpace.host - - if - let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), - let serverTrust = challenge.protectionSpace.serverTrust - { - if serverTrustPolicy.evaluate(serverTrust, forHost: host) { - disposition = .useCredential - credential = URLCredential(trust: serverTrust) - } else { - disposition = .cancelAuthenticationChallenge - } - } - } else { - if challenge.previousFailureCount > 0 { - disposition = .rejectProtectionSpace - } else { - credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) - - if credential != nil { - disposition = .useCredential - } - } - } - - completionHandler(disposition, credential) - } - - @objc(URLSession:task:needNewBodyStream:) - func urlSession( - _ session: URLSession, - task: URLSessionTask, - needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { - var bodyStream: InputStream? - - if let taskNeedNewBodyStream = taskNeedNewBodyStream { - bodyStream = taskNeedNewBodyStream(session, task) - } - - completionHandler(bodyStream) - } - - @objc(URLSession:task:didCompleteWithError:) - func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - if let taskDidCompleteWithError = taskDidCompleteWithError { - taskDidCompleteWithError(session, task, error) - } else { - if let error = error { - if self.error == nil { self.error = error } - - if - let downloadDelegate = self as? DownloadTaskDelegate, - let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data - { - downloadDelegate.resumeData = resumeData - } - } - - queue.isSuspended = false - } - } -} - -// MARK: - - -class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { - - // MARK: Properties - - var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } - - override var data: Data? { - if dataStream != nil { - return nil - } else { - return mutableData - } - } - - var progress: Progress - var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? - - var dataStream: ((_ data: Data) -> Void)? - - private var totalBytesReceived: Int64 = 0 - private var mutableData: Data - - private var expectedContentLength: Int64? - - // MARK: Lifecycle - - override init(task: URLSessionTask?) { - mutableData = Data() - progress = Progress(totalUnitCount: 0) - - super.init(task: task) - } - - override func reset() { - super.reset() - - progress = Progress(totalUnitCount: 0) - totalBytesReceived = 0 - mutableData = Data() - expectedContentLength = nil - } - - // MARK: URLSessionDataDelegate - - var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? - var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? - var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? - var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? - - func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didReceive response: URLResponse, - completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { - var disposition: URLSession.ResponseDisposition = .allow - - expectedContentLength = response.expectedContentLength - - if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { - disposition = dataTaskDidReceiveResponse(session, dataTask, response) - } - - completionHandler(disposition) - } - - func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didBecome downloadTask: URLSessionDownloadTask) { - dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) - } - - func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } - - if let dataTaskDidReceiveData = dataTaskDidReceiveData { - dataTaskDidReceiveData(session, dataTask, data) - } else { - if let dataStream = dataStream { - dataStream(data) - } else { - mutableData.append(data) - } - - let bytesReceived = Int64(data.count) - totalBytesReceived += bytesReceived - let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown - - progress.totalUnitCount = totalBytesExpected - progress.completedUnitCount = totalBytesReceived - - if let progressHandler = progressHandler { - progressHandler.queue.async { progressHandler.closure(self.progress) } - } - } - } - - func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse, - completionHandler: @escaping (CachedURLResponse?) -> Void) { - var cachedResponse: CachedURLResponse? = proposedResponse - - if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { - cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) - } - - completionHandler(cachedResponse) - } -} - -// MARK: - - -class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { - - // MARK: Properties - - var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } - - var progress: Progress - var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? - - var resumeData: Data? - override var data: Data? { return resumeData } - - var destination: DownloadRequest.DownloadFileDestination? - - var temporaryURL: URL? - var destinationURL: URL? - - var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } - - // MARK: Lifecycle - - override init(task: URLSessionTask?) { - progress = Progress(totalUnitCount: 0) - super.init(task: task) - } - - override func reset() { - super.reset() - - progress = Progress(totalUnitCount: 0) - resumeData = nil - } - - // MARK: URLSessionDownloadDelegate - - var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? - var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? - var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? - - func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) { - temporaryURL = location - - guard - let destination = destination, - let response = downloadTask.response as? HTTPURLResponse - else { return } - - let result = destination(location, response) - let destinationURL = result.destinationURL - let options = result.options - - self.destinationURL = destinationURL - - do { - if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { - try FileManager.default.removeItem(at: destinationURL) - } - - if options.contains(.createIntermediateDirectories) { - let directory = destinationURL.deletingLastPathComponent() - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - } - - try FileManager.default.moveItem(at: location, to: destinationURL) - } catch { - self.error = error - } - } - - func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) { - if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } - - if let downloadTaskDidWriteData = downloadTaskDidWriteData { - downloadTaskDidWriteData( - session, - downloadTask, - bytesWritten, - totalBytesWritten, - totalBytesExpectedToWrite - ) - } else { - progress.totalUnitCount = totalBytesExpectedToWrite - progress.completedUnitCount = totalBytesWritten - - if let progressHandler = progressHandler { - progressHandler.queue.async { progressHandler.closure(self.progress) } - } - } - } - - func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) { - if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { - downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) - } else { - progress.totalUnitCount = expectedTotalBytes - progress.completedUnitCount = fileOffset - } - } -} - -// MARK: - - -class UploadTaskDelegate: DataTaskDelegate { - - // MARK: Properties - - var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } - - var uploadProgress: Progress - var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? - - // MARK: Lifecycle - - override init(task: URLSessionTask?) { - uploadProgress = Progress(totalUnitCount: 0) - super.init(task: task) - } - - override func reset() { - super.reset() - uploadProgress = Progress(totalUnitCount: 0) - } - - // MARK: URLSessionTaskDelegate - - var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? - - func URLSession( - _ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) { - if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } - - if let taskDidSendBodyData = taskDidSendBodyData { - taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) - } else { - uploadProgress.totalUnitCount = totalBytesExpectedToSend - uploadProgress.completedUnitCount = totalBytesSent - - if let uploadProgressHandler = uploadProgressHandler { - uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } - } - } - } -} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift deleted file mode 100644 index 2c27dd29f74b..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Timeline.swift +++ /dev/null @@ -1,135 +0,0 @@ -// -// Timeline.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. -public struct Timeline { - /// The time the request was initialized. - public let requestStartTime: CFAbsoluteTime - - /// The time the first bytes were received from or sent to the server. - public let initialResponseTime: CFAbsoluteTime - - /// The time when the request was completed. - public let requestCompletedTime: CFAbsoluteTime - - /// The time when the response serialization was completed. - public let serializationCompletedTime: CFAbsoluteTime - - /// The time interval in seconds from the time the request started to the initial response from the server. - public let latency: TimeInterval - - /// The time interval in seconds from the time the request started to the time the request completed. - public let requestDuration: TimeInterval - - /// The time interval in seconds from the time the request completed to the time response serialization completed. - public let serializationDuration: TimeInterval - - /// The time interval in seconds from the time the request started to the time response serialization completed. - public let totalDuration: TimeInterval - - /// Creates a new `Timeline` instance with the specified request times. - /// - /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. - /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. - /// Defaults to `0.0`. - /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. - /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults - /// to `0.0`. - /// - /// - returns: The new `Timeline` instance. - public init( - requestStartTime: CFAbsoluteTime = 0.0, - initialResponseTime: CFAbsoluteTime = 0.0, - requestCompletedTime: CFAbsoluteTime = 0.0, - serializationCompletedTime: CFAbsoluteTime = 0.0) { - self.requestStartTime = requestStartTime - self.initialResponseTime = initialResponseTime - self.requestCompletedTime = requestCompletedTime - self.serializationCompletedTime = serializationCompletedTime - - self.latency = initialResponseTime - requestStartTime - self.requestDuration = requestCompletedTime - requestStartTime - self.serializationDuration = serializationCompletedTime - requestCompletedTime - self.totalDuration = serializationCompletedTime - requestStartTime - } -} - -// MARK: - CustomStringConvertible - -extension Timeline: CustomStringConvertible { - /// The textual representation used when written to an output stream, which includes the latency, the request - /// duration and the total duration. - public var description: String { - let latency = String(format: "%.3f", self.latency) - let requestDuration = String(format: "%.3f", self.requestDuration) - let serializationDuration = String(format: "%.3f", self.serializationDuration) - let totalDuration = String(format: "%.3f", self.totalDuration) - - // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is - // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. - let timings = [ - "\"Latency\": " + latency + " secs", - "\"Request Duration\": " + requestDuration + " secs", - "\"Serialization Duration\": " + serializationDuration + " secs", - "\"Total Duration\": " + totalDuration + " secs" - ] - - return "Timeline: { " + timings.joined(separator: ", ") + " }" - } -} - -// MARK: - CustomDebugStringConvertible - -extension Timeline: CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, which includes the request start time, the - /// initial response time, the request completed time, the serialization completed time, the latency, the request - /// duration and the total duration. - public var debugDescription: String { - let requestStartTime = String(format: "%.3f", self.requestStartTime) - let initialResponseTime = String(format: "%.3f", self.initialResponseTime) - let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) - let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) - let latency = String(format: "%.3f", self.latency) - let requestDuration = String(format: "%.3f", self.requestDuration) - let serializationDuration = String(format: "%.3f", self.serializationDuration) - let totalDuration = String(format: "%.3f", self.totalDuration) - - // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is - // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. - let timings = [ - "\"Request Start Time\": " + requestStartTime, - "\"Initial Response Time\": " + initialResponseTime, - "\"Request Completed Time\": " + requestCompletedTime, - "\"Serialization Completed Time\": " + serializationCompletedTime, - "\"Latency\": " + latency + " secs", - "\"Request Duration\": " + requestDuration + " secs", - "\"Serialization Duration\": " + serializationDuration + " secs", - "\"Total Duration\": " + totalDuration + " secs" - ] - - return "Timeline: { " + timings.joined(separator: ", ") + " }" - } -} diff --git a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift b/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift deleted file mode 100644 index 3c37e24d847f..000000000000 --- a/samples/client/petstore/swift4/default/SwaggerClientTests/Pods/Alamofire/Source/Validation.swift +++ /dev/null @@ -1,319 +0,0 @@ -// -// Validation.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension Request { - - // MARK: Helper Types - - fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason - - /// Used to represent whether validation was successful or encountered an error resulting in a failure. - /// - /// - success: The validation was successful. - /// - failure: The validation failed encountering the provided error. - public enum ValidationResult { - case success - case failure(Error) - } - - fileprivate struct MIMEType { - let type: String - let subtype: String - - var isWildcard: Bool { return type == "*" && subtype == "*" } - - init?(_ string: String) { - let components: [String] = { - let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) - - #if swift(>=3.2) - let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] - #else - let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) - #endif - - return split.components(separatedBy: "/") - }() - - if let type = components.first, let subtype = components.last { - self.type = type - self.subtype = subtype - } else { - return nil - } - } - - func matches(_ mime: MIMEType) -> Bool { - switch (type, subtype) { - case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): - return true - default: - return false - } - } - } - - // MARK: Properties - - fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } - - fileprivate var acceptableContentTypes: [String] { - if let accept = request?.value(forHTTPHeaderField: "Accept") { - return accept.components(separatedBy: ",") - } - - return ["*/*"] - } - - // MARK: Status Code - - fileprivate func validate( - statusCode acceptableStatusCodes: S, - response: HTTPURLResponse) - -> ValidationResult - where S.Iterator.Element == Int { - if acceptableStatusCodes.contains(response.statusCode) { - return .success - } else { - let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) - return .failure(AFError.responseValidationFailed(reason: reason)) - } - } - - // MARK: Content Type - - fileprivate func validate( - contentType acceptableContentTypes: S, - response: HTTPURLResponse, - data: Data?) - -> ValidationResult - where S.Iterator.Element == String { - guard let data = data, data.count > 0 else { return .success } - - guard - let responseContentType = response.mimeType, - let responseMIMEType = MIMEType(responseContentType) - else { - for contentType in acceptableContentTypes { - if let mimeType = MIMEType(contentType), mimeType.isWildcard { - return .success - } - } - - let error: AFError = { - let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) - return AFError.responseValidationFailed(reason: reason) - }() - - return .failure(error) - } - - for contentType in acceptableContentTypes { - if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { - return .success - } - } - - let error: AFError = { - let reason: ErrorReason = .unacceptableContentType( - acceptableContentTypes: Array(acceptableContentTypes), - responseContentType: responseContentType - ) - - return AFError.responseValidationFailed(reason: reason) - }() - - return .failure(error) - } -} - -// MARK: - - -extension DataRequest { - /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the - /// request was valid. - public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult - - /// Validates the request, using the specified closure. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter validation: A closure to validate the request. - /// - /// - returns: The request. - @discardableResult - public func validate(_ validation: @escaping Validation) -> Self { - let validationExecution: () -> Void = { [unowned self] in - if - let response = self.response, - self.delegate.error == nil, - case let .failure(error) = validation(self.request, response, self.delegate.data) - { - self.delegate.error = error - } - } - - validations.append(validationExecution) - - return self - } - - /// Validates that the response has a status code in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter range: The range of acceptable status codes. - /// - /// - returns: The request. - @discardableResult - public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { - return validate { [unowned self] _, response, _ in - return self.validate(statusCode: acceptableStatusCodes, response: response) - } - } - - /// Validates that the response has a content type in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - /// - /// - returns: The request. - @discardableResult - public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { - return validate { [unowned self] _, response, data in - return self.validate(contentType: acceptableContentTypes, response: response, data: data) - } - } - - /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content - /// type matches any specified in the Accept HTTP header field. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - returns: The request. - @discardableResult - public func validate() -> Self { - let contentTypes = { [unowned self] in - self.acceptableContentTypes - } - return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) - } -} - -// MARK: - - -extension DownloadRequest { - /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a - /// destination URL, and returns whether the request was valid. - public typealias Validation = ( - _ request: URLRequest?, - _ response: HTTPURLResponse, - _ temporaryURL: URL?, - _ destinationURL: URL?) - -> ValidationResult - - /// Validates the request, using the specified closure. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter validation: A closure to validate the request. - /// - /// - returns: The request. - @discardableResult - public func validate(_ validation: @escaping Validation) -> Self { - let validationExecution: () -> Void = { [unowned self] in - let request = self.request - let temporaryURL = self.downloadDelegate.temporaryURL - let destinationURL = self.downloadDelegate.destinationURL - - if - let response = self.response, - self.delegate.error == nil, - case let .failure(error) = validation(request, response, temporaryURL, destinationURL) - { - self.delegate.error = error - } - } - - validations.append(validationExecution) - - return self - } - - /// Validates that the response has a status code in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter range: The range of acceptable status codes. - /// - /// - returns: The request. - @discardableResult - public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { - return validate { [unowned self] _, response, _, _ in - return self.validate(statusCode: acceptableStatusCodes, response: response) - } - } - - /// Validates that the response has a content type in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - /// - /// - returns: The request. - @discardableResult - public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { - return validate { [unowned self] _, response, _, _ in - let fileURL = self.downloadDelegate.fileURL - - guard let validFileURL = fileURL else { - return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) - } - - do { - let data = try Data(contentsOf: validFileURL) - return self.validate(contentType: acceptableContentTypes, response: response, data: data) - } catch { - return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) - } - } - } - - /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content - /// type matches any specified in the Accept HTTP header field. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - returns: The request. - @discardableResult - public func validate() -> Self { - let contentTypes = { [unowned self] in - self.acceptableContentTypes - } - return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) - } -} diff --git a/samples/client/petstore/swift4/default/docs/FakeAPI.md b/samples/client/petstore/swift4/default/docs/FakeAPI.md index 49d4d3fb6a13..d0ab705d4e4b 100644 --- a/samples/client/petstore/swift4/default/docs/FakeAPI.md +++ b/samples/client/petstore/swift4/default/docs/FakeAPI.md @@ -11,7 +11,7 @@ Method | HTTP request | Description [**testBodyWithFileSchema**](FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters [**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties @@ -32,7 +32,7 @@ Test serialization of outer boolean types // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let body = false // Bool | Input boolean as post body (optional) +let body = true // Bool | Input boolean as post body (optional) FakeAPI.fakeOuterBooleanSerialize(body: body) { (response, error) in guard error == nil else { @@ -367,9 +367,9 @@ No authorization required open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```swift @@ -391,7 +391,7 @@ let dateTime = Date() // Date | None (optional) let password = "password_example" // String | None (optional) let callback = "callback_example" // String | None (optional) -// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 FakeAPI.testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { (response, error) in guard error == nil else { print(error) @@ -517,10 +517,10 @@ Fake endpoint to test group parameters (optional) import PetstoreClient let requiredStringGroup = 987 // Int | Required String in group parameters -let requiredBooleanGroup = false // Bool | Required Boolean in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters let requiredInt64Group = 987 // Int64 | Required Integer in group parameters let stringGroup = 987 // Int | String in group parameters (optional) -let booleanGroup = false // Bool | Boolean in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) let int64Group = 987 // Int64 | Integer in group parameters (optional) // Fake endpoint to test group parameters (optional) diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient.xcodeproj/project.pbxproj index b606fe1ab100..94b4f451305e 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient.xcodeproj/project.pbxproj @@ -299,6 +299,8 @@ isa = PBXProject; attributes = { LastUpgradeCheck = 1020; + TargetAttributes = { + }; }; buildConfigurationList = ECAB17FF35111B5E14DAAC08 /* Build configuration list for PBXProject "PetstoreClient" */; compatibilityVersion = "Xcode 10.0"; diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 6f36b224248a..8641eb7ebf77 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -22,7 +22,7 @@ internal struct APIHelper { internal static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" @@ -46,7 +46,7 @@ internal struct APIHelper { } internal static func mapValueToPathItem(_ source: Any) -> Any { - if let collection = source as? Array { + if let collection = source as? [Any?] { return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") } return source @@ -54,7 +54,7 @@ internal struct APIHelper { internal static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") result.append(URLQueryItem(name: item.key, value: value)) } else if let value = item.value { diff --git a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 28a05b008c6f..7fcf9f8545df 100644 --- a/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -226,7 +226,7 @@ internal class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - parameter integer: (form) None (optional) - parameter int32: (form) None (optional) @@ -255,9 +255,9 @@ internal class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - POST /fake - - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - BASIC: - type: http - name: http_basic_test diff --git a/samples/client/petstore/swift4/nonPublicApi/README.md b/samples/client/petstore/swift4/nonPublicApi/README.md index 0711eb870547..e00b3c99d2ae 100644 --- a/samples/client/petstore/swift4/nonPublicApi/README.md +++ b/samples/client/petstore/swift4/nonPublicApi/README.md @@ -33,7 +33,7 @@ Class | Method | HTTP request | Description *FakeAPI* | [**testBodyWithFileSchema**](docs/FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeAPI* | [**testBodyWithQueryParams**](docs/FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeAPI* | [**testClientModel**](docs/FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters *FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties diff --git a/samples/client/petstore/swift4/nonPublicApi/docs/FakeAPI.md b/samples/client/petstore/swift4/nonPublicApi/docs/FakeAPI.md index f8e42ac4df80..dd2d871bca84 100644 --- a/samples/client/petstore/swift4/nonPublicApi/docs/FakeAPI.md +++ b/samples/client/petstore/swift4/nonPublicApi/docs/FakeAPI.md @@ -11,7 +11,7 @@ Method | HTTP request | Description [**testBodyWithFileSchema**](FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters [**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties @@ -32,7 +32,7 @@ Test serialization of outer boolean types // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let body = false // Bool | Input boolean as post body (optional) +let body = true // Bool | Input boolean as post body (optional) FakeAPI.fakeOuterBooleanSerialize(body: body) { (response, error) in guard error == nil else { @@ -367,9 +367,9 @@ No authorization required internal class func testEndpointParameters(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```swift @@ -391,7 +391,7 @@ let dateTime = Date() // Date | None (optional) let password = "password_example" // String | None (optional) let callback = "callback_example" // String | None (optional) -// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 FakeAPI.testEndpointParameters(integer: integer, int32: int32, int64: int64, number: number, float: float, double: double, string: string, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { (response, error) in guard error == nil else { print(error) @@ -517,10 +517,10 @@ Fake endpoint to test group parameters (optional) import PetstoreClient let requiredStringGroup = 987 // Int | Required String in group parameters -let requiredBooleanGroup = false // Bool | Required Boolean in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters let requiredInt64Group = 987 // Int64 | Required Integer in group parameters let stringGroup = 987 // Int | String in group parameters (optional) -let booleanGroup = false // Bool | Boolean in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) let int64Group = 987 // Int64 | Integer in group parameters (optional) // Fake endpoint to test group parameters (optional) diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/objcCompatible/PetstoreClient.xcodeproj/project.pbxproj index b606fe1ab100..94b4f451305e 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient.xcodeproj/project.pbxproj @@ -299,6 +299,8 @@ isa = PBXProject; attributes = { LastUpgradeCheck = 1020; + TargetAttributes = { + }; }; buildConfigurationList = ECAB17FF35111B5E14DAAC08 /* Build configuration list for PBXProject "PetstoreClient" */; compatibilityVersion = "Xcode 10.0"; diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 75dea2439575..200070096800 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -22,7 +22,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" @@ -46,7 +46,7 @@ public struct APIHelper { } public static func mapValueToPathItem(_ source: Any) -> Any { - if let collection = source as? Array { + if let collection = source as? [Any?] { return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") } return source @@ -54,7 +54,7 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") result.append(URLQueryItem(name: item.key, value: value)) } else if let value = item.value { diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 02e24286e3c8..89e7eb02109c 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -7,7 +7,7 @@ import Foundation -open class AnotherFakeAPI { +@objc open class AnotherFakeAPI: NSObject { /** To test special tags diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index b0b394aa06e0..19738e6b1e74 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -7,7 +7,7 @@ import Foundation -open class FakeAPI { +@objc open class FakeAPI: NSObject { /** - parameter body: (body) Input boolean as post body (optional) @@ -226,7 +226,7 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - parameter number: (form) None - parameter double: (form) None @@ -255,9 +255,9 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - POST /fake - - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - BASIC: - type: http - name: http_basic_test diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 060d434fbf24..ba8571a22f9d 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -7,7 +7,7 @@ import Foundation -open class FakeClassnameTags123API { +@objc open class FakeClassnameTags123API: NSObject { /** To test class name in snake case diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index fe75962a72cf..25c4dfc14918 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -7,7 +7,7 @@ import Foundation -open class PetAPI { +@objc open class PetAPI: NSObject { /** Add a new pet to the store diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index d5f627df52ac..c2d0578f0a47 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -7,7 +7,7 @@ import Foundation -open class StoreAPI { +@objc open class StoreAPI: NSObject { /** Delete purchase order by ID diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index ef4f971a91e2..ad10a9334db6 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -7,7 +7,7 @@ import Foundation -open class UserAPI { +@objc open class UserAPI: NSObject { /** Create user diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 83a06951ccd6..25a2d8b46c03 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -7,7 +7,7 @@ import Foundation -public struct AdditionalPropertiesClass: Codable { +@objc public class AdditionalPropertiesClass: NSObject, Codable { public var mapString: [String: String]? public var mapMapString: [String: [String: String]]? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 5ed9f31e2a36..b63ebe3aad4d 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -7,14 +7,19 @@ import Foundation -public struct Animal: Codable { +@objc public class Animal: NSObject, Codable { - public var className: String + public var _className: String public var color: String? = "red" - public init(className: String, color: String?) { - self.className = className + public init(_className: String, color: String?) { + self._className = _className self.color = color } + public enum CodingKeys: String, CodingKey { + case _className = "className" + case color + } + } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index ec270da89074..d0fcd4368854 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -7,9 +7,14 @@ import Foundation -public struct ApiResponse: Codable { +@objc public class ApiResponse: NSObject, Codable { public var code: Int? + public var codeNum: NSNumber? { + get { + return code as NSNumber? + } + } public var type: String? public var message: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 3843287630b1..fddd1e8eb2e2 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -7,7 +7,7 @@ import Foundation -public struct ArrayOfArrayOfNumberOnly: Codable { +@objc public class ArrayOfArrayOfNumberOnly: NSObject, Codable { public var arrayArrayNumber: [[Double]]? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index f8b198e81f50..0a3450dd69f9 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -7,7 +7,7 @@ import Foundation -public struct ArrayOfNumberOnly: Codable { +@objc public class ArrayOfNumberOnly: NSObject, Codable { public var arrayNumber: [Double]? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index 67f7f7e5151f..dbc35d31065c 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -7,7 +7,7 @@ import Foundation -public struct ArrayTest: Codable { +@objc public class ArrayTest: NSObject, Codable { public var arrayOfString: [String]? public var arrayArrayOfInteger: [[Int64]]? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index d576b50b1c9c..27102732b74e 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -7,7 +7,7 @@ import Foundation -public struct Capitalization: Codable { +@objc public class Capitalization: NSObject, Codable { public var smallCamel: String? public var capitalCamel: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 7d819cbcc8f4..c78d15eecbc9 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -7,21 +7,27 @@ import Foundation -public struct Cat: Codable { +@objc public class Cat: NSObject, Codable { - public var className: String + public var _className: String public var color: String? = "red" public var declawed: Bool? public var declawedNum: NSNumber? { get { - return declawed.map({ return NSNumber(value: $0) }) + return declawed as NSNumber? } } - public init(className: String, color: String?, declawed: Bool?) { - self.className = className + public init(_className: String, color: String?, declawed: Bool?) { + self._className = _className self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey { + case _className = "className" + case color + case declawed + } + } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index a51ad0dffab1..ef8cec45aff1 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -7,9 +7,14 @@ import Foundation -public struct CatAllOf: Codable { +@objc public class CatAllOf: NSObject, Codable { public var declawed: Bool? + public var declawedNum: NSNumber? { + get { + return declawed as NSNumber? + } + } public init(declawed: Bool?) { self.declawed = declawed diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index abcd82b07837..94d01910abe8 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,9 +7,14 @@ import Foundation -public struct Category: Codable { +@objc public class Category: NSObject, Codable { public var _id: Int64? + public var _idNum: NSNumber? { + get { + return _id as NSNumber? + } + } public var name: String = "default-name" public init(_id: Int64?, name: String) { diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index e2a7d4427a06..4197ffcaed6c 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -8,7 +8,8 @@ import Foundation /** Model for testing model with \"_class\" property */ -public struct ClassModel: Codable { + +@objc public class ClassModel: NSObject, Codable { public var _class: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 00245ca37280..517dbbba2ec2 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -7,7 +7,7 @@ import Foundation -public struct Client: Codable { +@objc public class Client: NSObject, Codable { public var client: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 492c1228008e..e6a878a1ea05 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -7,16 +7,22 @@ import Foundation -public struct Dog: Codable { +@objc public class Dog: NSObject, Codable { - public var className: String + public var _className: String public var color: String? = "red" public var breed: String? - public init(className: String, color: String?, breed: String?) { - self.className = className + public init(_className: String, color: String?, breed: String?) { + self._className = _className self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey { + case _className = "className" + case color + case breed + } + } diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 7786f8acc5ae..73fd1822725c 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -7,7 +7,7 @@ import Foundation -public struct DogAllOf: Codable { +@objc public class DogAllOf: NSObject, Codable { public var breed: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 5034ff0b8c68..4e35e79a6820 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -7,7 +7,7 @@ import Foundation -public struct EnumArrays: Codable { +@objc public class EnumArrays: NSObject, Codable { public enum JustSymbol: String, Codable { case greaterThanOrEqualTo = ">=" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 6db9b34d183b..a6906e8bbef9 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -7,7 +7,7 @@ import Foundation -public struct EnumTest: Codable { +@objc public class EnumTest: NSObject, Codable { public enum EnumString: String, Codable { case upper = "UPPER" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift index abf3ccffc485..7a320c177d38 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -8,7 +8,8 @@ import Foundation /** Must be named `File` for test. */ -public struct File: Codable { + +@objc public class File: NSObject, Codable { /** Test capitalization */ public var sourceURI: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index 532f1457939a..a6437b4fe901 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -7,7 +7,7 @@ import Foundation -public struct FileSchemaTestClass: Codable { +@objc public class FileSchemaTestClass: NSObject, Codable { public var file: File? public var files: [File]? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 20bd6d103b3d..df2c46d3757b 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -7,14 +7,39 @@ import Foundation -public struct FormatTest: Codable { +@objc public class FormatTest: NSObject, Codable { public var integer: Int? + public var integerNum: NSNumber? { + get { + return integer as NSNumber? + } + } public var int32: Int? + public var int32Num: NSNumber? { + get { + return int32 as NSNumber? + } + } public var int64: Int64? + public var int64Num: NSNumber? { + get { + return int64 as NSNumber? + } + } public var number: Double public var float: Float? + public var floatNum: NSNumber? { + get { + return float as NSNumber? + } + } public var double: Double? + public var doubleNum: NSNumber? { + get { + return double as NSNumber? + } + } public var string: String? public var byte: Data public var binary: URL? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 906ddb06fb17..b9f5b39117d7 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -7,7 +7,7 @@ import Foundation -public struct HasOnlyReadOnly: Codable { +@objc public class HasOnlyReadOnly: NSObject, Codable { public var bar: String? public var foo: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift index 08d59953873e..2ac4bfc90d84 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -7,7 +7,7 @@ import Foundation -public struct List: Codable { +@objc public class List: NSObject, Codable { public var _123list: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 3a10a7dfcaf6..4fb067a5ffab 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -7,7 +7,7 @@ import Foundation -public struct MapTest: Codable { +@objc public class MapTest: NSObject, Codable { public enum MapOfEnumString: String, Codable { case upper = "UPPER" diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index c3deb2f28932..e10adad0a7e1 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -7,7 +7,7 @@ import Foundation -public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { +@objc public class MixedPropertiesAndAdditionalPropertiesClass: NSObject, Codable { public var uuid: UUID? public var dateTime: Date? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index 78917d75b44d..2e9399332e6a 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -8,9 +8,15 @@ import Foundation /** Model for testing model name starting with number */ -public struct Model200Response: Codable { + +@objc public class Model200Response: NSObject, Codable { public var name: Int? + public var nameNum: NSNumber? { + get { + return name as NSNumber? + } + } public var _class: String? public init(name: Int?, _class: String?) { diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 43c4891e1e23..e30fd5a47152 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -8,12 +8,28 @@ import Foundation /** Model for testing model name same as property name */ -public struct Name: Codable { + +@objc public class Name: NSObject, Codable { public var name: Int + public var nameNum: NSNumber? { + get { + return name as NSNumber? + } + } public var snakeCase: Int? + public var snakeCaseNum: NSNumber? { + get { + return snakeCase as NSNumber? + } + } public var property: String? public var _123number: Int? + public var _123numberNum: NSNumber? { + get { + return _123number as NSNumber? + } + } public init(name: Int, snakeCase: Int?, property: String?, _123number: Int?) { self.name = name diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index abd2269e8e76..9a80fcacc6ca 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -7,7 +7,7 @@ import Foundation -public struct NumberOnly: Codable { +@objc public class NumberOnly: NSObject, Codable { public var justNumber: Double? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index f2b7565e2d91..37cfed6adb23 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -7,7 +7,7 @@ import Foundation -public struct Order: Codable { +@objc public class Order: NSObject, Codable { public enum Status: String, Codable { case placed = "placed" @@ -15,12 +15,32 @@ public struct Order: Codable { case delivered = "delivered" } public var _id: Int64? + public var _idNum: NSNumber? { + get { + return _id as NSNumber? + } + } public var petId: Int64? + public var petIdNum: NSNumber? { + get { + return petId as NSNumber? + } + } public var quantity: Int? + public var quantityNum: NSNumber? { + get { + return quantity as NSNumber? + } + } public var shipDate: Date? /** Order Status */ public var status: Status? public var complete: Bool? = false + public var completeNum: NSNumber? { + get { + return complete as NSNumber? + } + } public init(_id: Int64?, petId: Int64?, quantity: Int?, shipDate: Date?, status: Status?, complete: Bool?) { self._id = _id diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 49aec001c5db..85ed62455d10 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -7,11 +7,16 @@ import Foundation -public struct OuterComposite: Codable { +@objc public class OuterComposite: NSObject, Codable { public var myNumber: Double? public var myString: String? public var myBoolean: Bool? + public var myBooleanNum: NSNumber? { + get { + return myBoolean as NSNumber? + } + } public init(myNumber: Double?, myString: String?, myBoolean: Bool?) { self.myNumber = myNumber diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index 971ce9d4db6e..f99f4d790ec6 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -7,7 +7,7 @@ import Foundation -public struct Pet: Codable { +@objc public class Pet: NSObject, Codable { public enum Status: String, Codable { case available = "available" @@ -15,6 +15,11 @@ public struct Pet: Codable { case sold = "sold" } public var _id: Int64? + public var _idNum: NSNumber? { + get { + return _id as NSNumber? + } + } public var category: Category? public var name: String public var photoUrls: [String] diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 0acd21fd1000..d1252433b2d8 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -7,7 +7,7 @@ import Foundation -public struct ReadOnlyFirst: Codable { +@objc public class ReadOnlyFirst: NSObject, Codable { public var bar: String? public var baz: String? diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index b34ddc68142d..50c3614973df 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -8,9 +8,15 @@ import Foundation /** Model for testing reserved words */ -public struct Return: Codable { + +@objc public class Return: NSObject, Codable { public var _return: Int? + public var _returnNum: NSNumber? { + get { + return _return as NSNumber? + } + } public init(_return: Int?) { self._return = _return diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index e79fc45c0e91..0996025cce52 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -7,9 +7,14 @@ import Foundation -public struct SpecialModelName: Codable { +@objc public class SpecialModelName: NSObject, Codable { public var specialPropertyName: Int64? + public var specialPropertyNameNum: NSNumber? { + get { + return specialPropertyName as NSNumber? + } + } public init(specialPropertyName: Int64?) { self.specialPropertyName = specialPropertyName diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 3f1237fee477..ffe9730a6fe4 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -7,7 +7,7 @@ import Foundation -public struct StringBooleanMap: Codable { +@objc public class StringBooleanMap: NSObject, Codable { public var additionalProperties: [String: Bool] = [:] @@ -35,7 +35,7 @@ public struct StringBooleanMap: Codable { // Decodable protocol methods - public init(from decoder: Decoder) throws { + public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: String.self) var nonAdditionalPropertyKeys = Set() diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 83efe72b8a4e..a3994745e254 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,9 +7,14 @@ import Foundation -public struct Tag: Codable { +@objc public class Tag: NSObject, Codable { public var _id: Int64? + public var _idNum: NSNumber? { + get { + return _id as NSNumber? + } + } public var name: String? public init(_id: Int64?, name: String?) { diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index bf0006e1a266..382944d1b0d5 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -7,12 +7,22 @@ import Foundation -public struct TypeHolderDefault: Codable { +@objc public class TypeHolderDefault: NSObject, Codable { public var stringItem: String = "what" public var numberItem: Double public var integerItem: Int + public var integerItemNum: NSNumber? { + get { + return integerItem as NSNumber? + } + } public var boolItem: Bool = true + public var boolItemNum: NSNumber? { + get { + return boolItem as NSNumber? + } + } public var arrayItem: [Int] public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index 602a2a6d185a..0344e51e0e34 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -7,12 +7,22 @@ import Foundation -public struct TypeHolderExample: Codable { +@objc public class TypeHolderExample: NSObject, Codable { public var stringItem: String public var numberItem: Double public var integerItem: Int + public var integerItemNum: NSNumber? { + get { + return integerItem as NSNumber? + } + } public var boolItem: Bool + public var boolItemNum: NSNumber? { + get { + return boolItem as NSNumber? + } + } public var arrayItem: [Int] public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { diff --git a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 7d6b24b9e100..9b9b03a946f8 100644 --- a/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift4/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -7,9 +7,14 @@ import Foundation -public struct User: Codable { +@objc public class User: NSObject, Codable { public var _id: Int64? + public var _idNum: NSNumber? { + get { + return _id as NSNumber? + } + } public var username: String? public var firstName: String? public var lastName: String? @@ -18,6 +23,11 @@ public struct User: Codable { public var phone: String? /** User Status */ public var userStatus: Int? + public var userStatusNum: NSNumber? { + get { + return userStatus as NSNumber? + } + } public init(_id: Int64?, username: String?, firstName: String?, lastName: String?, email: String?, password: String?, phone: String?, userStatus: Int?) { self._id = _id diff --git a/samples/client/petstore/swift4/objcCompatible/README.md b/samples/client/petstore/swift4/objcCompatible/README.md index 0711eb870547..e00b3c99d2ae 100644 --- a/samples/client/petstore/swift4/objcCompatible/README.md +++ b/samples/client/petstore/swift4/objcCompatible/README.md @@ -33,7 +33,7 @@ Class | Method | HTTP request | Description *FakeAPI* | [**testBodyWithFileSchema**](docs/FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeAPI* | [**testBodyWithQueryParams**](docs/FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeAPI* | [**testClientModel**](docs/FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters *FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties diff --git a/samples/client/petstore/swift4/objcCompatible/docs/Animal.md b/samples/client/petstore/swift4/objcCompatible/docs/Animal.md index 69c601455cd8..5ca136c87e86 100644 --- a/samples/client/petstore/swift4/objcCompatible/docs/Animal.md +++ b/samples/client/petstore/swift4/objcCompatible/docs/Animal.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | +**_className** | **String** | | **color** | **String** | | [optional] [default to "red"] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/swift4/objcCompatible/docs/FakeAPI.md b/samples/client/petstore/swift4/objcCompatible/docs/FakeAPI.md index c7e27b881fdb..f7faf3aa2aa6 100644 --- a/samples/client/petstore/swift4/objcCompatible/docs/FakeAPI.md +++ b/samples/client/petstore/swift4/objcCompatible/docs/FakeAPI.md @@ -11,7 +11,7 @@ Method | HTTP request | Description [**testBodyWithFileSchema**](FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters [**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties @@ -32,7 +32,7 @@ Test serialization of outer boolean types // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let body = false // Bool | Input boolean as post body (optional) +let body = true // Bool | Input boolean as post body (optional) FakeAPI.fakeOuterBooleanSerialize(body: body) { (response, error) in guard error == nil else { @@ -367,9 +367,9 @@ No authorization required open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```swift @@ -391,7 +391,7 @@ let dateTime = Date() // Date | None (optional) let password = "password_example" // String | None (optional) let callback = "callback_example" // String | None (optional) -// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 FakeAPI.testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { (response, error) in guard error == nil else { print(error) @@ -517,10 +517,10 @@ Fake endpoint to test group parameters (optional) import PetstoreClient let requiredStringGroup = 987 // Int | Required String in group parameters -let requiredBooleanGroup = false // Bool | Required Boolean in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters let requiredInt64Group = 987 // Int64 | Required Integer in group parameters let stringGroup = 987 // Int | String in group parameters (optional) -let booleanGroup = false // Bool | Boolean in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) let int64Group = 987 // Int64 | Integer in group parameters (optional) // Fake endpoint to test group parameters (optional) diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient.xcodeproj/project.pbxproj index c2e04850669d..6b9213511f8a 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient.xcodeproj/project.pbxproj @@ -303,6 +303,8 @@ isa = PBXProject; attributes = { LastUpgradeCheck = 1020; + TargetAttributes = { + }; }; buildConfigurationList = ECAB17FF35111B5E14DAAC08 /* Build configuration list for PBXProject "PetstoreClient" */; compatibilityVersion = "Xcode 10.0"; diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 75dea2439575..200070096800 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -22,7 +22,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" @@ -46,7 +46,7 @@ public struct APIHelper { } public static func mapValueToPathItem(_ source: Any) -> Any { - if let collection = source as? Array { + if let collection = source as? [Any?] { return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") } return source @@ -54,7 +54,7 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") result.append(URLQueryItem(name: item.key, value: value)) } else if let value = item.value { diff --git a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 39c419674ba1..9ce9e5b16ae0 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -271,7 +271,7 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - parameter number: (form) None - parameter double: (form) None @@ -302,9 +302,9 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - POST /fake - - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - BASIC: - type: http - name: http_basic_test diff --git a/samples/client/petstore/swift4/promisekitLibrary/README.md b/samples/client/petstore/swift4/promisekitLibrary/README.md index 0711eb870547..e00b3c99d2ae 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/README.md +++ b/samples/client/petstore/swift4/promisekitLibrary/README.md @@ -33,7 +33,7 @@ Class | Method | HTTP request | Description *FakeAPI* | [**testBodyWithFileSchema**](docs/FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeAPI* | [**testBodyWithQueryParams**](docs/FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeAPI* | [**testClientModel**](docs/FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters *FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties diff --git a/samples/client/petstore/swift4/promisekitLibrary/docs/FakeAPI.md b/samples/client/petstore/swift4/promisekitLibrary/docs/FakeAPI.md index bf8e514f03d7..5519037c52cb 100644 --- a/samples/client/petstore/swift4/promisekitLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift4/promisekitLibrary/docs/FakeAPI.md @@ -11,7 +11,7 @@ Method | HTTP request | Description [**testBodyWithFileSchema**](FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters [**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties @@ -32,7 +32,7 @@ Test serialization of outer boolean types // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let body = false // Bool | Input boolean as post body (optional) +let body = true // Bool | Input boolean as post body (optional) FakeAPI.fakeOuterBooleanSerialize(body: body).then { // when the promise is fulfilled @@ -346,9 +346,9 @@ No authorization required open class func testEndpointParameters( number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> Promise ``` -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```swift @@ -370,7 +370,7 @@ let dateTime = Date() // Date | None (optional) let password = "password_example" // String | None (optional) let callback = "callback_example" // String | None (optional) -// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 FakeAPI.testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).then { // when the promise is fulfilled }.always { @@ -490,10 +490,10 @@ Fake endpoint to test group parameters (optional) import PetstoreClient let requiredStringGroup = 987 // Int | Required String in group parameters -let requiredBooleanGroup = false // Bool | Required Boolean in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters let requiredInt64Group = 987 // Int64 | Required Integer in group parameters let stringGroup = 987 // Int | String in group parameters (optional) -let booleanGroup = false // Bool | Boolean in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) let int64Group = 987 // Int64 | Integer in group parameters (optional) // Fake endpoint to test group parameters (optional) diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/resultLibrary/PetstoreClient.xcodeproj/project.pbxproj index 49e6ca81fd81..e8707f0ff9b1 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient.xcodeproj/project.pbxproj @@ -302,6 +302,8 @@ isa = PBXProject; attributes = { LastUpgradeCheck = 1020; + TargetAttributes = { + }; }; buildConfigurationList = ECAB17FF35111B5E14DAAC08 /* Build configuration list for PBXProject "PetstoreClient" */; compatibilityVersion = "Xcode 10.0"; diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 75dea2439575..200070096800 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -22,7 +22,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" @@ -46,7 +46,7 @@ public struct APIHelper { } public static func mapValueToPathItem(_ source: Any) -> Any { - if let collection = source as? Array { + if let collection = source as? [Any?] { return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") } return source @@ -54,7 +54,7 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") result.append(URLQueryItem(name: item.key, value: value)) } else if let value = item.value { diff --git a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index c5d29842ad87..341e23d3685b 100644 --- a/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -336,7 +336,7 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - parameter number: (form) None - parameter double: (form) None @@ -364,7 +364,7 @@ open class FakeAPI { } } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - parameter number: (form) None - parameter double: (form) None @@ -393,9 +393,9 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - POST /fake - - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - BASIC: - type: http - name: http_basic_test diff --git a/samples/client/petstore/swift4/resultLibrary/README.md b/samples/client/petstore/swift4/resultLibrary/README.md index 0711eb870547..e00b3c99d2ae 100644 --- a/samples/client/petstore/swift4/resultLibrary/README.md +++ b/samples/client/petstore/swift4/resultLibrary/README.md @@ -33,7 +33,7 @@ Class | Method | HTTP request | Description *FakeAPI* | [**testBodyWithFileSchema**](docs/FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeAPI* | [**testBodyWithQueryParams**](docs/FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeAPI* | [**testClientModel**](docs/FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters *FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties diff --git a/samples/client/petstore/swift4/resultLibrary/docs/FakeAPI.md b/samples/client/petstore/swift4/resultLibrary/docs/FakeAPI.md index 49d4d3fb6a13..d0ab705d4e4b 100644 --- a/samples/client/petstore/swift4/resultLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift4/resultLibrary/docs/FakeAPI.md @@ -11,7 +11,7 @@ Method | HTTP request | Description [**testBodyWithFileSchema**](FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters [**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties @@ -32,7 +32,7 @@ Test serialization of outer boolean types // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let body = false // Bool | Input boolean as post body (optional) +let body = true // Bool | Input boolean as post body (optional) FakeAPI.fakeOuterBooleanSerialize(body: body) { (response, error) in guard error == nil else { @@ -367,9 +367,9 @@ No authorization required open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```swift @@ -391,7 +391,7 @@ let dateTime = Date() // Date | None (optional) let password = "password_example" // String | None (optional) let callback = "callback_example" // String | None (optional) -// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 FakeAPI.testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { (response, error) in guard error == nil else { print(error) @@ -517,10 +517,10 @@ Fake endpoint to test group parameters (optional) import PetstoreClient let requiredStringGroup = 987 // Int | Required String in group parameters -let requiredBooleanGroup = false // Bool | Required Boolean in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters let requiredInt64Group = 987 // Int64 | Required Integer in group parameters let stringGroup = 987 // Int | String in group parameters (optional) -let booleanGroup = false // Bool | Boolean in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) let int64Group = 987 // Int64 | Integer in group parameters (optional) // Fake endpoint to test group parameters (optional) diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient.xcodeproj/project.pbxproj index 43e65668d5ae..c749d2778db9 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient.xcodeproj/project.pbxproj @@ -303,6 +303,8 @@ isa = PBXProject; attributes = { LastUpgradeCheck = 1020; + TargetAttributes = { + }; }; buildConfigurationList = ECAB17FF35111B5E14DAAC08 /* Build configuration list for PBXProject "PetstoreClient" */; compatibilityVersion = "Xcode 10.0"; diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 75dea2439575..200070096800 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -22,7 +22,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" @@ -46,7 +46,7 @@ public struct APIHelper { } public static func mapValueToPathItem(_ source: Any) -> Any { - if let collection = source as? Array { + if let collection = source as? [Any?] { return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") } return source @@ -54,7 +54,7 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") result.append(URLQueryItem(name: item.key, value: value)) } else if let value = item.value { diff --git a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index edbc9b6fffc6..a20128c73813 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -285,7 +285,7 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - parameter number: (form) None - parameter double: (form) None @@ -318,9 +318,9 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - POST /fake - - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - BASIC: - type: http - name: http_basic_test diff --git a/samples/client/petstore/swift4/rxswiftLibrary/README.md b/samples/client/petstore/swift4/rxswiftLibrary/README.md index 0711eb870547..e00b3c99d2ae 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/README.md +++ b/samples/client/petstore/swift4/rxswiftLibrary/README.md @@ -33,7 +33,7 @@ Class | Method | HTTP request | Description *FakeAPI* | [**testBodyWithFileSchema**](docs/FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeAPI* | [**testBodyWithQueryParams**](docs/FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeAPI* | [**testClientModel**](docs/FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters *FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties diff --git a/samples/client/petstore/swift4/rxswiftLibrary/docs/FakeAPI.md b/samples/client/petstore/swift4/rxswiftLibrary/docs/FakeAPI.md index a9a6c32c98bd..aae8b34423b7 100644 --- a/samples/client/petstore/swift4/rxswiftLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift4/rxswiftLibrary/docs/FakeAPI.md @@ -11,7 +11,7 @@ Method | HTTP request | Description [**testBodyWithFileSchema**](FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters [**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties @@ -32,7 +32,7 @@ Test serialization of outer boolean types // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let body = false // Bool | Input boolean as post body (optional) +let body = true // Bool | Input boolean as post body (optional) // TODO RxSwift sample code not yet implemented. To contribute, please open a ticket via http://github.com/OpenAPITools/openapi-generator/issues/new ``` @@ -303,9 +303,9 @@ No authorization required open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> Observable ``` -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```swift @@ -433,10 +433,10 @@ Fake endpoint to test group parameters (optional) import PetstoreClient let requiredStringGroup = 987 // Int | Required String in group parameters -let requiredBooleanGroup = false // Bool | Required Boolean in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters let requiredInt64Group = 987 // Int64 | Required Integer in group parameters let stringGroup = 987 // Int | String in group parameters (optional) -let booleanGroup = false // Bool | Boolean in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) let int64Group = 987 // Int64 | Integer in group parameters (optional) // TODO RxSwift sample code not yet implemented. To contribute, please open a ticket via http://github.com/OpenAPITools/openapi-generator/issues/new diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient.xcodeproj/project.pbxproj index b606fe1ab100..94b4f451305e 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient.xcodeproj/project.pbxproj @@ -299,6 +299,8 @@ isa = PBXProject; attributes = { LastUpgradeCheck = 1020; + TargetAttributes = { + }; }; buildConfigurationList = ECAB17FF35111B5E14DAAC08 /* Build configuration list for PBXProject "PetstoreClient" */; compatibilityVersion = "Xcode 10.0"; diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 75dea2439575..200070096800 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -22,7 +22,7 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { result[item.key] = collection.filter({ $0 != nil }).map { "\($0!)" }.joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" @@ -46,7 +46,7 @@ public struct APIHelper { } public static func mapValueToPathItem(_ source: Any) -> Any { - if let collection = source as? Array { + if let collection = source as? [Any?] { return collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") } return source @@ -54,7 +54,7 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter({ $0.value != nil}).reduce(into: [URLQueryItem]()) { (result, item) in - if let collection = item.value as? Array { + if let collection = item.value as? [Any?] { let value = collection.filter({ $0 != nil }).map({"\($0!)"}).joined(separator: ",") result.append(URLQueryItem(name: item.key, value: value)) } else if let value = item.value { diff --git a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index b0b394aa06e0..8f5d7550f0c8 100644 --- a/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift4/unwrapRequired/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -226,7 +226,7 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - parameter number: (form) None - parameter double: (form) None @@ -255,9 +255,9 @@ open class FakeAPI { } /** - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - POST /fake - - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - BASIC: - type: http - name: http_basic_test diff --git a/samples/client/petstore/swift4/unwrapRequired/README.md b/samples/client/petstore/swift4/unwrapRequired/README.md index 0711eb870547..e00b3c99d2ae 100644 --- a/samples/client/petstore/swift4/unwrapRequired/README.md +++ b/samples/client/petstore/swift4/unwrapRequired/README.md @@ -33,7 +33,7 @@ Class | Method | HTTP request | Description *FakeAPI* | [**testBodyWithFileSchema**](docs/FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeAPI* | [**testBodyWithQueryParams**](docs/FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeAPI* | [**testClientModel**](docs/FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters *FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties diff --git a/samples/client/petstore/swift4/unwrapRequired/docs/FakeAPI.md b/samples/client/petstore/swift4/unwrapRequired/docs/FakeAPI.md index 49d4d3fb6a13..d0ab705d4e4b 100644 --- a/samples/client/petstore/swift4/unwrapRequired/docs/FakeAPI.md +++ b/samples/client/petstore/swift4/unwrapRequired/docs/FakeAPI.md @@ -11,7 +11,7 @@ Method | HTTP request | Description [**testBodyWithFileSchema**](FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | [**testClientModel**](FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model -[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 [**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters [**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties @@ -32,7 +32,7 @@ Test serialization of outer boolean types // The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new import PetstoreClient -let body = false // Bool | Input boolean as post body (optional) +let body = true // Bool | Input boolean as post body (optional) FakeAPI.fakeOuterBooleanSerialize(body: body) { (response, error) in guard error == nil else { @@ -367,9 +367,9 @@ No authorization required open class func testEndpointParameters(number: Double, double: Double, patternWithoutDelimiter: String, byte: Data, integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, float: Float? = nil, string: String? = nil, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```swift @@ -391,7 +391,7 @@ let dateTime = Date() // Date | None (optional) let password = "password_example" // String | None (optional) let callback = "callback_example" // String | None (optional) -// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 FakeAPI.testEndpointParameters(number: number, double: double, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, integer: integer, int32: int32, int64: int64, float: float, string: string, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { (response, error) in guard error == nil else { print(error) @@ -517,10 +517,10 @@ Fake endpoint to test group parameters (optional) import PetstoreClient let requiredStringGroup = 987 // Int | Required String in group parameters -let requiredBooleanGroup = false // Bool | Required Boolean in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters let requiredInt64Group = 987 // Int64 | Required Integer in group parameters let stringGroup = 987 // Int | String in group parameters (optional) -let booleanGroup = false // Bool | Boolean in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) let int64Group = 987 // Int64 | Integer in group parameters (optional) // Fake endpoint to test group parameters (optional) diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 5bbf323f820c..2e9ad96a66b5 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -7,7 +7,7 @@ import Foundation -open class AnotherFakeAPI { +@objc open class AnotherFakeAPI: NSObject { /** To test special tags diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 134d6aea416a..6483ab29bcc3 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -7,7 +7,7 @@ import Foundation -open class FakeAPI { +@objc open class FakeAPI: NSObject { /** - parameter body: (body) Input boolean as post body (optional) diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 48cfe7187b9a..b9cfc75eeb4c 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -7,7 +7,7 @@ import Foundation -open class FakeClassnameTags123API { +@objc open class FakeClassnameTags123API: NSObject { /** To test class name in snake case diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 0552d4a6c16e..e1708decd35b 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -7,7 +7,7 @@ import Foundation -open class PetAPI { +@objc open class PetAPI: NSObject { /** Add a new pet to the store diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index a8a83eda39a4..a19d12c7d24b 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -7,7 +7,7 @@ import Foundation -open class StoreAPI { +@objc open class StoreAPI: NSObject { /** Delete purchase order by ID diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 505ed1b0c5c9..4dfe4da1a021 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -7,7 +7,7 @@ import Foundation -open class UserAPI { +@objc open class UserAPI: NSObject { /** Create user diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift index 1af031535967..e184d7691799 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -7,7 +7,7 @@ import Foundation -public struct AdditionalPropertiesClass: Codable { +@objc public class AdditionalPropertiesClass: NSObject, Codable { public var mapString: [String: String]? public var mapMapString: [String: [String: String]]? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift index 5ed9f31e2a36..88152934da2b 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -7,14 +7,19 @@ import Foundation -public struct Animal: Codable { +@objc public class Animal: NSObject, Codable { - public var className: String + public var _className: String public var color: String? = "red" - public init(className: String, color: String?) { - self.className = className + public init(_className: String, color: String?) { + self._className = _className self.color = color } + public enum CodingKeys: String, CodingKey, CaseIterable { + case _className = "className" + case color + } + } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift index ec270da89074..d0fcd4368854 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -7,9 +7,14 @@ import Foundation -public struct ApiResponse: Codable { +@objc public class ApiResponse: NSObject, Codable { public var code: Int? + public var codeNum: NSNumber? { + get { + return code as NSNumber? + } + } public var type: String? public var message: String? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift index 6c252ed475b2..9e3f3aba246a 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -7,7 +7,7 @@ import Foundation -public struct ArrayOfArrayOfNumberOnly: Codable { +@objc public class ArrayOfArrayOfNumberOnly: NSObject, Codable { public var arrayArrayNumber: [[Double]]? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift index e84eb5d65025..d287cc1563aa 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -7,7 +7,7 @@ import Foundation -public struct ArrayOfNumberOnly: Codable { +@objc public class ArrayOfNumberOnly: NSObject, Codable { public var arrayNumber: [Double]? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift index d2140933d181..dcc3e9c3dd51 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -7,7 +7,7 @@ import Foundation -public struct ArrayTest: Codable { +@objc public class ArrayTest: NSObject, Codable { public var arrayOfString: [String]? public var arrayArrayOfInteger: [[Int64]]? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift index d1b3b27616ed..80a5667445f2 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -7,7 +7,7 @@ import Foundation -public struct Capitalization: Codable { +@objc public class Capitalization: NSObject, Codable { public var smallCamel: String? public var capitalCamel: String? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift index 7d819cbcc8f4..78de5a909f54 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -7,21 +7,27 @@ import Foundation -public struct Cat: Codable { +@objc public class Cat: NSObject, Codable { - public var className: String + public var _className: String public var color: String? = "red" public var declawed: Bool? public var declawedNum: NSNumber? { get { - return declawed.map({ return NSNumber(value: $0) }) + return declawed as NSNumber? } } - public init(className: String, color: String?, declawed: Bool?) { - self.className = className + public init(_className: String, color: String?, declawed: Bool?) { + self._className = _className self.color = color self.declawed = declawed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case _className = "className" + case color + case declawed + } + } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift index a51ad0dffab1..ef8cec45aff1 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -7,9 +7,14 @@ import Foundation -public struct CatAllOf: Codable { +@objc public class CatAllOf: NSObject, Codable { public var declawed: Bool? + public var declawedNum: NSNumber? { + get { + return declawed as NSNumber? + } + } public init(declawed: Bool?) { self.declawed = declawed diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift index 620031f88c8f..0610c10c982f 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -7,9 +7,14 @@ import Foundation -public struct Category: Codable { +@objc public class Category: NSObject, Codable { public var _id: Int64? + public var _idNum: NSNumber? { + get { + return _id as NSNumber? + } + } public var name: String = "default-name" public init(_id: Int64?, name: String) { diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift index e2a7d4427a06..4197ffcaed6c 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -8,7 +8,8 @@ import Foundation /** Model for testing model with \"_class\" property */ -public struct ClassModel: Codable { + +@objc public class ClassModel: NSObject, Codable { public var _class: String? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift index 00245ca37280..517dbbba2ec2 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -7,7 +7,7 @@ import Foundation -public struct Client: Codable { +@objc public class Client: NSObject, Codable { public var client: String? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift index 492c1228008e..37733cd1f3be 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -7,16 +7,22 @@ import Foundation -public struct Dog: Codable { +@objc public class Dog: NSObject, Codable { - public var className: String + public var _className: String public var color: String? = "red" public var breed: String? - public init(className: String, color: String?, breed: String?) { - self.className = className + public init(_className: String, color: String?, breed: String?) { + self._className = _className self.color = color self.breed = breed } + public enum CodingKeys: String, CodingKey, CaseIterable { + case _className = "className" + case color + case breed + } + } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift index 7786f8acc5ae..73fd1822725c 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -7,7 +7,7 @@ import Foundation -public struct DogAllOf: Codable { +@objc public class DogAllOf: NSObject, Codable { public var breed: String? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift index 9844e7c40e35..034a58c6c0eb 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -7,7 +7,7 @@ import Foundation -public struct EnumArrays: Codable { +@objc public class EnumArrays: NSObject, Codable { public enum JustSymbol: String, Codable, CaseIterable { case greaterThanOrEqualTo = ">=" diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift index 789f583e1d77..ce3a03006097 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -7,7 +7,7 @@ import Foundation -public struct EnumTest: Codable { +@objc public class EnumTest: NSObject, Codable { public enum EnumString: String, Codable, CaseIterable { case upper = "UPPER" diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift index abf3ccffc485..7a320c177d38 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -8,7 +8,8 @@ import Foundation /** Must be named `File` for test. */ -public struct File: Codable { + +@objc public class File: NSObject, Codable { /** Test capitalization */ public var sourceURI: String? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift index 532f1457939a..a6437b4fe901 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -7,7 +7,7 @@ import Foundation -public struct FileSchemaTestClass: Codable { +@objc public class FileSchemaTestClass: NSObject, Codable { public var file: File? public var files: [File]? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift index 20bd6d103b3d..df2c46d3757b 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -7,14 +7,39 @@ import Foundation -public struct FormatTest: Codable { +@objc public class FormatTest: NSObject, Codable { public var integer: Int? + public var integerNum: NSNumber? { + get { + return integer as NSNumber? + } + } public var int32: Int? + public var int32Num: NSNumber? { + get { + return int32 as NSNumber? + } + } public var int64: Int64? + public var int64Num: NSNumber? { + get { + return int64 as NSNumber? + } + } public var number: Double public var float: Float? + public var floatNum: NSNumber? { + get { + return float as NSNumber? + } + } public var double: Double? + public var doubleNum: NSNumber? { + get { + return double as NSNumber? + } + } public var string: String? public var byte: Data public var binary: URL? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift index 906ddb06fb17..b9f5b39117d7 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -7,7 +7,7 @@ import Foundation -public struct HasOnlyReadOnly: Codable { +@objc public class HasOnlyReadOnly: NSObject, Codable { public var bar: String? public var foo: String? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift index fe13d302ccbf..826dc9e27f2b 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -7,7 +7,7 @@ import Foundation -public struct List: Codable { +@objc public class List: NSObject, Codable { public var _123list: String? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift index 4b6037f378ee..2b97660b80e8 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -7,7 +7,7 @@ import Foundation -public struct MapTest: Codable { +@objc public class MapTest: NSObject, Codable { public enum MapOfEnumString: String, Codable, CaseIterable { case upper = "UPPER" diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift index c3deb2f28932..e10adad0a7e1 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -7,7 +7,7 @@ import Foundation -public struct MixedPropertiesAndAdditionalPropertiesClass: Codable { +@objc public class MixedPropertiesAndAdditionalPropertiesClass: NSObject, Codable { public var uuid: UUID? public var dateTime: Date? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift index b61db7d6e716..1c5410f61dde 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -8,9 +8,15 @@ import Foundation /** Model for testing model name starting with number */ -public struct Model200Response: Codable { + +@objc public class Model200Response: NSObject, Codable { public var name: Int? + public var nameNum: NSNumber? { + get { + return name as NSNumber? + } + } public var _class: String? public init(name: Int?, _class: String?) { diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift index 8ab4db44b73a..06f8a2f81a3a 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -8,12 +8,23 @@ import Foundation /** Model for testing model name same as property name */ -public struct Name: Codable { + +@objc public class Name: NSObject, Codable { public var name: Int public var snakeCase: Int? + public var snakeCaseNum: NSNumber? { + get { + return snakeCase as NSNumber? + } + } public var property: String? public var _123number: Int? + public var _123numberNum: NSNumber? { + get { + return _123number as NSNumber? + } + } public init(name: Int, snakeCase: Int?, property: String?, _123number: Int?) { self.name = name diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift index 4d1dafcc2c1f..3bd9859378d8 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -7,7 +7,7 @@ import Foundation -public struct NumberOnly: Codable { +@objc public class NumberOnly: NSObject, Codable { public var justNumber: Double? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index 50f6f9bb74d5..586a4c2d55a8 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -7,7 +7,7 @@ import Foundation -public struct Order: Codable { +@objc public class Order: NSObject, Codable { public enum Status: String, Codable, CaseIterable { case placed = "placed" @@ -15,12 +15,32 @@ public struct Order: Codable { case delivered = "delivered" } public var _id: Int64? + public var _idNum: NSNumber? { + get { + return _id as NSNumber? + } + } public var petId: Int64? + public var petIdNum: NSNumber? { + get { + return petId as NSNumber? + } + } public var quantity: Int? + public var quantityNum: NSNumber? { + get { + return quantity as NSNumber? + } + } public var shipDate: Date? /** Order Status */ public var status: Status? public var complete: Bool? = false + public var completeNum: NSNumber? { + get { + return complete as NSNumber? + } + } public init(_id: Int64?, petId: Int64?, quantity: Int?, shipDate: Date?, status: Status?, complete: Bool?) { self._id = _id diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift index 18c3a024f122..434111678de7 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -7,11 +7,16 @@ import Foundation -public struct OuterComposite: Codable { +@objc public class OuterComposite: NSObject, Codable { public var myNumber: Double? public var myString: String? public var myBoolean: Bool? + public var myBooleanNum: NSNumber? { + get { + return myBoolean as NSNumber? + } + } public init(myNumber: Double?, myString: String?, myBoolean: Bool?) { self.myNumber = myNumber diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift index e769462ea707..d84079a2b48d 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -7,7 +7,7 @@ import Foundation -public struct Pet: Codable { +@objc public class Pet: NSObject, Codable { public enum Status: String, Codable, CaseIterable { case available = "available" @@ -15,6 +15,11 @@ public struct Pet: Codable { case sold = "sold" } public var _id: Int64? + public var _idNum: NSNumber? { + get { + return _id as NSNumber? + } + } public var category: Category? public var name: String public var photoUrls: [String] diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift index 0acd21fd1000..d1252433b2d8 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -7,7 +7,7 @@ import Foundation -public struct ReadOnlyFirst: Codable { +@objc public class ReadOnlyFirst: NSObject, Codable { public var bar: String? public var baz: String? diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift index c223f993a69e..4b10ac18cf0d 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -8,9 +8,15 @@ import Foundation /** Model for testing reserved words */ -public struct Return: Codable { + +@objc public class Return: NSObject, Codable { public var _return: Int? + public var _returnNum: NSNumber? { + get { + return _return as NSNumber? + } + } public init(_return: Int?) { self._return = _return diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift index 6e8650f76d8e..85e33352531d 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -7,9 +7,14 @@ import Foundation -public struct SpecialModelName: Codable { +@objc public class SpecialModelName: NSObject, Codable { public var specialPropertyName: Int64? + public var specialPropertyNameNum: NSNumber? { + get { + return specialPropertyName as NSNumber? + } + } public init(specialPropertyName: Int64?) { self.specialPropertyName = specialPropertyName diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift index 3f1237fee477..ffe9730a6fe4 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -7,7 +7,7 @@ import Foundation -public struct StringBooleanMap: Codable { +@objc public class StringBooleanMap: NSObject, Codable { public var additionalProperties: [String: Bool] = [:] @@ -35,7 +35,7 @@ public struct StringBooleanMap: Codable { // Decodable protocol methods - public init(from decoder: Decoder) throws { + public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: String.self) var nonAdditionalPropertyKeys = Set() diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift index 632eaf6fb454..88583be7f5dd 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -7,9 +7,14 @@ import Foundation -public struct Tag: Codable { +@objc public class Tag: NSObject, Codable { public var _id: Int64? + public var _idNum: NSNumber? { + get { + return _id as NSNumber? + } + } public var name: String? public init(_id: Int64?, name: String?) { diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift index a9e088808ed3..6d51f44540c0 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -7,7 +7,7 @@ import Foundation -public struct TypeHolderDefault: Codable { +@objc public class TypeHolderDefault: NSObject, Codable { public var stringItem: String = "what" public var numberItem: Double diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift index dff4083ae432..40e3a41c34d9 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -7,7 +7,7 @@ import Foundation -public struct TypeHolderExample: Codable { +@objc public class TypeHolderExample: NSObject, Codable { public var stringItem: String public var numberItem: Double diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift index 72e264d628a1..7dc3cc5954d6 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -7,9 +7,14 @@ import Foundation -public struct User: Codable { +@objc public class User: NSObject, Codable { public var _id: Int64? + public var _idNum: NSNumber? { + get { + return _id as NSNumber? + } + } public var username: String? public var firstName: String? public var lastName: String? @@ -18,6 +23,11 @@ public struct User: Codable { public var phone: String? /** User Status */ public var userStatus: Int? + public var userStatusNum: NSNumber? { + get { + return userStatus as NSNumber? + } + } public init(_id: Int64?, username: String?, firstName: String?, lastName: String?, email: String?, password: String?, phone: String?, userStatus: Int?) { self._id = _id diff --git a/samples/client/petstore/swift5/objcCompatible/docs/Animal.md b/samples/client/petstore/swift5/objcCompatible/docs/Animal.md index 69c601455cd8..5ca136c87e86 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/Animal.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/Animal.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**className** | **String** | | +**_className** | **String** | | **color** | **String** | | [optional] [default to "red"] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/typescript-axios/builds/default/api.ts b/samples/client/petstore/typescript-axios/builds/default/api.ts index 3592be77d5fb..afe31b598e69 100644 --- a/samples/client/petstore/typescript-axios/builds/default/api.ts +++ b/samples/client/petstore/typescript-axios/builds/default/api.ts @@ -290,7 +290,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -341,7 +342,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -388,7 +390,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -435,7 +438,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -478,7 +482,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -523,7 +528,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -582,7 +588,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams.toString(); return { @@ -640,7 +647,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams; return { @@ -1016,7 +1024,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1053,7 +1062,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1088,7 +1098,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1124,7 +1135,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1340,7 +1352,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1378,7 +1391,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1416,7 +1430,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1453,7 +1468,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1488,7 +1504,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1535,7 +1552,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1564,7 +1582,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1606,7 +1625,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/api.ts b/samples/client/petstore/typescript-axios/builds/es6-target/api.ts index 3592be77d5fb..afe31b598e69 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-axios/builds/es6-target/api.ts @@ -290,7 +290,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -341,7 +342,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -388,7 +390,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -435,7 +438,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -478,7 +482,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -523,7 +528,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -582,7 +588,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams.toString(); return { @@ -640,7 +647,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams; return { @@ -1016,7 +1024,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1053,7 +1062,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1088,7 +1098,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1124,7 +1135,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1340,7 +1352,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1378,7 +1391,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1416,7 +1430,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1453,7 +1468,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1488,7 +1504,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1535,7 +1552,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1564,7 +1582,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1606,7 +1625,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); diff --git a/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts b/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts index 66c69d869462..bed5634db46d 100644 --- a/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts @@ -339,7 +339,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof pet !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(pet !== undefined ? pet : {}) : (pet || ""); @@ -390,7 +391,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -437,7 +439,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -484,7 +487,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -527,7 +531,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -572,7 +577,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof pet !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(pet !== undefined ? pet : {}) : (pet || ""); @@ -631,7 +637,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams.toString(); return { @@ -689,7 +696,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams; return { @@ -1071,7 +1079,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1108,7 +1117,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1143,7 +1153,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1179,7 +1190,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof order !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(order !== undefined ? order : {}) : (order || ""); @@ -1395,7 +1407,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof user !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(user !== undefined ? user : {}) : (user || ""); @@ -1433,7 +1446,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof user !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(user !== undefined ? user : {}) : (user || ""); @@ -1471,7 +1485,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof user !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(user !== undefined ? user : {}) : (user || ""); @@ -1508,7 +1523,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1543,7 +1559,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1590,7 +1607,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1619,7 +1637,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1661,7 +1680,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof user !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(user !== undefined ? user : {}) : (user || ""); diff --git a/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts b/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts index efbe9589e12d..f9a81f26f0d7 100644 --- a/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts @@ -290,7 +290,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -341,7 +342,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -388,7 +390,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -435,7 +438,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -478,7 +482,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -523,7 +528,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -582,7 +588,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams.toString(); return { @@ -640,7 +647,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams; return { @@ -1109,7 +1117,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1146,7 +1155,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1181,7 +1191,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1217,7 +1228,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1480,7 +1492,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1518,7 +1531,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1556,7 +1570,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1593,7 +1608,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1628,7 +1644,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1675,7 +1692,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1704,7 +1722,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1746,7 +1765,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts index 0d01d428b7ae..37f48bb8801a 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts @@ -65,7 +65,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -116,7 +117,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -163,7 +165,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -210,7 +213,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -253,7 +257,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -298,7 +303,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -357,7 +363,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams.toString(); return { @@ -415,7 +422,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams; return { diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/store-api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/store-api.ts index 302b1bcd470c..e3d3a50cdf2b 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/store-api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/store-api.ts @@ -54,7 +54,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -91,7 +92,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -126,7 +128,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -162,7 +165,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/user-api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/user-api.ts index c06bbbcde132..ce60b09973bb 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/user-api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/user-api.ts @@ -55,7 +55,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -93,7 +94,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -131,7 +133,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -168,7 +171,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -203,7 +207,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -250,7 +255,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -279,7 +285,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -321,7 +328,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts index 3592be77d5fb..afe31b598e69 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts @@ -290,7 +290,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -341,7 +342,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -388,7 +390,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -435,7 +438,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -478,7 +482,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -523,7 +528,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -582,7 +588,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams.toString(); return { @@ -640,7 +647,8 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; localVarRequestOptions.data = localVarFormParams; return { @@ -1016,7 +1024,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1053,7 +1062,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1088,7 +1098,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1124,7 +1135,8 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1340,7 +1352,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1378,7 +1391,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1416,7 +1430,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); @@ -1453,7 +1468,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1488,7 +1504,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1535,7 +1552,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1564,7 +1582,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; return { url: globalImportUrl.format(localVarUrlObj), @@ -1606,7 +1625,8 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) localVarUrlObj.query = {...localVarUrlObj.query, ...localVarQueryParameter, ...options.query}; // fix override query string Detail: https://stackoverflow.com/a/7517673/1077943 delete localVarUrlObj.search; - localVarRequestOptions.headers = {...localVarHeaderParameter, ...options.headers}; + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; const needsSerialization = (typeof body !== "string") || localVarRequestOptions.headers['Content-Type'] === 'application/json'; localVarRequestOptions.data = needsSerialization ? JSON.stringify(body !== undefined ? body : {}) : (body || ""); diff --git a/samples/client/test/swift4/default/.openapi-generator/VERSION b/samples/client/test/swift4/default/.openapi-generator/VERSION index 58592f031f65..bfbf77eb7fad 100644 --- a/samples/client/test/swift4/default/.openapi-generator/VERSION +++ b/samples/client/test/swift4/default/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/test/swift4/default/TestClient.xcodeproj/project.pbxproj b/samples/client/test/swift4/default/TestClient.xcodeproj/project.pbxproj index 75c44d3d7caa..ca8fa20ff1c1 100644 --- a/samples/client/test/swift4/default/TestClient.xcodeproj/project.pbxproj +++ b/samples/client/test/swift4/default/TestClient.xcodeproj/project.pbxproj @@ -221,6 +221,8 @@ isa = PBXProject; attributes = { LastUpgradeCheck = 1020; + TargetAttributes = { + }; }; buildConfigurationList = 87FDCE50021B77EB5CF8EF08 /* Build configuration list for PBXProject "TestClient" */; compatibilityVersion = "Xcode 10.0"; diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Extensions.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Extensions.swift index 93579843a9d2..74fcfcf2ad49 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Extensions.swift @@ -80,12 +80,6 @@ extension URL: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - extension UUID: JSONEncodable { func encodeToJSON() -> Any { return self.uuidString diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/AllPrimitives.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/AllPrimitives.swift index 6ed3d6c022b9..64073972bc6e 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/AllPrimitives.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/AllPrimitives.swift @@ -8,7 +8,6 @@ import Foundation /** Object which contains lots of different primitive OpenAPI types */ - public struct AllPrimitives: Codable { public enum MyInlineStringEnum: String, Codable { diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/BaseCard.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/BaseCard.swift index 51055d85739e..2ffb3a5e1ab9 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/BaseCard.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/BaseCard.swift @@ -8,7 +8,6 @@ import Foundation /** This is a base card object which uses a 'cardType' discriminator. */ - public struct BaseCard: Codable { public var cardType: String diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ErrorInfo.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ErrorInfo.swift index a603717abe68..c2b1fcda5868 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ErrorInfo.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ErrorInfo.swift @@ -8,7 +8,6 @@ import Foundation /** Example Error object */ - public struct ErrorInfo: Codable { public var code: Int? diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/GetAllModelsResult.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/GetAllModelsResult.swift index cc3992e748af..b8cfedbe94af 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/GetAllModelsResult.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/GetAllModelsResult.swift @@ -8,7 +8,6 @@ import Foundation /** Response object containing AllPrimitives object */ - public struct GetAllModelsResult: Codable { public var myPrimitiveArray: [AllPrimitives]? diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithIntAdditionalPropertiesOnly.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithIntAdditionalPropertiesOnly.swift index 7070e5d16cbf..2878543406a4 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithIntAdditionalPropertiesOnly.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithIntAdditionalPropertiesOnly.swift @@ -8,7 +8,6 @@ import Foundation /** This is an empty model with no properties and only additionalProperties of type int32 */ - public struct ModelWithIntAdditionalPropertiesOnly: Codable { public var additionalProperties: [String: Int] = [:] diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithPropertiesAndAdditionalProperties.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithPropertiesAndAdditionalProperties.swift index c00da2ea9fe2..d8f115cb4998 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithPropertiesAndAdditionalProperties.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithPropertiesAndAdditionalProperties.swift @@ -8,7 +8,6 @@ import Foundation /** This is an empty model with no properties and only additionalProperties of type int32 */ - public struct ModelWithPropertiesAndAdditionalProperties: Codable { public var myIntegerReq: Int diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithStringAdditionalPropertiesOnly.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithStringAdditionalPropertiesOnly.swift index 81f9dede4310..fffed8885315 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithStringAdditionalPropertiesOnly.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/ModelWithStringAdditionalPropertiesOnly.swift @@ -8,7 +8,6 @@ import Foundation /** This is an empty model with no properties and only additionalProperties of type string */ - public struct ModelWithStringAdditionalPropertiesOnly: Codable { public var additionalProperties: [String: String] = [:] diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/PersonCard.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/PersonCard.swift index 0f6036276583..db1a081b275d 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/PersonCard.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/PersonCard.swift @@ -8,7 +8,6 @@ import Foundation /** This is a card object for a Person derived from BaseCard. */ - public struct PersonCard: Codable { public var cardType: String diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/PlaceCard.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/PlaceCard.swift index d29263604039..0fd94cf83640 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/PlaceCard.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/PlaceCard.swift @@ -8,7 +8,6 @@ import Foundation /** This is a card object for a Person derived from BaseCard. */ - public struct PlaceCard: Codable { public var cardType: String diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/SampleBase.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/SampleBase.swift index 42b32eee4397..7d884d88e185 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/SampleBase.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/SampleBase.swift @@ -8,7 +8,6 @@ import Foundation /** This is a base class object from which other classes will derive. */ - public struct SampleBase: Codable { public var baseClassStringProp: String? diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/SampleSubClass.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/SampleSubClass.swift index 7d4e4e9899b2..c6ffc74a959d 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/SampleSubClass.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/SampleSubClass.swift @@ -8,7 +8,6 @@ import Foundation /** This is a subclass defived from the SampleBase class. */ - public struct SampleSubClass: Codable { public var baseClassStringProp: String? diff --git a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/VariableNameTest.swift b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/VariableNameTest.swift index 6592d3f1eefd..285d86a56941 100644 --- a/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/VariableNameTest.swift +++ b/samples/client/test/swift4/default/TestClient/Classes/OpenAPIs/Models/VariableNameTest.swift @@ -8,7 +8,6 @@ import Foundation /** This object contains property names which we know will be different from their variable name. Examples of this include snake case property names and property names which are Swift 4 reserved words. */ - public struct VariableNameTest: Codable { /** This snake-case examle_name property name should be converted to a camelCase variable name like exampleName */ diff --git a/samples/client/test/swift4/default/TestClientApp/.gitignore b/samples/client/test/swift4/default/TestClientApp/.gitignore new file mode 100644 index 000000000000..0269c2f56db9 --- /dev/null +++ b/samples/client/test/swift4/default/TestClientApp/.gitignore @@ -0,0 +1,72 @@ +### https://raw.github.com/github/gitignore/7792e50daeaa6c07460484704671d1dc9f0045a7/Swift.gitignore + +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData/ + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata/ + +## Other +*.moved-aside +*.xccheckout +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +.build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +Pods/ + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output + + diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/LICENSE b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/LICENSE deleted file mode 100644 index 38a301a1db8f..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/README.md b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/README.md deleted file mode 100644 index 9fdc9c738737..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/README.md +++ /dev/null @@ -1,242 +0,0 @@ -![Alamofire: Elegant Networking in Swift](https://raw.githubusercontent.com/Alamofire/Alamofire/master/alamofire.png) - -[![Build Status](https://travis-ci.org/Alamofire/Alamofire.svg?branch=master)](https://travis-ci.org/Alamofire/Alamofire) -[![CocoaPods Compatible](https://img.shields.io/cocoapods/v/Alamofire.svg)](https://img.shields.io/cocoapods/v/Alamofire.svg) -[![Carthage Compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) -[![Platform](https://img.shields.io/cocoapods/p/Alamofire.svg?style=flat)](https://alamofire.github.io/Alamofire) -[![Twitter](https://img.shields.io/badge/twitter-@AlamofireSF-blue.svg?style=flat)](https://twitter.com/AlamofireSF) -[![Gitter](https://badges.gitter.im/Alamofire/Alamofire.svg)](https://gitter.im/Alamofire/Alamofire?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -Alamofire is an HTTP networking library written in Swift. - -- [Features](#features) -- [Component Libraries](#component-libraries) -- [Requirements](#requirements) -- [Migration Guides](#migration-guides) -- [Communication](#communication) -- [Installation](#installation) -- [Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md) - - **Intro -** [Making a Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-a-request), [Response Handling](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling), [Response Validation](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-validation), [Response Caching](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-caching) - - **HTTP -** [HTTP Methods](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-methods), [Parameter Encoding](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#parameter-encoding), [HTTP Headers](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#http-headers), [Authentication](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#authentication) - - **Large Data -** [Downloading Data to a File](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#downloading-data-to-a-file), [Uploading Data to a Server](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#uploading-data-to-a-server) - - **Tools -** [Statistical Metrics](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#statistical-metrics), [cURL Command Output](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#curl-command-output) -- [Advanced Usage](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md) - - **URL Session -** [Session Manager](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-manager), [Session Delegate](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#session-delegate), [Request](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#request) - - **Routing -** [Routing Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#routing-requests), [Adapting and Retrying Requests](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#adapting-and-retrying-requests) - - **Model Objects -** [Custom Response Serialization](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#custom-response-serialization) - - **Connection -** [Security](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#security), [Network Reachability](https://github.com/Alamofire/Alamofire/blob/master/Documentation/AdvancedUsage.md#network-reachability) -- [Open Radars](#open-radars) -- [FAQ](#faq) -- [Credits](#credits) -- [Donations](#donations) -- [License](#license) - -## Features - -- [x] Chainable Request / Response Methods -- [x] URL / JSON / plist Parameter Encoding -- [x] Upload File / Data / Stream / MultipartFormData -- [x] Download File using Request or Resume Data -- [x] Authentication with URLCredential -- [x] HTTP Response Validation -- [x] Upload and Download Progress Closures with Progress -- [x] cURL Command Output -- [x] Dynamically Adapt and Retry Requests -- [x] TLS Certificate and Public Key Pinning -- [x] Network Reachability -- [x] Comprehensive Unit and Integration Test Coverage -- [x] [Complete Documentation](https://alamofire.github.io/Alamofire) - -## Component Libraries - -In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the [Alamofire Software Foundation](https://github.com/Alamofire/Foundation) to bring additional functionality to the Alamofire ecosystem. - -- [AlamofireImage](https://github.com/Alamofire/AlamofireImage) - An image library including image response serializers, `UIImage` and `UIImageView` extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system. -- [AlamofireNetworkActivityIndicator](https://github.com/Alamofire/AlamofireNetworkActivityIndicator) - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support `URLSession` instances not managed by Alamofire. - -## Requirements - -- iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+ -- Xcode 8.3+ -- Swift 3.1+ - -## Migration Guides - -- [Alamofire 4.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%204.0%20Migration%20Guide.md) -- [Alamofire 3.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%203.0%20Migration%20Guide.md) -- [Alamofire 2.0 Migration Guide](https://github.com/Alamofire/Alamofire/blob/master/Documentation/Alamofire%202.0%20Migration%20Guide.md) - -## Communication -- If you **need help with making network requests**, use [Stack Overflow](https://stackoverflow.com/questions/tagged/alamofire) and tag `alamofire`. -- If you need to **find or understand an API**, check [our documentation](http://alamofire.github.io/Alamofire/) or [Apple's documentation for `URLSession`](https://developer.apple.com/documentation/foundation/url_loading_system), on top of which Alamofire is built. -- If you need **help with an Alamofire feature**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). -- If you'd like to **discuss Alamofire best practices**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). -- If you'd like to **discuss a feature request**, use [our forum on swift.org](https://forums.swift.org/c/related-projects/alamofire). -- If you **found a bug**, open an issue and follow the guide. The more detail the better! -- If you **want to contribute**, submit a pull request. - -## Installation - -### CocoaPods - -[CocoaPods](https://cocoapods.org) is a dependency manager for Cocoa projects. You can install it with the following command: - -```bash -$ gem install cocoapods -``` - -> CocoaPods 1.7+ is required to build Alamofire 4.9+. - -To integrate Alamofire into your Xcode project using CocoaPods, specify it in your `Podfile`: - -```ruby -source 'https://github.com/CocoaPods/Specs.git' -platform :ios, '10.0' -use_frameworks! - -target '' do - pod 'Alamofire', '~> 4.9' -end -``` - -Then, run the following command: - -```bash -$ pod install -``` - -### Carthage - -[Carthage](https://github.com/Carthage/Carthage) is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. - -You can install Carthage with [Homebrew](https://brew.sh/) using the following command: - -```bash -$ brew install carthage -``` - -To integrate Alamofire into your Xcode project using Carthage, specify it in your `Cartfile`: - -```ogdl -github "Alamofire/Alamofire" ~> 4.9 -``` - -Run `carthage update` to build the framework and drag the built `Alamofire.framework` into your Xcode project. - -### Swift Package Manager - -The [Swift Package Manager](https://swift.org/package-manager/) is a tool for automating the distribution of Swift code and is integrated into the `swift` compiler. It is in early development, but Alamofire does support its use on supported platforms. - -Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the `dependencies` value of your `Package.swift`. - -#### Swift 3 - -```swift -dependencies: [ - .Package(url: "https://github.com/Alamofire/Alamofire.git", majorVersion: 4) -] -``` - -#### Swift 4 - -```swift -dependencies: [ - .package(url: "https://github.com/Alamofire/Alamofire.git", from: "4.9.0") -] -``` - -### Manually - -If you prefer not to use any of the aforementioned dependency managers, you can integrate Alamofire into your project manually. - -#### Embedded Framework - -- Open up Terminal, `cd` into your top-level project directory, and run the following command "if" your project is not initialized as a git repository: - - ```bash - $ git init - ``` - -- Add Alamofire as a git [submodule](https://git-scm.com/docs/git-submodule) by running the following command: - - ```bash - $ git submodule add https://github.com/Alamofire/Alamofire.git - ``` - -- Open the new `Alamofire` folder, and drag the `Alamofire.xcodeproj` into the Project Navigator of your application's Xcode project. - - > It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter. - -- Select the `Alamofire.xcodeproj` in the Project Navigator and verify the deployment target matches that of your application target. -- Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar. -- In the tab bar at the top of that window, open the "General" panel. -- Click on the `+` button under the "Embedded Binaries" section. -- You will see two different `Alamofire.xcodeproj` folders each with two different versions of the `Alamofire.framework` nested inside a `Products` folder. - - > It does not matter which `Products` folder you choose from, but it does matter whether you choose the top or bottom `Alamofire.framework`. - -- Select the top `Alamofire.framework` for iOS and the bottom one for OS X. - - > You can verify which one you selected by inspecting the build log for your project. The build target for `Alamofire` will be listed as either `Alamofire iOS`, `Alamofire macOS`, `Alamofire tvOS` or `Alamofire watchOS`. - -- And that's it! - - > The `Alamofire.framework` is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device. - -## Open Radars - -The following radars have some effect on the current implementation of Alamofire. - -- [`rdar://21349340`](http://www.openradar.me/radar?id=5517037090635776) - Compiler throwing warning due to toll-free bridging issue in test case -- `rdar://26870455` - Background URL Session Configurations do not work in the simulator -- `rdar://26849668` - Some URLProtocol APIs do not properly handle `URLRequest` -- [`rdar://36082113`](http://openradar.appspot.com/radar?id=4942308441063424) - `URLSessionTaskMetrics` failing to link on watchOS 3.0+ - -## Resolved Radars - -The following radars have been resolved over time after being filed against the Alamofire project. - -- [`rdar://26761490`](http://www.openradar.me/radar?id=5010235949318144) - Swift string interpolation causing memory leak with common usage (Resolved on 9/1/17 in Xcode 9 beta 6). - -## FAQ - -### What's the origin of the name Alamofire? - -Alamofire is named after the [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html), a hybrid variant of the Bluebonnet, the official state flower of Texas. - -### What logic belongs in a Router vs. a Request Adapter? - -Simple, static data such as paths, parameters and common headers belong in the `Router`. Dynamic data such as an `Authorization` header whose value can changed based on an authentication system belongs in a `RequestAdapter`. - -The reason the dynamic data MUST be placed into the `RequestAdapter` is to support retry operations. When a `Request` is retried, the original request is not rebuilt meaning the `Router` will not be called again. The `RequestAdapter` is called again allowing the dynamic data to be updated on the original request before retrying the `Request`. - -## Credits - -Alamofire is owned and maintained by the [Alamofire Software Foundation](http://alamofire.org). You can follow them on Twitter at [@AlamofireSF](https://twitter.com/AlamofireSF) for project updates and releases. - -### Security Disclosure - -If you believe you have identified a security vulnerability with Alamofire, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker. - -## Donations - -The [ASF](https://github.com/Alamofire/Foundation#members) is looking to raise money to officially stay registered as a federal non-profit organization. -Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free. -Donating to the ASF will enable us to: - -- Pay our yearly legal fees to keep the non-profit in good status -- Pay for our mail servers to help us stay on top of all questions and security issues -- Potentially fund test servers to make it easier for us to test the edge cases -- Potentially fund developers to work on one of our projects full-time - -The community adoption of the ASF libraries has been amazing. -We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward. -With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members. -If you use any of our libraries for work, see if your employers would be interested in donating. -Any amount you can donate today to help us reach our goal would be greatly appreciated. - -[![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=W34WPEE74APJQ) - -## License - -Alamofire is released under the MIT license. [See LICENSE](https://github.com/Alamofire/Alamofire/blob/master/LICENSE) for details. diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/AFError.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/AFError.swift deleted file mode 100644 index b163f6038fae..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/AFError.swift +++ /dev/null @@ -1,460 +0,0 @@ -// -// AFError.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// `AFError` is the error type returned by Alamofire. It encompasses a few different types of errors, each with -/// their own associated reasons. -/// -/// - invalidURL: Returned when a `URLConvertible` type fails to create a valid `URL`. -/// - parameterEncodingFailed: Returned when a parameter encoding object throws an error during the encoding process. -/// - multipartEncodingFailed: Returned when some step in the multipart encoding process fails. -/// - responseValidationFailed: Returned when a `validate()` call fails. -/// - responseSerializationFailed: Returned when a response serializer encounters an error in the serialization process. -public enum AFError: Error { - /// The underlying reason the parameter encoding error occurred. - /// - /// - missingURL: The URL request did not have a URL to encode. - /// - jsonEncodingFailed: JSON serialization failed with an underlying system error during the - /// encoding process. - /// - propertyListEncodingFailed: Property list serialization failed with an underlying system error during - /// encoding process. - public enum ParameterEncodingFailureReason { - case missingURL - case jsonEncodingFailed(error: Error) - case propertyListEncodingFailed(error: Error) - } - - /// The underlying reason the multipart encoding error occurred. - /// - /// - bodyPartURLInvalid: The `fileURL` provided for reading an encodable body part isn't a - /// file URL. - /// - bodyPartFilenameInvalid: The filename of the `fileURL` provided has either an empty - /// `lastPathComponent` or `pathExtension. - /// - bodyPartFileNotReachable: The file at the `fileURL` provided was not reachable. - /// - bodyPartFileNotReachableWithError: Attempting to check the reachability of the `fileURL` provided threw - /// an error. - /// - bodyPartFileIsDirectory: The file at the `fileURL` provided is actually a directory. - /// - bodyPartFileSizeNotAvailable: The size of the file at the `fileURL` provided was not returned by - /// the system. - /// - bodyPartFileSizeQueryFailedWithError: The attempt to find the size of the file at the `fileURL` provided - /// threw an error. - /// - bodyPartInputStreamCreationFailed: An `InputStream` could not be created for the provided `fileURL`. - /// - outputStreamCreationFailed: An `OutputStream` could not be created when attempting to write the - /// encoded data to disk. - /// - outputStreamFileAlreadyExists: The encoded body data could not be writtent disk because a file - /// already exists at the provided `fileURL`. - /// - outputStreamURLInvalid: The `fileURL` provided for writing the encoded body data to disk is - /// not a file URL. - /// - outputStreamWriteFailed: The attempt to write the encoded body data to disk failed with an - /// underlying error. - /// - inputStreamReadFailed: The attempt to read an encoded body part `InputStream` failed with - /// underlying system error. - public enum MultipartEncodingFailureReason { - case bodyPartURLInvalid(url: URL) - case bodyPartFilenameInvalid(in: URL) - case bodyPartFileNotReachable(at: URL) - case bodyPartFileNotReachableWithError(atURL: URL, error: Error) - case bodyPartFileIsDirectory(at: URL) - case bodyPartFileSizeNotAvailable(at: URL) - case bodyPartFileSizeQueryFailedWithError(forURL: URL, error: Error) - case bodyPartInputStreamCreationFailed(for: URL) - - case outputStreamCreationFailed(for: URL) - case outputStreamFileAlreadyExists(at: URL) - case outputStreamURLInvalid(url: URL) - case outputStreamWriteFailed(error: Error) - - case inputStreamReadFailed(error: Error) - } - - /// The underlying reason the response validation error occurred. - /// - /// - dataFileNil: The data file containing the server response did not exist. - /// - dataFileReadFailed: The data file containing the server response could not be read. - /// - missingContentType: The response did not contain a `Content-Type` and the `acceptableContentTypes` - /// provided did not contain wildcard type. - /// - unacceptableContentType: The response `Content-Type` did not match any type in the provided - /// `acceptableContentTypes`. - /// - unacceptableStatusCode: The response status code was not acceptable. - public enum ResponseValidationFailureReason { - case dataFileNil - case dataFileReadFailed(at: URL) - case missingContentType(acceptableContentTypes: [String]) - case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) - case unacceptableStatusCode(code: Int) - } - - /// The underlying reason the response serialization error occurred. - /// - /// - inputDataNil: The server response contained no data. - /// - inputDataNilOrZeroLength: The server response contained no data or the data was zero length. - /// - inputFileNil: The file containing the server response did not exist. - /// - inputFileReadFailed: The file containing the server response could not be read. - /// - stringSerializationFailed: String serialization failed using the provided `String.Encoding`. - /// - jsonSerializationFailed: JSON serialization failed with an underlying system error. - /// - propertyListSerializationFailed: Property list serialization failed with an underlying system error. - public enum ResponseSerializationFailureReason { - case inputDataNil - case inputDataNilOrZeroLength - case inputFileNil - case inputFileReadFailed(at: URL) - case stringSerializationFailed(encoding: String.Encoding) - case jsonSerializationFailed(error: Error) - case propertyListSerializationFailed(error: Error) - } - - case invalidURL(url: URLConvertible) - case parameterEncodingFailed(reason: ParameterEncodingFailureReason) - case multipartEncodingFailed(reason: MultipartEncodingFailureReason) - case responseValidationFailed(reason: ResponseValidationFailureReason) - case responseSerializationFailed(reason: ResponseSerializationFailureReason) -} - -// MARK: - Adapt Error - -struct AdaptError: Error { - let error: Error -} - -extension Error { - var underlyingAdaptError: Error? { return (self as? AdaptError)?.error } -} - -// MARK: - Error Booleans - -extension AFError { - /// Returns whether the AFError is an invalid URL error. - public var isInvalidURLError: Bool { - if case .invalidURL = self { return true } - return false - } - - /// Returns whether the AFError is a parameter encoding error. When `true`, the `underlyingError` property will - /// contain the associated value. - public var isParameterEncodingError: Bool { - if case .parameterEncodingFailed = self { return true } - return false - } - - /// Returns whether the AFError is a multipart encoding error. When `true`, the `url` and `underlyingError` properties - /// will contain the associated values. - public var isMultipartEncodingError: Bool { - if case .multipartEncodingFailed = self { return true } - return false - } - - /// Returns whether the `AFError` is a response validation error. When `true`, the `acceptableContentTypes`, - /// `responseContentType`, and `responseCode` properties will contain the associated values. - public var isResponseValidationError: Bool { - if case .responseValidationFailed = self { return true } - return false - } - - /// Returns whether the `AFError` is a response serialization error. When `true`, the `failedStringEncoding` and - /// `underlyingError` properties will contain the associated values. - public var isResponseSerializationError: Bool { - if case .responseSerializationFailed = self { return true } - return false - } -} - -// MARK: - Convenience Properties - -extension AFError { - /// The `URLConvertible` associated with the error. - public var urlConvertible: URLConvertible? { - switch self { - case .invalidURL(let url): - return url - default: - return nil - } - } - - /// The `URL` associated with the error. - public var url: URL? { - switch self { - case .multipartEncodingFailed(let reason): - return reason.url - default: - return nil - } - } - - /// The `Error` returned by a system framework associated with a `.parameterEncodingFailed`, - /// `.multipartEncodingFailed` or `.responseSerializationFailed` error. - public var underlyingError: Error? { - switch self { - case .parameterEncodingFailed(let reason): - return reason.underlyingError - case .multipartEncodingFailed(let reason): - return reason.underlyingError - case .responseSerializationFailed(let reason): - return reason.underlyingError - default: - return nil - } - } - - /// The acceptable `Content-Type`s of a `.responseValidationFailed` error. - public var acceptableContentTypes: [String]? { - switch self { - case .responseValidationFailed(let reason): - return reason.acceptableContentTypes - default: - return nil - } - } - - /// The response `Content-Type` of a `.responseValidationFailed` error. - public var responseContentType: String? { - switch self { - case .responseValidationFailed(let reason): - return reason.responseContentType - default: - return nil - } - } - - /// The response code of a `.responseValidationFailed` error. - public var responseCode: Int? { - switch self { - case .responseValidationFailed(let reason): - return reason.responseCode - default: - return nil - } - } - - /// The `String.Encoding` associated with a failed `.stringResponse()` call. - public var failedStringEncoding: String.Encoding? { - switch self { - case .responseSerializationFailed(let reason): - return reason.failedStringEncoding - default: - return nil - } - } -} - -extension AFError.ParameterEncodingFailureReason { - var underlyingError: Error? { - switch self { - case .jsonEncodingFailed(let error), .propertyListEncodingFailed(let error): - return error - default: - return nil - } - } -} - -extension AFError.MultipartEncodingFailureReason { - var url: URL? { - switch self { - case .bodyPartURLInvalid(let url), .bodyPartFilenameInvalid(let url), .bodyPartFileNotReachable(let url), - .bodyPartFileIsDirectory(let url), .bodyPartFileSizeNotAvailable(let url), - .bodyPartInputStreamCreationFailed(let url), .outputStreamCreationFailed(let url), - .outputStreamFileAlreadyExists(let url), .outputStreamURLInvalid(let url), - .bodyPartFileNotReachableWithError(let url, _), .bodyPartFileSizeQueryFailedWithError(let url, _): - return url - default: - return nil - } - } - - var underlyingError: Error? { - switch self { - case .bodyPartFileNotReachableWithError(_, let error), .bodyPartFileSizeQueryFailedWithError(_, let error), - .outputStreamWriteFailed(let error), .inputStreamReadFailed(let error): - return error - default: - return nil - } - } -} - -extension AFError.ResponseValidationFailureReason { - var acceptableContentTypes: [String]? { - switch self { - case .missingContentType(let types), .unacceptableContentType(let types, _): - return types - default: - return nil - } - } - - var responseContentType: String? { - switch self { - case .unacceptableContentType(_, let responseType): - return responseType - default: - return nil - } - } - - var responseCode: Int? { - switch self { - case .unacceptableStatusCode(let code): - return code - default: - return nil - } - } -} - -extension AFError.ResponseSerializationFailureReason { - var failedStringEncoding: String.Encoding? { - switch self { - case .stringSerializationFailed(let encoding): - return encoding - default: - return nil - } - } - - var underlyingError: Error? { - switch self { - case .jsonSerializationFailed(let error), .propertyListSerializationFailed(let error): - return error - default: - return nil - } - } -} - -// MARK: - Error Descriptions - -extension AFError: LocalizedError { - public var errorDescription: String? { - switch self { - case .invalidURL(let url): - return "URL is not valid: \(url)" - case .parameterEncodingFailed(let reason): - return reason.localizedDescription - case .multipartEncodingFailed(let reason): - return reason.localizedDescription - case .responseValidationFailed(let reason): - return reason.localizedDescription - case .responseSerializationFailed(let reason): - return reason.localizedDescription - } - } -} - -extension AFError.ParameterEncodingFailureReason { - var localizedDescription: String { - switch self { - case .missingURL: - return "URL request to encode was missing a URL" - case .jsonEncodingFailed(let error): - return "JSON could not be encoded because of error:\n\(error.localizedDescription)" - case .propertyListEncodingFailed(let error): - return "PropertyList could not be encoded because of error:\n\(error.localizedDescription)" - } - } -} - -extension AFError.MultipartEncodingFailureReason { - var localizedDescription: String { - switch self { - case .bodyPartURLInvalid(let url): - return "The URL provided is not a file URL: \(url)" - case .bodyPartFilenameInvalid(let url): - return "The URL provided does not have a valid filename: \(url)" - case .bodyPartFileNotReachable(let url): - return "The URL provided is not reachable: \(url)" - case .bodyPartFileNotReachableWithError(let url, let error): - return ( - "The system returned an error while checking the provided URL for " + - "reachability.\nURL: \(url)\nError: \(error)" - ) - case .bodyPartFileIsDirectory(let url): - return "The URL provided is a directory: \(url)" - case .bodyPartFileSizeNotAvailable(let url): - return "Could not fetch the file size from the provided URL: \(url)" - case .bodyPartFileSizeQueryFailedWithError(let url, let error): - return ( - "The system returned an error while attempting to fetch the file size from the " + - "provided URL.\nURL: \(url)\nError: \(error)" - ) - case .bodyPartInputStreamCreationFailed(let url): - return "Failed to create an InputStream for the provided URL: \(url)" - case .outputStreamCreationFailed(let url): - return "Failed to create an OutputStream for URL: \(url)" - case .outputStreamFileAlreadyExists(let url): - return "A file already exists at the provided URL: \(url)" - case .outputStreamURLInvalid(let url): - return "The provided OutputStream URL is invalid: \(url)" - case .outputStreamWriteFailed(let error): - return "OutputStream write failed with error: \(error)" - case .inputStreamReadFailed(let error): - return "InputStream read failed with error: \(error)" - } - } -} - -extension AFError.ResponseSerializationFailureReason { - var localizedDescription: String { - switch self { - case .inputDataNil: - return "Response could not be serialized, input data was nil." - case .inputDataNilOrZeroLength: - return "Response could not be serialized, input data was nil or zero length." - case .inputFileNil: - return "Response could not be serialized, input file was nil." - case .inputFileReadFailed(let url): - return "Response could not be serialized, input file could not be read: \(url)." - case .stringSerializationFailed(let encoding): - return "String could not be serialized with encoding: \(encoding)." - case .jsonSerializationFailed(let error): - return "JSON could not be serialized because of error:\n\(error.localizedDescription)" - case .propertyListSerializationFailed(let error): - return "PropertyList could not be serialized because of error:\n\(error.localizedDescription)" - } - } -} - -extension AFError.ResponseValidationFailureReason { - var localizedDescription: String { - switch self { - case .dataFileNil: - return "Response could not be validated, data file was nil." - case .dataFileReadFailed(let url): - return "Response could not be validated, data file could not be read: \(url)." - case .missingContentType(let types): - return ( - "Response Content-Type was missing and acceptable content types " + - "(\(types.joined(separator: ","))) do not match \"*/*\"." - ) - case .unacceptableContentType(let acceptableTypes, let responseType): - return ( - "Response Content-Type \"\(responseType)\" does not match any acceptable types: " + - "\(acceptableTypes.joined(separator: ","))." - ) - case .unacceptableStatusCode(let code): - return "Response status code was unacceptable: \(code)." - } - } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Alamofire.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Alamofire.swift deleted file mode 100644 index 036e1df7cd50..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Alamofire.swift +++ /dev/null @@ -1,456 +0,0 @@ -// -// Alamofire.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Types adopting the `URLConvertible` protocol can be used to construct URLs, which are then used to construct -/// URL requests. -public protocol URLConvertible { - /// Returns a URL that conforms to RFC 2396 or throws an `Error`. - /// - /// - throws: An `Error` if the type cannot be converted to a `URL`. - /// - /// - returns: A URL or throws an `Error`. - func asURL() throws -> URL -} - -extension String: URLConvertible { - /// Returns a URL if `self` represents a valid URL string that conforms to RFC 2396 or throws an `AFError`. - /// - /// - throws: An `AFError.invalidURL` if `self` is not a valid URL string. - /// - /// - returns: A URL or throws an `AFError`. - public func asURL() throws -> URL { - guard let url = URL(string: self) else { throw AFError.invalidURL(url: self) } - return url - } -} - -extension URL: URLConvertible { - /// Returns self. - public func asURL() throws -> URL { return self } -} - -extension URLComponents: URLConvertible { - /// Returns a URL if `url` is not nil, otherwise throws an `Error`. - /// - /// - throws: An `AFError.invalidURL` if `url` is `nil`. - /// - /// - returns: A URL or throws an `AFError`. - public func asURL() throws -> URL { - guard let url = url else { throw AFError.invalidURL(url: self) } - return url - } -} - -// MARK: - - -/// Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests. -public protocol URLRequestConvertible { - /// Returns a URL request or throws if an `Error` was encountered. - /// - /// - throws: An `Error` if the underlying `URLRequest` is `nil`. - /// - /// - returns: A URL request. - func asURLRequest() throws -> URLRequest -} - -extension URLRequestConvertible { - /// The URL request. - public var urlRequest: URLRequest? { return try? asURLRequest() } -} - -extension URLRequest: URLRequestConvertible { - /// Returns a URL request or throws if an `Error` was encountered. - public func asURLRequest() throws -> URLRequest { return self } -} - -// MARK: - - -extension URLRequest { - /// Creates an instance with the specified `method`, `urlString` and `headers`. - /// - /// - parameter url: The URL. - /// - parameter method: The HTTP method. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The new `URLRequest` instance. - public init(url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders? = nil) throws { - let url = try url.asURL() - - self.init(url: url) - - httpMethod = method.rawValue - - if let headers = headers { - for (headerField, headerValue) in headers { - setValue(headerValue, forHTTPHeaderField: headerField) - } - } - } - - func adapt(using adapter: RequestAdapter?) throws -> URLRequest { - guard let adapter = adapter else { return self } - return try adapter.adapt(self) - } -} - -// MARK: - Data Request - -/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, -/// `method`, `parameters`, `encoding` and `headers`. -/// -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.get` by default. -/// - parameter parameters: The parameters. `nil` by default. -/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `DataRequest`. -@discardableResult -public func request( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil) - -> DataRequest { - return SessionManager.default.request( - url, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers - ) -} - -/// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of a URL based on the -/// specified `urlRequest`. -/// -/// - parameter urlRequest: The URL request -/// -/// - returns: The created `DataRequest`. -@discardableResult -public func request(_ urlRequest: URLRequestConvertible) -> DataRequest { - return SessionManager.default.request(urlRequest) -} - -// MARK: - Download Request - -// MARK: URL Request - -/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of the specified `url`, -/// `method`, `parameters`, `encoding`, `headers` and save them to the `destination`. -/// -/// If `destination` is not specified, the contents will remain in the temporary location determined by the -/// underlying URL session. -/// -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.get` by default. -/// - parameter parameters: The parameters. `nil` by default. -/// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. -/// -/// - returns: The created `DownloadRequest`. -@discardableResult -public func download( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - return SessionManager.default.download( - url, - method: method, - parameters: parameters, - encoding: encoding, - headers: headers, - to: destination - ) -} - -/// Creates a `DownloadRequest` using the default `SessionManager` to retrieve the contents of a URL based on the -/// specified `urlRequest` and save them to the `destination`. -/// -/// If `destination` is not specified, the contents will remain in the temporary location determined by the -/// underlying URL session. -/// -/// - parameter urlRequest: The URL request. -/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. -/// -/// - returns: The created `DownloadRequest`. -@discardableResult -public func download( - _ urlRequest: URLRequestConvertible, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - return SessionManager.default.download(urlRequest, to: destination) -} - -// MARK: Resume Data - -/// Creates a `DownloadRequest` using the default `SessionManager` from the `resumeData` produced from a -/// previous request cancellation to retrieve the contents of the original request and save them to the `destination`. -/// -/// If `destination` is not specified, the contents will remain in the temporary location determined by the -/// underlying URL session. -/// -/// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken -/// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the -/// data is written incorrectly and will always fail to resume the download. For more information about the bug and -/// possible workarounds, please refer to the following Stack Overflow post: -/// -/// - http://stackoverflow.com/a/39347461/1342462 -/// -/// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` -/// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for additional -/// information. -/// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. -/// -/// - returns: The created `DownloadRequest`. -@discardableResult -public func download( - resumingWith resumeData: Data, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - return SessionManager.default.download(resumingWith: resumeData, to: destination) -} - -// MARK: - Upload Request - -// MARK: File - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` -/// for uploading the `file`. -/// -/// - parameter file: The file to upload. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload( - _ fileURL: URL, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - return SessionManager.default.upload(fileURL, to: url, method: method, headers: headers) -} - -/// Creates a `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for -/// uploading the `file`. -/// -/// - parameter file: The file to upload. -/// - parameter urlRequest: The URL request. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { - return SessionManager.default.upload(fileURL, with: urlRequest) -} - -// MARK: Data - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` -/// for uploading the `data`. -/// -/// - parameter data: The data to upload. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload( - _ data: Data, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - return SessionManager.default.upload(data, to: url, method: method, headers: headers) -} - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for -/// uploading the `data`. -/// -/// - parameter data: The data to upload. -/// - parameter urlRequest: The URL request. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { - return SessionManager.default.upload(data, with: urlRequest) -} - -// MARK: InputStream - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `url`, `method` and `headers` -/// for uploading the `stream`. -/// -/// - parameter stream: The stream to upload. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload( - _ stream: InputStream, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - return SessionManager.default.upload(stream, to: url, method: method, headers: headers) -} - -/// Creates an `UploadRequest` using the default `SessionManager` from the specified `urlRequest` for -/// uploading the `stream`. -/// -/// - parameter urlRequest: The URL request. -/// - parameter stream: The stream to upload. -/// -/// - returns: The created `UploadRequest`. -@discardableResult -public func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { - return SessionManager.default.upload(stream, with: urlRequest) -} - -// MARK: MultipartFormData - -/// Encodes `multipartFormData` using `encodingMemoryThreshold` with the default `SessionManager` and calls -/// `encodingCompletion` with new `UploadRequest` using the `url`, `method` and `headers`. -/// -/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative -/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -/// used for larger payloads such as video content. -/// -/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory -/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, -/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -/// technique was used. -/// -/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. -/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. -/// `multipartFormDataEncodingMemoryThreshold` by default. -/// - parameter url: The URL. -/// - parameter method: The HTTP method. `.post` by default. -/// - parameter headers: The HTTP headers. `nil` by default. -/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. -public func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { - return SessionManager.default.upload( - multipartFormData: multipartFormData, - usingThreshold: encodingMemoryThreshold, - to: url, - method: method, - headers: headers, - encodingCompletion: encodingCompletion - ) -} - -/// Encodes `multipartFormData` using `encodingMemoryThreshold` and the default `SessionManager` and -/// calls `encodingCompletion` with new `UploadRequest` using the `urlRequest`. -/// -/// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative -/// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most -/// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to -/// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory -/// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be -/// used for larger payloads such as video content. -/// -/// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory -/// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, -/// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk -/// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding -/// technique was used. -/// -/// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. -/// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. -/// `multipartFormDataEncodingMemoryThreshold` by default. -/// - parameter urlRequest: The URL request. -/// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. -public func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - with urlRequest: URLRequestConvertible, - encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?) { - return SessionManager.default.upload( - multipartFormData: multipartFormData, - usingThreshold: encodingMemoryThreshold, - with: urlRequest, - encodingCompletion: encodingCompletion - ) -} - -#if !os(watchOS) - -// MARK: - Stream Request - -// MARK: Hostname and Port - -/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `hostname` -/// and `port`. -/// -/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. -/// -/// - parameter hostName: The hostname of the server to connect to. -/// - parameter port: The port of the server to connect to. -/// -/// - returns: The created `StreamRequest`. -@discardableResult -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -public func stream(withHostName hostName: String, port: Int) -> StreamRequest { - return SessionManager.default.stream(withHostName: hostName, port: port) -} - -// MARK: NetService - -/// Creates a `StreamRequest` using the default `SessionManager` for bidirectional streaming with the `netService`. -/// -/// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. -/// -/// - parameter netService: The net service used to identify the endpoint. -/// -/// - returns: The created `StreamRequest`. -@discardableResult -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -public func stream(with netService: NetService) -> StreamRequest { - return SessionManager.default.stream(with: netService) -} - -#endif diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift deleted file mode 100644 index a54673cca618..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/DispatchQueue+Alamofire.swift +++ /dev/null @@ -1,37 +0,0 @@ -// -// DispatchQueue+Alamofire.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Dispatch -import Foundation - -extension DispatchQueue { - static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) } - static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) } - static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) } - static var background: DispatchQueue { return DispatchQueue.global(qos: .background) } - - func after(_ delay: TimeInterval, execute closure: @escaping () -> Void) { - asyncAfter(deadline: .now() + delay, execute: closure) - } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/MultipartFormData.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/MultipartFormData.swift deleted file mode 100644 index 7df468a011c8..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/MultipartFormData.swift +++ /dev/null @@ -1,578 +0,0 @@ -// -// MultipartFormData.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -#if os(iOS) || os(watchOS) || os(tvOS) -import MobileCoreServices -#elseif os(macOS) -import CoreServices -#endif - -/// Constructs `multipart/form-data` for uploads within an HTTP or HTTPS body. There are currently two ways to encode -/// multipart form data. The first way is to encode the data directly in memory. This is very efficient, but can lead -/// to memory issues if the dataset is too large. The second way is designed for larger datasets and will write all the -/// data to a single file on disk with all the proper boundary segmentation. The second approach MUST be used for -/// larger datasets such as video content, otherwise your app may run out of memory when trying to encode the dataset. -/// -/// For more information on `multipart/form-data` in general, please refer to the RFC-2388 and RFC-2045 specs as well -/// and the w3 form documentation. -/// -/// - https://www.ietf.org/rfc/rfc2388.txt -/// - https://www.ietf.org/rfc/rfc2045.txt -/// - https://www.w3.org/TR/html401/interact/forms.html#h-17.13 -open class MultipartFormData { - - // MARK: - Helper Types - - struct EncodingCharacters { - static let crlf = "\r\n" - } - - struct BoundaryGenerator { - enum BoundaryType { - case initial, encapsulated, final - } - - static func randomBoundary() -> String { - return String(format: "alamofire.boundary.%08x%08x", arc4random(), arc4random()) - } - - static func boundaryData(forBoundaryType boundaryType: BoundaryType, boundary: String) -> Data { - let boundaryText: String - - switch boundaryType { - case .initial: - boundaryText = "--\(boundary)\(EncodingCharacters.crlf)" - case .encapsulated: - boundaryText = "\(EncodingCharacters.crlf)--\(boundary)\(EncodingCharacters.crlf)" - case .final: - boundaryText = "\(EncodingCharacters.crlf)--\(boundary)--\(EncodingCharacters.crlf)" - } - - return boundaryText.data(using: String.Encoding.utf8, allowLossyConversion: false)! - } - } - - class BodyPart { - let headers: HTTPHeaders - let bodyStream: InputStream - let bodyContentLength: UInt64 - var hasInitialBoundary = false - var hasFinalBoundary = false - - init(headers: HTTPHeaders, bodyStream: InputStream, bodyContentLength: UInt64) { - self.headers = headers - self.bodyStream = bodyStream - self.bodyContentLength = bodyContentLength - } - } - - // MARK: - Properties - - /// The `Content-Type` header value containing the boundary used to generate the `multipart/form-data`. - open lazy var contentType: String = "multipart/form-data; boundary=\(self.boundary)" - - /// The content length of all body parts used to generate the `multipart/form-data` not including the boundaries. - public var contentLength: UInt64 { return bodyParts.reduce(0) { $0 + $1.bodyContentLength } } - - /// The boundary used to separate the body parts in the encoded form data. - public var boundary: String - - private var bodyParts: [BodyPart] - private var bodyPartError: AFError? - private let streamBufferSize: Int - - // MARK: - Lifecycle - - /// Creates a multipart form data object. - /// - /// - returns: The multipart form data object. - public init() { - self.boundary = BoundaryGenerator.randomBoundary() - self.bodyParts = [] - - /// - /// The optimal read/write buffer size in bytes for input and output streams is 1024 (1KB). For more - /// information, please refer to the following article: - /// - https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Streams/Articles/ReadingInputStreams.html - /// - - self.streamBufferSize = 1024 - } - - // MARK: - Body Parts - - /// Creates a body part from the data and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - /// - Encoded data - /// - Multipart form boundary - /// - /// - parameter data: The data to encode into the multipart form data. - /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - public func append(_ data: Data, withName name: String) { - let headers = contentHeaders(withName: name) - let stream = InputStream(data: data) - let length = UInt64(data.count) - - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part from the data and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}` (HTTP Header) - /// - `Content-Type: #{generated mimeType}` (HTTP Header) - /// - Encoded data - /// - Multipart form boundary - /// - /// - parameter data: The data to encode into the multipart form data. - /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The MIME type to associate with the data content type in the `Content-Type` HTTP header. - public func append(_ data: Data, withName name: String, mimeType: String) { - let headers = contentHeaders(withName: name, mimeType: mimeType) - let stream = InputStream(data: data) - let length = UInt64(data.count) - - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part from the data and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - /// - `Content-Type: #{mimeType}` (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// - parameter data: The data to encode into the multipart form data. - /// - parameter name: The name to associate with the data in the `Content-Disposition` HTTP header. - /// - parameter fileName: The filename to associate with the data in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The MIME type to associate with the data in the `Content-Type` HTTP header. - public func append(_ data: Data, withName name: String, fileName: String, mimeType: String) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - let stream = InputStream(data: data) - let length = UInt64(data.count) - - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part from the file and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{generated filename}` (HTTP Header) - /// - `Content-Type: #{generated mimeType}` (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// The filename in the `Content-Disposition` HTTP header is generated from the last path component of the - /// `fileURL`. The `Content-Type` HTTP header MIME type is generated by mapping the `fileURL` extension to the - /// system associated MIME type. - /// - /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. - public func append(_ fileURL: URL, withName name: String) { - let fileName = fileURL.lastPathComponent - let pathExtension = fileURL.pathExtension - - if !fileName.isEmpty && !pathExtension.isEmpty { - let mime = mimeType(forPathExtension: pathExtension) - append(fileURL, withName: name, fileName: fileName, mimeType: mime) - } else { - setBodyPartError(withReason: .bodyPartFilenameInvalid(in: fileURL)) - } - } - - /// Creates a body part from the file and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - Content-Disposition: form-data; name=#{name}; filename=#{filename} (HTTP Header) - /// - Content-Type: #{mimeType} (HTTP Header) - /// - Encoded file data - /// - Multipart form boundary - /// - /// - parameter fileURL: The URL of the file whose content will be encoded into the multipart form data. - /// - parameter name: The name to associate with the file content in the `Content-Disposition` HTTP header. - /// - parameter fileName: The filename to associate with the file content in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The MIME type to associate with the file content in the `Content-Type` HTTP header. - public func append(_ fileURL: URL, withName name: String, fileName: String, mimeType: String) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - - //============================================================ - // Check 1 - is file URL? - //============================================================ - - guard fileURL.isFileURL else { - setBodyPartError(withReason: .bodyPartURLInvalid(url: fileURL)) - return - } - - //============================================================ - // Check 2 - is file URL reachable? - //============================================================ - - do { - let isReachable = try fileURL.checkPromisedItemIsReachable() - guard isReachable else { - setBodyPartError(withReason: .bodyPartFileNotReachable(at: fileURL)) - return - } - } catch { - setBodyPartError(withReason: .bodyPartFileNotReachableWithError(atURL: fileURL, error: error)) - return - } - - //============================================================ - // Check 3 - is file URL a directory? - //============================================================ - - var isDirectory: ObjCBool = false - let path = fileURL.path - - guard FileManager.default.fileExists(atPath: path, isDirectory: &isDirectory) && !isDirectory.boolValue else { - setBodyPartError(withReason: .bodyPartFileIsDirectory(at: fileURL)) - return - } - - //============================================================ - // Check 4 - can the file size be extracted? - //============================================================ - - let bodyContentLength: UInt64 - - do { - guard let fileSize = try FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber else { - setBodyPartError(withReason: .bodyPartFileSizeNotAvailable(at: fileURL)) - return - } - - bodyContentLength = fileSize.uint64Value - } catch { - setBodyPartError(withReason: .bodyPartFileSizeQueryFailedWithError(forURL: fileURL, error: error)) - return - } - - //============================================================ - // Check 5 - can a stream be created from file URL? - //============================================================ - - guard let stream = InputStream(url: fileURL) else { - setBodyPartError(withReason: .bodyPartInputStreamCreationFailed(for: fileURL)) - return - } - - append(stream, withLength: bodyContentLength, headers: headers) - } - - /// Creates a body part from the stream and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - `Content-Disposition: form-data; name=#{name}; filename=#{filename}` (HTTP Header) - /// - `Content-Type: #{mimeType}` (HTTP Header) - /// - Encoded stream data - /// - Multipart form boundary - /// - /// - parameter stream: The input stream to encode in the multipart form data. - /// - parameter length: The content length of the stream. - /// - parameter name: The name to associate with the stream content in the `Content-Disposition` HTTP header. - /// - parameter fileName: The filename to associate with the stream content in the `Content-Disposition` HTTP header. - /// - parameter mimeType: The MIME type to associate with the stream content in the `Content-Type` HTTP header. - public func append( - _ stream: InputStream, - withLength length: UInt64, - name: String, - fileName: String, - mimeType: String) { - let headers = contentHeaders(withName: name, fileName: fileName, mimeType: mimeType) - append(stream, withLength: length, headers: headers) - } - - /// Creates a body part with the headers, stream and length and appends it to the multipart form data object. - /// - /// The body part data will be encoded using the following format: - /// - /// - HTTP headers - /// - Encoded stream data - /// - Multipart form boundary - /// - /// - parameter stream: The input stream to encode in the multipart form data. - /// - parameter length: The content length of the stream. - /// - parameter headers: The HTTP headers for the body part. - public func append(_ stream: InputStream, withLength length: UInt64, headers: HTTPHeaders) { - let bodyPart = BodyPart(headers: headers, bodyStream: stream, bodyContentLength: length) - bodyParts.append(bodyPart) - } - - // MARK: - Data Encoding - - /// Encodes all the appended body parts into a single `Data` value. - /// - /// It is important to note that this method will load all the appended body parts into memory all at the same - /// time. This method should only be used when the encoded data will have a small memory footprint. For large data - /// cases, please use the `writeEncodedDataToDisk(fileURL:completionHandler:)` method. - /// - /// - throws: An `AFError` if encoding encounters an error. - /// - /// - returns: The encoded `Data` if encoding is successful. - public func encode() throws -> Data { - if let bodyPartError = bodyPartError { - throw bodyPartError - } - - var encoded = Data() - - bodyParts.first?.hasInitialBoundary = true - bodyParts.last?.hasFinalBoundary = true - - for bodyPart in bodyParts { - let encodedData = try encode(bodyPart) - encoded.append(encodedData) - } - - return encoded - } - - /// Writes the appended body parts into the given file URL. - /// - /// This process is facilitated by reading and writing with input and output streams, respectively. Thus, - /// this approach is very memory efficient and should be used for large body part data. - /// - /// - parameter fileURL: The file URL to write the multipart form data into. - /// - /// - throws: An `AFError` if encoding encounters an error. - public func writeEncodedData(to fileURL: URL) throws { - if let bodyPartError = bodyPartError { - throw bodyPartError - } - - if FileManager.default.fileExists(atPath: fileURL.path) { - throw AFError.multipartEncodingFailed(reason: .outputStreamFileAlreadyExists(at: fileURL)) - } else if !fileURL.isFileURL { - throw AFError.multipartEncodingFailed(reason: .outputStreamURLInvalid(url: fileURL)) - } - - guard let outputStream = OutputStream(url: fileURL, append: false) else { - throw AFError.multipartEncodingFailed(reason: .outputStreamCreationFailed(for: fileURL)) - } - - outputStream.open() - defer { outputStream.close() } - - self.bodyParts.first?.hasInitialBoundary = true - self.bodyParts.last?.hasFinalBoundary = true - - for bodyPart in self.bodyParts { - try write(bodyPart, to: outputStream) - } - } - - // MARK: - Private - Body Part Encoding - - private func encode(_ bodyPart: BodyPart) throws -> Data { - var encoded = Data() - - let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() - encoded.append(initialData) - - let headerData = encodeHeaders(for: bodyPart) - encoded.append(headerData) - - let bodyStreamData = try encodeBodyStream(for: bodyPart) - encoded.append(bodyStreamData) - - if bodyPart.hasFinalBoundary { - encoded.append(finalBoundaryData()) - } - - return encoded - } - - private func encodeHeaders(for bodyPart: BodyPart) -> Data { - var headerText = "" - - for (key, value) in bodyPart.headers { - headerText += "\(key): \(value)\(EncodingCharacters.crlf)" - } - headerText += EncodingCharacters.crlf - - return headerText.data(using: String.Encoding.utf8, allowLossyConversion: false)! - } - - private func encodeBodyStream(for bodyPart: BodyPart) throws -> Data { - let inputStream = bodyPart.bodyStream - inputStream.open() - defer { inputStream.close() } - - var encoded = Data() - - while inputStream.hasBytesAvailable { - var buffer = [UInt8](repeating: 0, count: streamBufferSize) - let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) - - if let error = inputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: error)) - } - - if bytesRead > 0 { - encoded.append(buffer, count: bytesRead) - } else { - break - } - } - - return encoded - } - - // MARK: - Private - Writing Body Part to Output Stream - - private func write(_ bodyPart: BodyPart, to outputStream: OutputStream) throws { - try writeInitialBoundaryData(for: bodyPart, to: outputStream) - try writeHeaderData(for: bodyPart, to: outputStream) - try writeBodyStream(for: bodyPart, to: outputStream) - try writeFinalBoundaryData(for: bodyPart, to: outputStream) - } - - private func writeInitialBoundaryData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let initialData = bodyPart.hasInitialBoundary ? initialBoundaryData() : encapsulatedBoundaryData() - return try write(initialData, to: outputStream) - } - - private func writeHeaderData(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let headerData = encodeHeaders(for: bodyPart) - return try write(headerData, to: outputStream) - } - - private func writeBodyStream(for bodyPart: BodyPart, to outputStream: OutputStream) throws { - let inputStream = bodyPart.bodyStream - - inputStream.open() - defer { inputStream.close() } - - while inputStream.hasBytesAvailable { - var buffer = [UInt8](repeating: 0, count: streamBufferSize) - let bytesRead = inputStream.read(&buffer, maxLength: streamBufferSize) - - if let streamError = inputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .inputStreamReadFailed(error: streamError)) - } - - if bytesRead > 0 { - if buffer.count != bytesRead { - buffer = Array(buffer[0.. 0, outputStream.hasSpaceAvailable { - let bytesWritten = outputStream.write(buffer, maxLength: bytesToWrite) - - if let error = outputStream.streamError { - throw AFError.multipartEncodingFailed(reason: .outputStreamWriteFailed(error: error)) - } - - bytesToWrite -= bytesWritten - - if bytesToWrite > 0 { - buffer = Array(buffer[bytesWritten.. String { - if - let id = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as CFString, nil)?.takeRetainedValue(), - let contentType = UTTypeCopyPreferredTagWithClass(id, kUTTagClassMIMEType)?.takeRetainedValue() - { - return contentType as String - } - - return "application/octet-stream" - } - - // MARK: - Private - Content Headers - - private func contentHeaders(withName name: String, fileName: String? = nil, mimeType: String? = nil) -> [String: String] { - var disposition = "form-data; name=\"\(name)\"" - if let fileName = fileName { disposition += "; filename=\"\(fileName)\"" } - - var headers = ["Content-Disposition": disposition] - if let mimeType = mimeType { headers["Content-Type"] = mimeType } - - return headers - } - - // MARK: - Private - Boundary Encoding - - private func initialBoundaryData() -> Data { - return BoundaryGenerator.boundaryData(forBoundaryType: .initial, boundary: boundary) - } - - private func encapsulatedBoundaryData() -> Data { - return BoundaryGenerator.boundaryData(forBoundaryType: .encapsulated, boundary: boundary) - } - - private func finalBoundaryData() -> Data { - return BoundaryGenerator.boundaryData(forBoundaryType: .final, boundary: boundary) - } - - // MARK: - Private - Errors - - private func setBodyPartError(withReason reason: AFError.MultipartEncodingFailureReason) { - guard bodyPartError == nil else { return } - bodyPartError = AFError.multipartEncodingFailed(reason: reason) - } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/NetworkReachabilityManager.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/NetworkReachabilityManager.swift deleted file mode 100644 index fa0647934f67..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/NetworkReachabilityManager.swift +++ /dev/null @@ -1,236 +0,0 @@ -// -// NetworkReachabilityManager.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -#if !os(watchOS) - -import Foundation -import SystemConfiguration - -/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and -/// WiFi network interfaces. -/// -/// Reachability can be used to determine background information about why a network operation failed, or to retry -/// network requests when a connection is established. It should not be used to prevent a user from initiating a network -/// request, as it's possible that an initial request may be required to establish reachability. -open class NetworkReachabilityManager { - /// Defines the various states of network reachability. - /// - /// - unknown: It is unknown whether the network is reachable. - /// - notReachable: The network is not reachable. - /// - reachable: The network is reachable. - public enum NetworkReachabilityStatus { - case unknown - case notReachable - case reachable(ConnectionType) - } - - /// Defines the various connection types detected by reachability flags. - /// - /// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi. - /// - wwan: The connection type is a WWAN connection. - public enum ConnectionType { - case ethernetOrWiFi - case wwan - } - - /// A closure executed when the network reachability status changes. The closure takes a single argument: the - /// network reachability status. - public typealias Listener = (NetworkReachabilityStatus) -> Void - - // MARK: - Properties - - /// Whether the network is currently reachable. - open var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi } - - /// Whether the network is currently reachable over the WWAN interface. - open var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) } - - /// Whether the network is currently reachable over Ethernet or WiFi interface. - open var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) } - - /// The current network reachability status. - open var networkReachabilityStatus: NetworkReachabilityStatus { - guard let flags = self.flags else { return .unknown } - return networkReachabilityStatusForFlags(flags) - } - - /// The dispatch queue to execute the `listener` closure on. - open var listenerQueue: DispatchQueue = DispatchQueue.main - - /// A closure executed when the network reachability status changes. - open var listener: Listener? - - open var flags: SCNetworkReachabilityFlags? { - var flags = SCNetworkReachabilityFlags() - - if SCNetworkReachabilityGetFlags(reachability, &flags) { - return flags - } - - return nil - } - - private let reachability: SCNetworkReachability - open var previousFlags: SCNetworkReachabilityFlags - - // MARK: - Initialization - - /// Creates a `NetworkReachabilityManager` instance with the specified host. - /// - /// - parameter host: The host used to evaluate network reachability. - /// - /// - returns: The new `NetworkReachabilityManager` instance. - public convenience init?(host: String) { - guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil } - self.init(reachability: reachability) - } - - /// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0. - /// - /// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing - /// status of the device, both IPv4 and IPv6. - /// - /// - returns: The new `NetworkReachabilityManager` instance. - public convenience init?() { - var address = sockaddr_in() - address.sin_len = UInt8(MemoryLayout.size) - address.sin_family = sa_family_t(AF_INET) - - guard let reachability = withUnsafePointer(to: &address, { pointer in - return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout.size) { - return SCNetworkReachabilityCreateWithAddress(nil, $0) - } - }) else { return nil } - - self.init(reachability: reachability) - } - - private init(reachability: SCNetworkReachability) { - self.reachability = reachability - - // Set the previous flags to an unreserved value to represent unknown status - self.previousFlags = SCNetworkReachabilityFlags(rawValue: 1 << 30) - } - - deinit { - stopListening() - } - - // MARK: - Listening - - /// Starts listening for changes in network reachability status. - /// - /// - returns: `true` if listening was started successfully, `false` otherwise. - @discardableResult - open func startListening() -> Bool { - var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) - context.info = Unmanaged.passUnretained(self).toOpaque() - - let callbackEnabled = SCNetworkReachabilitySetCallback( - reachability, { (_, flags, info) in - let reachability = Unmanaged.fromOpaque(info!).takeUnretainedValue() - reachability.notifyListener(flags) - }, - &context - ) - - let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue) - - listenerQueue.async { - self.previousFlags = SCNetworkReachabilityFlags(rawValue: 1 << 30) - - guard let flags = self.flags else { return } - - self.notifyListener(flags) - } - - return callbackEnabled && queueEnabled - } - - /// Stops listening for changes in network reachability status. - open func stopListening() { - SCNetworkReachabilitySetCallback(reachability, nil, nil) - SCNetworkReachabilitySetDispatchQueue(reachability, nil) - } - - // MARK: - Internal - Listener Notification - - func notifyListener(_ flags: SCNetworkReachabilityFlags) { - guard previousFlags != flags else { return } - previousFlags = flags - - listener?(networkReachabilityStatusForFlags(flags)) - } - - // MARK: - Internal - Network Reachability Status - - func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus { - guard isNetworkReachable(with: flags) else { return .notReachable } - - var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi) - - #if os(iOS) - if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) } - #endif - - return networkStatus - } - - func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool { - let isReachable = flags.contains(.reachable) - let needsConnection = flags.contains(.connectionRequired) - let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) - let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) - - return isReachable && (!needsConnection || canConnectWithoutUserInteraction) - } -} - -// MARK: - - -extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {} - -/// Returns whether the two network reachability status values are equal. -/// -/// - parameter lhs: The left-hand side value to compare. -/// - parameter rhs: The right-hand side value to compare. -/// -/// - returns: `true` if the two values are equal, `false` otherwise. -public func ==( - lhs: NetworkReachabilityManager.NetworkReachabilityStatus, - rhs: NetworkReachabilityManager.NetworkReachabilityStatus) - -> Bool { - switch (lhs, rhs) { - case (.unknown, .unknown): - return true - case (.notReachable, .notReachable): - return true - case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)): - return lhsConnectionType == rhsConnectionType - default: - return false - } -} - -#endif diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Notifications.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Notifications.swift deleted file mode 100644 index e1ac31bf327e..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Notifications.swift +++ /dev/null @@ -1,55 +0,0 @@ -// -// Notifications.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension Notification.Name { - /// Used as a namespace for all `URLSessionTask` related notifications. - public struct Task { - /// Posted when a `URLSessionTask` is resumed. The notification `object` contains the resumed `URLSessionTask`. - public static let DidResume = Notification.Name(rawValue: "org.alamofire.notification.name.task.didResume") - - /// Posted when a `URLSessionTask` is suspended. The notification `object` contains the suspended `URLSessionTask`. - public static let DidSuspend = Notification.Name(rawValue: "org.alamofire.notification.name.task.didSuspend") - - /// Posted when a `URLSessionTask` is cancelled. The notification `object` contains the cancelled `URLSessionTask`. - public static let DidCancel = Notification.Name(rawValue: "org.alamofire.notification.name.task.didCancel") - - /// Posted when a `URLSessionTask` is completed. The notification `object` contains the completed `URLSessionTask`. - public static let DidComplete = Notification.Name(rawValue: "org.alamofire.notification.name.task.didComplete") - } -} - -// MARK: - - -extension Notification { - /// Used as a namespace for all `Notification` user info dictionary keys. - public struct Key { - /// User info dictionary key representing the `URLSessionTask` associated with the notification. - public static let Task = "org.alamofire.notification.key.task" - - /// User info dictionary key representing the responseData associated with the notification. - public static let ResponseData = "org.alamofire.notification.key.responseData" - } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/ParameterEncoding.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/ParameterEncoding.swift deleted file mode 100644 index dc8e75e847df..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/ParameterEncoding.swift +++ /dev/null @@ -1,482 +0,0 @@ -// -// ParameterEncoding.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// HTTP method definitions. -/// -/// See https://tools.ietf.org/html/rfc7231#section-4.3 -public enum HTTPMethod: String { - case options = "OPTIONS" - case get = "GET" - case head = "HEAD" - case post = "POST" - case put = "PUT" - case patch = "PATCH" - case delete = "DELETE" - case trace = "TRACE" - case connect = "CONNECT" -} - -// MARK: - - -/// A dictionary of parameters to apply to a `URLRequest`. -public typealias Parameters = [String: Any] - -/// A type used to define how a set of parameters are applied to a `URLRequest`. -public protocol ParameterEncoding { - /// Creates a URL request by encoding parameters and applying them onto an existing request. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. - /// - /// - throws: An `AFError.parameterEncodingFailed` error if encoding fails. - /// - /// - returns: The encoded request. - func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest -} - -// MARK: - - -/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP -/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as -/// the HTTP body depends on the destination of the encoding. -/// -/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to -/// `application/x-www-form-urlencoded; charset=utf-8`. -/// -/// There is no published specification for how to encode collection types. By default the convention of appending -/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for -/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the -/// square brackets appended to array keys. -/// -/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode -/// `true` as 1 and `false` as 0. -public struct URLEncoding: ParameterEncoding { - - // MARK: Helper Types - - /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the - /// resulting URL request. - /// - /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` - /// requests and sets as the HTTP body for requests with any other HTTP method. - /// - queryString: Sets or appends encoded query string result to existing query string. - /// - httpBody: Sets encoded query string result as the HTTP body of the URL request. - public enum Destination { - case methodDependent, queryString, httpBody - } - - /// Configures how `Array` parameters are encoded. - /// - /// - brackets: An empty set of square brackets is appended to the key for every value. - /// This is the default behavior. - /// - noBrackets: No brackets are appended. The key is encoded as is. - public enum ArrayEncoding { - case brackets, noBrackets - - func encode(key: String) -> String { - switch self { - case .brackets: - return "\(key)[]" - case .noBrackets: - return key - } - } - } - - /// Configures how `Bool` parameters are encoded. - /// - /// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior. - /// - literal: Encode `true` and `false` as string literals. - public enum BoolEncoding { - case numeric, literal - - func encode(value: Bool) -> String { - switch self { - case .numeric: - return value ? "1" : "0" - case .literal: - return value ? "true" : "false" - } - } - } - - // MARK: Properties - - /// Returns a default `URLEncoding` instance. - public static var `default`: URLEncoding { return URLEncoding() } - - /// Returns a `URLEncoding` instance with a `.methodDependent` destination. - public static var methodDependent: URLEncoding { return URLEncoding() } - - /// Returns a `URLEncoding` instance with a `.queryString` destination. - public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) } - - /// Returns a `URLEncoding` instance with an `.httpBody` destination. - public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) } - - /// The destination defining where the encoded query string is to be applied to the URL request. - public let destination: Destination - - /// The encoding to use for `Array` parameters. - public let arrayEncoding: ArrayEncoding - - /// The encoding to use for `Bool` parameters. - public let boolEncoding: BoolEncoding - - // MARK: Initialization - - /// Creates a `URLEncoding` instance using the specified destination. - /// - /// - parameter destination: The destination defining where the encoded query string is to be applied. - /// - parameter arrayEncoding: The encoding to use for `Array` parameters. - /// - parameter boolEncoding: The encoding to use for `Bool` parameters. - /// - /// - returns: The new `URLEncoding` instance. - public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) { - self.destination = destination - self.arrayEncoding = arrayEncoding - self.boolEncoding = boolEncoding - } - - // MARK: Encoding - - /// Creates a URL request by encoding parameters and applying them onto an existing request. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. - /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - returns: The encoded request. - public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let parameters = parameters else { return urlRequest } - - if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { - guard let url = urlRequest.url else { - throw AFError.parameterEncodingFailed(reason: .missingURL) - } - - if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { - let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) - urlComponents.percentEncodedQuery = percentEncodedQuery - urlRequest.url = urlComponents.url - } - } else { - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) - } - - return urlRequest - } - - /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. - /// - /// - parameter key: The key of the query component. - /// - parameter value: The value of the query component. - /// - /// - returns: The percent-escaped, URL encoded query string components. - public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { - var components: [(String, String)] = [] - - if let dictionary = value as? [String: Any] { - for (nestedKey, value) in dictionary { - components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) - } - } else if let array = value as? [Any] { - for value in array { - components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value) - } - } else if let value = value as? NSNumber { - if value.isBool { - components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue)))) - } else { - components.append((escape(key), escape("\(value)"))) - } - } else if let bool = value as? Bool { - components.append((escape(key), escape(boolEncoding.encode(value: bool)))) - } else { - components.append((escape(key), escape("\(value)"))) - } - - return components - } - - /// Returns a percent-escaped string following RFC 3986 for a query string key or value. - /// - /// RFC 3986 states that the following characters are "reserved" characters. - /// - /// - General Delimiters: ":", "#", "[", "]", "@", "?", "/" - /// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "=" - /// - /// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow - /// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/" - /// should be percent-escaped in the query string. - /// - /// - parameter string: The string to be percent-escaped. - /// - /// - returns: The percent-escaped string. - public func escape(_ string: String) -> String { - let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 - let subDelimitersToEncode = "!$&'()*+,;=" - - var allowedCharacterSet = CharacterSet.urlQueryAllowed - allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)") - - var escaped = "" - - //========================================================================================================== - // - // Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few - // hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no - // longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more - // info, please refer to: - // - // - https://github.com/Alamofire/Alamofire/issues/206 - // - //========================================================================================================== - - if #available(iOS 8.3, *) { - escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string - } else { - let batchSize = 50 - var index = string.startIndex - - while index != string.endIndex { - let startIndex = index - let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex - let range = startIndex.. String { - var components: [(String, String)] = [] - - for key in parameters.keys.sorted(by: <) { - let value = parameters[key]! - components += queryComponents(fromKey: key, value: value) - } - return components.map { "\($0)=\($1)" }.joined(separator: "&") - } - - private func encodesParametersInURL(with method: HTTPMethod) -> Bool { - switch destination { - case .queryString: - return true - case .httpBody: - return false - default: - break - } - - switch method { - case .get, .head, .delete: - return true - default: - return false - } - } -} - -// MARK: - - -/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the -/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. -public struct JSONEncoding: ParameterEncoding { - - // MARK: Properties - - /// Returns a `JSONEncoding` instance with default writing options. - public static var `default`: JSONEncoding { return JSONEncoding() } - - /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. - public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) } - - /// The options for writing the parameters as JSON data. - public let options: JSONSerialization.WritingOptions - - // MARK: Initialization - - /// Creates a `JSONEncoding` instance using the specified options. - /// - /// - parameter options: The options for writing the parameters as JSON data. - /// - /// - returns: The new `JSONEncoding` instance. - public init(options: JSONSerialization.WritingOptions = []) { - self.options = options - } - - // MARK: Encoding - - /// Creates a URL request by encoding parameters and applying them onto an existing request. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. - /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - returns: The encoded request. - public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let parameters = parameters else { return urlRequest } - - do { - let data = try JSONSerialization.data(withJSONObject: parameters, options: options) - - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = data - } catch { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) - } - - return urlRequest - } - - /// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body. - /// - /// - parameter urlRequest: The request to apply the JSON object to. - /// - parameter jsonObject: The JSON object to apply to the request. - /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - returns: The encoded request. - public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let jsonObject = jsonObject else { return urlRequest } - - do { - let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) - - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = data - } catch { - throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) - } - - return urlRequest - } -} - -// MARK: - - -/// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the -/// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header -/// field of an encoded request is set to `application/x-plist`. -public struct PropertyListEncoding: ParameterEncoding { - - // MARK: Properties - - /// Returns a default `PropertyListEncoding` instance. - public static var `default`: PropertyListEncoding { return PropertyListEncoding() } - - /// Returns a `PropertyListEncoding` instance with xml formatting and default writing options. - public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) } - - /// Returns a `PropertyListEncoding` instance with binary formatting and default writing options. - public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) } - - /// The property list serialization format. - public let format: PropertyListSerialization.PropertyListFormat - - /// The options for writing the parameters as plist data. - public let options: PropertyListSerialization.WriteOptions - - // MARK: Initialization - - /// Creates a `PropertyListEncoding` instance using the specified format and options. - /// - /// - parameter format: The property list serialization format. - /// - parameter options: The options for writing the parameters as plist data. - /// - /// - returns: The new `PropertyListEncoding` instance. - public init( - format: PropertyListSerialization.PropertyListFormat = .xml, - options: PropertyListSerialization.WriteOptions = 0) { - self.format = format - self.options = options - } - - // MARK: Encoding - - /// Creates a URL request by encoding parameters and applying them onto an existing request. - /// - /// - parameter urlRequest: The request to have parameters applied. - /// - parameter parameters: The parameters to apply. - /// - /// - throws: An `Error` if the encoding process encounters an error. - /// - /// - returns: The encoded request. - public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { - var urlRequest = try urlRequest.asURLRequest() - - guard let parameters = parameters else { return urlRequest } - - do { - let data = try PropertyListSerialization.data( - fromPropertyList: parameters, - format: format, - options: options - ) - - if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { - urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type") - } - - urlRequest.httpBody = data - } catch { - throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error)) - } - - return urlRequest - } -} - -// MARK: - - -extension NSNumber { - fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Request.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Request.swift deleted file mode 100644 index 9cd75057cae2..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Request.swift +++ /dev/null @@ -1,658 +0,0 @@ -// -// Request.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// A type that can inspect and optionally adapt a `URLRequest` in some manner if necessary. -public protocol RequestAdapter { - /// Inspects and adapts the specified `URLRequest` in some manner if necessary and returns the result. - /// - /// - parameter urlRequest: The URL request to adapt. - /// - /// - throws: An `Error` if the adaptation encounters an error. - /// - /// - returns: The adapted `URLRequest`. - func adapt(_ urlRequest: URLRequest) throws -> URLRequest -} - -// MARK: - - -/// A closure executed when the `RequestRetrier` determines whether a `Request` should be retried or not. -public typealias RequestRetryCompletion = (_ shouldRetry: Bool, _ timeDelay: TimeInterval) -> Void - -/// A type that determines whether a request should be retried after being executed by the specified session manager -/// and encountering an error. -public protocol RequestRetrier { - /// Determines whether the `Request` should be retried by calling the `completion` closure. - /// - /// This operation is fully asynchronous. Any amount of time can be taken to determine whether the request needs - /// to be retried. The one requirement is that the completion closure is called to ensure the request is properly - /// cleaned up after. - /// - /// - parameter manager: The session manager the request was executed on. - /// - parameter request: The request that failed due to the encountered error. - /// - parameter error: The error encountered when executing the request. - /// - parameter completion: The completion closure to be executed when retry decision has been determined. - func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) -} - -// MARK: - - -protocol TaskConvertible { - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask -} - -/// A dictionary of headers to apply to a `URLRequest`. -public typealias HTTPHeaders = [String: String] - -// MARK: - - -/// Responsible for sending a request and receiving the response and associated data from the server, as well as -/// managing its underlying `URLSessionTask`. -open class Request { - - // MARK: Helper Types - - /// A closure executed when monitoring upload or download progress of a request. - public typealias ProgressHandler = (Progress) -> Void - - enum RequestTask { - case data(TaskConvertible?, URLSessionTask?) - case download(TaskConvertible?, URLSessionTask?) - case upload(TaskConvertible?, URLSessionTask?) - case stream(TaskConvertible?, URLSessionTask?) - } - - // MARK: Properties - - /// The delegate for the underlying task. - open internal(set) var delegate: TaskDelegate { - get { - taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } - return taskDelegate - } - set { - taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } - taskDelegate = newValue - } - } - - /// The underlying task. - open var task: URLSessionTask? { return delegate.task } - - /// The session belonging to the underlying task. - public let session: URLSession - - /// The request sent or to be sent to the server. - open var request: URLRequest? { return task?.originalRequest } - - /// The response received from the server, if any. - open var response: HTTPURLResponse? { return task?.response as? HTTPURLResponse } - - /// The number of times the request has been retried. - open internal(set) var retryCount: UInt = 0 - - let originalTask: TaskConvertible? - - var startTime: CFAbsoluteTime? - var endTime: CFAbsoluteTime? - - var validations: [() -> Void] = [] - - private var taskDelegate: TaskDelegate - private var taskDelegateLock = NSLock() - - // MARK: Lifecycle - - init(session: URLSession, requestTask: RequestTask, error: Error? = nil) { - self.session = session - - switch requestTask { - case .data(let originalTask, let task): - taskDelegate = DataTaskDelegate(task: task) - self.originalTask = originalTask - case .download(let originalTask, let task): - taskDelegate = DownloadTaskDelegate(task: task) - self.originalTask = originalTask - case .upload(let originalTask, let task): - taskDelegate = UploadTaskDelegate(task: task) - self.originalTask = originalTask - case .stream(let originalTask, let task): - taskDelegate = TaskDelegate(task: task) - self.originalTask = originalTask - } - - delegate.error = error - delegate.queue.addOperation { self.endTime = CFAbsoluteTimeGetCurrent() } - } - - // MARK: Authentication - - /// Associates an HTTP Basic credential with the request. - /// - /// - parameter user: The user. - /// - parameter password: The password. - /// - parameter persistence: The URL credential persistence. `.ForSession` by default. - /// - /// - returns: The request. - @discardableResult - open func authenticate( - user: String, - password: String, - persistence: URLCredential.Persistence = .forSession) - -> Self { - let credential = URLCredential(user: user, password: password, persistence: persistence) - return authenticate(usingCredential: credential) - } - - /// Associates a specified credential with the request. - /// - /// - parameter credential: The credential. - /// - /// - returns: The request. - @discardableResult - open func authenticate(usingCredential credential: URLCredential) -> Self { - delegate.credential = credential - return self - } - - /// Returns a base64 encoded basic authentication credential as an authorization header tuple. - /// - /// - parameter user: The user. - /// - parameter password: The password. - /// - /// - returns: A tuple with Authorization header and credential value if encoding succeeds, `nil` otherwise. - open class func authorizationHeader(user: String, password: String) -> (key: String, value: String)? { - guard let data = "\(user):\(password)".data(using: .utf8) else { return nil } - - let credential = data.base64EncodedString(options: []) - - return (key: "Authorization", value: "Basic \(credential)") - } - - // MARK: State - - /// Resumes the request. - open func resume() { - guard let task = task else { delegate.queue.isSuspended = false ; return } - - if startTime == nil { startTime = CFAbsoluteTimeGetCurrent() } - - task.resume() - - NotificationCenter.default.post( - name: Notification.Name.Task.DidResume, - object: self, - userInfo: [Notification.Key.Task: task] - ) - } - - /// Suspends the request. - open func suspend() { - guard let task = task else { return } - - task.suspend() - - NotificationCenter.default.post( - name: Notification.Name.Task.DidSuspend, - object: self, - userInfo: [Notification.Key.Task: task] - ) - } - - /// Cancels the request. - open func cancel() { - guard let task = task else { return } - - task.cancel() - - NotificationCenter.default.post( - name: Notification.Name.Task.DidCancel, - object: self, - userInfo: [Notification.Key.Task: task] - ) - } -} - -// MARK: - CustomStringConvertible - -extension Request: CustomStringConvertible { - /// The textual representation used when written to an output stream, which includes the HTTP method and URL, as - /// well as the response status code if a response has been received. - open var description: String { - var components: [String] = [] - - if let HTTPMethod = request?.httpMethod { - components.append(HTTPMethod) - } - - if let urlString = request?.url?.absoluteString { - components.append(urlString) - } - - if let response = response { - components.append("(\(response.statusCode))") - } - - return components.joined(separator: " ") - } -} - -// MARK: - CustomDebugStringConvertible - -extension Request: CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, in the form of a cURL command. - open var debugDescription: String { - return cURLRepresentation() - } - - func cURLRepresentation() -> String { - var components = ["$ curl -v"] - - guard let request = self.request, - let url = request.url, - let host = url.host - else { - return "$ curl command could not be created" - } - - if let httpMethod = request.httpMethod, httpMethod != "GET" { - components.append("-X \(httpMethod)") - } - - if let credentialStorage = self.session.configuration.urlCredentialStorage { - let protectionSpace = URLProtectionSpace( - host: host, - port: url.port ?? 0, - protocol: url.scheme, - realm: host, - authenticationMethod: NSURLAuthenticationMethodHTTPBasic - ) - - if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { - for credential in credentials { - guard let user = credential.user, let password = credential.password else { continue } - components.append("-u \(user):\(password)") - } - } else { - if let credential = delegate.credential, let user = credential.user, let password = credential.password { - components.append("-u \(user):\(password)") - } - } - } - - if session.configuration.httpShouldSetCookies { - if - let cookieStorage = session.configuration.httpCookieStorage, - let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty - { - let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } - - #if swift(>=3.2) - components.append("-b \"\(string[.. URLSessionTask { - do { - let urlRequest = try self.urlRequest.adapt(using: adapter) - return queue.sync { session.dataTask(with: urlRequest) } - } catch { - throw AdaptError(error: error) - } - } - } - - // MARK: Properties - - /// The request sent or to be sent to the server. - open override var request: URLRequest? { - if let request = super.request { return request } - if let requestable = originalTask as? Requestable { return requestable.urlRequest } - - return nil - } - - /// The progress of fetching the response data from the server for the request. - open var progress: Progress { return dataDelegate.progress } - - var dataDelegate: DataTaskDelegate { return delegate as! DataTaskDelegate } - - // MARK: Stream - - /// Sets a closure to be called periodically during the lifecycle of the request as data is read from the server. - /// - /// This closure returns the bytes most recently received from the server, not including data from previous calls. - /// If this closure is set, data will only be available within this closure, and will not be saved elsewhere. It is - /// also important to note that the server data in any `Response` object will be `nil`. - /// - /// - parameter closure: The code to be executed periodically during the lifecycle of the request. - /// - /// - returns: The request. - @discardableResult - open func stream(closure: ((Data) -> Void)? = nil) -> Self { - dataDelegate.dataStream = closure - return self - } - - // MARK: Progress - - /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. - /// - /// - parameter queue: The dispatch queue to execute the closure on. - /// - parameter closure: The code to be executed periodically as data is read from the server. - /// - /// - returns: The request. - @discardableResult - open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { - dataDelegate.progressHandler = (closure, queue) - return self - } -} - -// MARK: - - -/// Specific type of `Request` that manages an underlying `URLSessionDownloadTask`. -open class DownloadRequest: Request { - - // MARK: Helper Types - - /// A collection of options to be executed prior to moving a downloaded file from the temporary URL to the - /// destination URL. - public struct DownloadOptions: OptionSet { - /// Returns the raw bitmask value of the option and satisfies the `RawRepresentable` protocol. - public let rawValue: UInt - - /// A `DownloadOptions` flag that creates intermediate directories for the destination URL if specified. - public static let createIntermediateDirectories = DownloadOptions(rawValue: 1 << 0) - - /// A `DownloadOptions` flag that removes a previous file from the destination URL if specified. - public static let removePreviousFile = DownloadOptions(rawValue: 1 << 1) - - /// Creates a `DownloadFileDestinationOptions` instance with the specified raw value. - /// - /// - parameter rawValue: The raw bitmask value for the option. - /// - /// - returns: A new log level instance. - public init(rawValue: UInt) { - self.rawValue = rawValue - } - } - - /// A closure executed once a download request has successfully completed in order to determine where to move the - /// temporary file written to during the download process. The closure takes two arguments: the temporary file URL - /// and the URL response, and returns a two arguments: the file URL where the temporary file should be moved and - /// the options defining how the file should be moved. - public typealias DownloadFileDestination = ( - _ temporaryURL: URL, - _ response: HTTPURLResponse) - -> (destinationURL: URL, options: DownloadOptions) - - enum Downloadable: TaskConvertible { - case request(URLRequest) - case resumeData(Data) - - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - do { - let task: URLSessionTask - - switch self { - case let .request(urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.downloadTask(with: urlRequest) } - case let .resumeData(resumeData): - task = queue.sync { session.downloadTask(withResumeData: resumeData) } - } - - return task - } catch { - throw AdaptError(error: error) - } - } - } - - // MARK: Properties - - /// The request sent or to be sent to the server. - open override var request: URLRequest? { - if let request = super.request { return request } - - if let downloadable = originalTask as? Downloadable, case let .request(urlRequest) = downloadable { - return urlRequest - } - - return nil - } - - /// The resume data of the underlying download task if available after a failure. - open var resumeData: Data? { return downloadDelegate.resumeData } - - /// The progress of downloading the response data from the server for the request. - open var progress: Progress { return downloadDelegate.progress } - - var downloadDelegate: DownloadTaskDelegate { return delegate as! DownloadTaskDelegate } - - // MARK: State - - /// Cancels the request. - override open func cancel() { - cancel(createResumeData: true) - } - - /// Cancels the request. - /// - /// - parameter createResumeData: Determines whether resume data is created via the underlying download task or not. - open func cancel(createResumeData: Bool) { - if createResumeData { - downloadDelegate.downloadTask.cancel { self.downloadDelegate.resumeData = $0 } - } else { - downloadDelegate.downloadTask.cancel() - } - - NotificationCenter.default.post( - name: Notification.Name.Task.DidCancel, - object: self, - userInfo: [Notification.Key.Task: task as Any] - ) - } - - // MARK: Progress - - /// Sets a closure to be called periodically during the lifecycle of the `Request` as data is read from the server. - /// - /// - parameter queue: The dispatch queue to execute the closure on. - /// - parameter closure: The code to be executed periodically as data is read from the server. - /// - /// - returns: The request. - @discardableResult - open func downloadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { - downloadDelegate.progressHandler = (closure, queue) - return self - } - - // MARK: Destination - - /// Creates a download file destination closure which uses the default file manager to move the temporary file to a - /// file URL in the first available directory with the specified search path directory and search path domain mask. - /// - /// - parameter directory: The search path directory. `.DocumentDirectory` by default. - /// - parameter domain: The search path domain mask. `.UserDomainMask` by default. - /// - /// - returns: A download file destination closure. - open class func suggestedDownloadDestination( - for directory: FileManager.SearchPathDirectory = .documentDirectory, - in domain: FileManager.SearchPathDomainMask = .userDomainMask) - -> DownloadFileDestination { - return { temporaryURL, response in - let directoryURLs = FileManager.default.urls(for: directory, in: domain) - - if !directoryURLs.isEmpty { - return (directoryURLs[0].appendingPathComponent(response.suggestedFilename!), []) - } - - return (temporaryURL, []) - } - } -} - -// MARK: - - -/// Specific type of `Request` that manages an underlying `URLSessionUploadTask`. -open class UploadRequest: DataRequest { - - // MARK: Helper Types - - enum Uploadable: TaskConvertible { - case data(Data, URLRequest) - case file(URL, URLRequest) - case stream(InputStream, URLRequest) - - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - do { - let task: URLSessionTask - - switch self { - case let .data(data, urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.uploadTask(with: urlRequest, from: data) } - case let .file(url, urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.uploadTask(with: urlRequest, fromFile: url) } - case let .stream(_, urlRequest): - let urlRequest = try urlRequest.adapt(using: adapter) - task = queue.sync { session.uploadTask(withStreamedRequest: urlRequest) } - } - - return task - } catch { - throw AdaptError(error: error) - } - } - } - - // MARK: Properties - - /// The request sent or to be sent to the server. - open override var request: URLRequest? { - if let request = super.request { return request } - - guard let uploadable = originalTask as? Uploadable else { return nil } - - switch uploadable { - case .data(_, let urlRequest), .file(_, let urlRequest), .stream(_, let urlRequest): - return urlRequest - } - } - - /// The progress of uploading the payload to the server for the upload request. - open var uploadProgress: Progress { return uploadDelegate.uploadProgress } - - var uploadDelegate: UploadTaskDelegate { return delegate as! UploadTaskDelegate } - - // MARK: Upload Progress - - /// Sets a closure to be called periodically during the lifecycle of the `UploadRequest` as data is sent to - /// the server. - /// - /// After the data is sent to the server, the `progress(queue:closure:)` APIs can be used to monitor the progress - /// of data being read from the server. - /// - /// - parameter queue: The dispatch queue to execute the closure on. - /// - parameter closure: The code to be executed periodically as data is sent to the server. - /// - /// - returns: The request. - @discardableResult - open func uploadProgress(queue: DispatchQueue = DispatchQueue.main, closure: @escaping ProgressHandler) -> Self { - uploadDelegate.uploadProgressHandler = (closure, queue) - return self - } -} - -// MARK: - - -#if !os(watchOS) - -/// Specific type of `Request` that manages an underlying `URLSessionStreamTask`. -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -open class StreamRequest: Request { - enum Streamable: TaskConvertible { - case stream(hostName: String, port: Int) - case netService(NetService) - - func task(session: URLSession, adapter: RequestAdapter?, queue: DispatchQueue) throws -> URLSessionTask { - let task: URLSessionTask - - switch self { - case let .stream(hostName, port): - task = queue.sync { session.streamTask(withHostName: hostName, port: port) } - case let .netService(netService): - task = queue.sync { session.streamTask(with: netService) } - } - - return task - } - } -} - -#endif diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Response.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Response.swift deleted file mode 100644 index 88d09e33ff8e..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Response.swift +++ /dev/null @@ -1,563 +0,0 @@ -// -// Response.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Used to store all data associated with an non-serialized response of a data or upload request. -public struct DefaultDataResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The data returned by the server. - public let data: Data? - - /// The error encountered while executing or validating the request. - public let error: Error? - - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline - - var _metrics: AnyObject? - - /// Creates a `DefaultDataResponse` instance from the specified parameters. - /// - /// - Parameters: - /// - request: The URL request sent to the server. - /// - response: The server's response to the URL request. - /// - data: The data returned by the server. - /// - error: The error encountered while executing or validating the request. - /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. - /// - metrics: The task metrics containing the request / response statistics. `nil` by default. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - data: Data?, - error: Error?, - timeline: Timeline = Timeline(), - metrics: AnyObject? = nil) { - self.request = request - self.response = response - self.data = data - self.error = error - self.timeline = timeline - } -} - -// MARK: - - -/// Used to store all data associated with a serialized response of a data or upload request. -public struct DataResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The data returned by the server. - public let data: Data? - - /// The result of response serialization. - public let result: Result - - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline - - /// Returns the associated value of the result if it is a success, `nil` otherwise. - public var value: Value? { return result.value } - - /// Returns the associated error value if the result if it is a failure, `nil` otherwise. - public var error: Error? { return result.error } - - var _metrics: AnyObject? - - /// Creates a `DataResponse` instance with the specified parameters derived from response serialization. - /// - /// - parameter request: The URL request sent to the server. - /// - parameter response: The server's response to the URL request. - /// - parameter data: The data returned by the server. - /// - parameter result: The result of response serialization. - /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. - /// - /// - returns: The new `DataResponse` instance. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - data: Data?, - result: Result, - timeline: Timeline = Timeline()) { - self.request = request - self.response = response - self.data = data - self.result = result - self.timeline = timeline - } -} - -// MARK: - - -extension DataResponse: CustomStringConvertible, CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a - /// success or failure. - public var description: String { - return result.debugDescription - } - - /// The debug textual representation used when written to an output stream, which includes the URL request, the URL - /// response, the server data, the response serialization result and the timeline. - public var debugDescription: String { - var output: [String] = [] - - output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") - output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") - output.append("[Data]: \(data?.count ?? 0) bytes") - output.append("[Result]: \(result.debugDescription)") - output.append("[Timeline]: \(timeline.debugDescription)") - - return output.joined(separator: "\n") - } -} - -// MARK: - - -extension DataResponse { - /// Evaluates the specified closure when the result of this `DataResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `map` method with a closure that does not throw. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleInt = possibleData.map { $0.count } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A `DataResponse` whose result wraps the value returned by the given closure. If this instance's - /// result is a failure, returns a response wrapping the same failure. - public func map(_ transform: (Value) -> T) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.map(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the given closure when the result of this `DataResponse` is a success, passing the unwrapped result - /// value as a parameter. - /// - /// Use the `flatMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleObject = possibleData.flatMap { - /// try JSONSerialization.jsonObject(with: $0) - /// } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A success or failure `DataResponse` depending on the result of the given closure. If this instance's - /// result is a failure, returns the same failure. - public func flatMap(_ transform: (Value) throws -> T) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.flatMap(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `mapError` function with a closure that does not throw. For example: - /// - /// let possibleData: DataResponse = ... - /// let withMyError = possibleData.mapError { MyError.error($0) } - /// - /// - Parameter transform: A closure that takes the error of the instance. - /// - Returns: A `DataResponse` instance containing the result of the transform. - public func mapError(_ transform: (Error) -> E) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.mapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the specified closure when the `DataResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `flatMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: DataResponse = ... - /// let possibleObject = possibleData.flatMapError { - /// try someFailableFunction(taking: $0) - /// } - /// - /// - Parameter transform: A throwing closure that takes the error of the instance. - /// - /// - Returns: A `DataResponse` instance containing the result of the transform. - public func flatMapError(_ transform: (Error) throws -> E) -> DataResponse { - var response = DataResponse( - request: request, - response: self.response, - data: data, - result: result.flatMapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } -} - -// MARK: - - -/// Used to store all data associated with an non-serialized response of a download request. -public struct DefaultDownloadResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The temporary destination URL of the data returned from the server. - public let temporaryURL: URL? - - /// The final destination URL of the data returned from the server if it was moved. - public let destinationURL: URL? - - /// The resume data generated if the request was cancelled. - public let resumeData: Data? - - /// The error encountered while executing or validating the request. - public let error: Error? - - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline - - var _metrics: AnyObject? - - /// Creates a `DefaultDownloadResponse` instance from the specified parameters. - /// - /// - Parameters: - /// - request: The URL request sent to the server. - /// - response: The server's response to the URL request. - /// - temporaryURL: The temporary destination URL of the data returned from the server. - /// - destinationURL: The final destination URL of the data returned from the server if it was moved. - /// - resumeData: The resume data generated if the request was cancelled. - /// - error: The error encountered while executing or validating the request. - /// - timeline: The timeline of the complete lifecycle of the request. `Timeline()` by default. - /// - metrics: The task metrics containing the request / response statistics. `nil` by default. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - temporaryURL: URL?, - destinationURL: URL?, - resumeData: Data?, - error: Error?, - timeline: Timeline = Timeline(), - metrics: AnyObject? = nil) { - self.request = request - self.response = response - self.temporaryURL = temporaryURL - self.destinationURL = destinationURL - self.resumeData = resumeData - self.error = error - self.timeline = timeline - } -} - -// MARK: - - -/// Used to store all data associated with a serialized response of a download request. -public struct DownloadResponse { - /// The URL request sent to the server. - public let request: URLRequest? - - /// The server's response to the URL request. - public let response: HTTPURLResponse? - - /// The temporary destination URL of the data returned from the server. - public let temporaryURL: URL? - - /// The final destination URL of the data returned from the server if it was moved. - public let destinationURL: URL? - - /// The resume data generated if the request was cancelled. - public let resumeData: Data? - - /// The result of response serialization. - public let result: Result - - /// The timeline of the complete lifecycle of the request. - public let timeline: Timeline - - /// Returns the associated value of the result if it is a success, `nil` otherwise. - public var value: Value? { return result.value } - - /// Returns the associated error value if the result if it is a failure, `nil` otherwise. - public var error: Error? { return result.error } - - var _metrics: AnyObject? - - /// Creates a `DownloadResponse` instance with the specified parameters derived from response serialization. - /// - /// - parameter request: The URL request sent to the server. - /// - parameter response: The server's response to the URL request. - /// - parameter temporaryURL: The temporary destination URL of the data returned from the server. - /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. - /// - parameter resumeData: The resume data generated if the request was cancelled. - /// - parameter result: The result of response serialization. - /// - parameter timeline: The timeline of the complete lifecycle of the `Request`. Defaults to `Timeline()`. - /// - /// - returns: The new `DownloadResponse` instance. - public init( - request: URLRequest?, - response: HTTPURLResponse?, - temporaryURL: URL?, - destinationURL: URL?, - resumeData: Data?, - result: Result, - timeline: Timeline = Timeline()) { - self.request = request - self.response = response - self.temporaryURL = temporaryURL - self.destinationURL = destinationURL - self.resumeData = resumeData - self.result = result - self.timeline = timeline - } -} - -// MARK: - - -extension DownloadResponse: CustomStringConvertible, CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a - /// success or failure. - public var description: String { - return result.debugDescription - } - - /// The debug textual representation used when written to an output stream, which includes the URL request, the URL - /// response, the temporary and destination URLs, the resume data, the response serialization result and the - /// timeline. - public var debugDescription: String { - var output: [String] = [] - - output.append(request != nil ? "[Request]: \(request!.httpMethod ?? "GET") \(request!)" : "[Request]: nil") - output.append(response != nil ? "[Response]: \(response!)" : "[Response]: nil") - output.append("[TemporaryURL]: \(temporaryURL?.path ?? "nil")") - output.append("[DestinationURL]: \(destinationURL?.path ?? "nil")") - output.append("[ResumeData]: \(resumeData?.count ?? 0) bytes") - output.append("[Result]: \(result.debugDescription)") - output.append("[Timeline]: \(timeline.debugDescription)") - - return output.joined(separator: "\n") - } -} - -// MARK: - - -extension DownloadResponse { - /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `map` method with a closure that does not throw. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleInt = possibleData.map { $0.count } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A `DownloadResponse` whose result wraps the value returned by the given closure. If this instance's - /// result is a failure, returns a response wrapping the same failure. - public func map(_ transform: (Value) -> T) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.map(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the given closure when the result of this `DownloadResponse` is a success, passing the unwrapped - /// result value as a parameter. - /// - /// Use the `flatMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleObject = possibleData.flatMap { - /// try JSONSerialization.jsonObject(with: $0) - /// } - /// - /// - parameter transform: A closure that takes the success value of the instance's result. - /// - /// - returns: A success or failure `DownloadResponse` depending on the result of the given closure. If this - /// instance's result is a failure, returns the same failure. - public func flatMap(_ transform: (Value) throws -> T) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.flatMap(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `mapError` function with a closure that does not throw. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let withMyError = possibleData.mapError { MyError.error($0) } - /// - /// - Parameter transform: A closure that takes the error of the instance. - /// - Returns: A `DownloadResponse` instance containing the result of the transform. - public func mapError(_ transform: (Error) -> E) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.mapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } - - /// Evaluates the specified closure when the `DownloadResponse` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `flatMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: DownloadResponse = ... - /// let possibleObject = possibleData.flatMapError { - /// try someFailableFunction(taking: $0) - /// } - /// - /// - Parameter transform: A throwing closure that takes the error of the instance. - /// - /// - Returns: A `DownloadResponse` instance containing the result of the transform. - public func flatMapError(_ transform: (Error) throws -> E) -> DownloadResponse { - var response = DownloadResponse( - request: request, - response: self.response, - temporaryURL: temporaryURL, - destinationURL: destinationURL, - resumeData: resumeData, - result: result.flatMapError(transform), - timeline: timeline - ) - - response._metrics = _metrics - - return response - } -} - -// MARK: - - -protocol Response { - /// The task metrics containing the request / response statistics. - var _metrics: AnyObject? { get set } - mutating func add(_ metrics: AnyObject?) -} - -extension Response { - mutating func add(_ metrics: AnyObject?) { - #if !os(watchOS) - guard #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) else { return } - guard let metrics = metrics as? URLSessionTaskMetrics else { return } - - _metrics = metrics - #endif - } -} - -// MARK: - - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DefaultDataResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DataResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DefaultDownloadResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} - -@available(iOS 10.0, macOS 10.12, tvOS 10.0, *) -extension DownloadResponse: Response { -#if !os(watchOS) - /// The task metrics containing the request / response statistics. - public var metrics: URLSessionTaskMetrics? { return _metrics as? URLSessionTaskMetrics } -#endif -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/ResponseSerialization.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/ResponseSerialization.swift deleted file mode 100644 index b8f5b65b204d..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/ResponseSerialization.swift +++ /dev/null @@ -1,697 +0,0 @@ -// -// ResponseSerialization.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// The type in which all data response serializers must conform to in order to serialize a response. -public protocol DataResponseSerializerProtocol { - /// The type of serialized object to be created by this `DataResponseSerializerType`. - associatedtype SerializedObject - - /// A closure used by response handlers that takes a request, response, data and error and returns a result. - var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result { get } -} - -// MARK: - - -/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object. -public struct DataResponseSerializer: DataResponseSerializerProtocol { - /// The type of serialized object to be created by this `DataResponseSerializer`. - public typealias SerializedObject = Value - - /// A closure used by response handlers that takes a request, response, data and error and returns a result. - public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result - - /// Initializes the `ResponseSerializer` instance with the given serialize response closure. - /// - /// - parameter serializeResponse: The closure used to serialize the response. - /// - /// - returns: The new generic response serializer instance. - public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result) { - self.serializeResponse = serializeResponse - } -} - -// MARK: - - -/// The type in which all download response serializers must conform to in order to serialize a response. -public protocol DownloadResponseSerializerProtocol { - /// The type of serialized object to be created by this `DownloadResponseSerializerType`. - associatedtype SerializedObject - - /// A closure used by response handlers that takes a request, response, url and error and returns a result. - var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result { get } -} - -// MARK: - - -/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object. -public struct DownloadResponseSerializer: DownloadResponseSerializerProtocol { - /// The type of serialized object to be created by this `DownloadResponseSerializer`. - public typealias SerializedObject = Value - - /// A closure used by response handlers that takes a request, response, url and error and returns a result. - public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result - - /// Initializes the `ResponseSerializer` instance with the given serialize response closure. - /// - /// - parameter serializeResponse: The closure used to serialize the response. - /// - /// - returns: The new generic response serializer instance. - public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result) { - self.serializeResponse = serializeResponse - } -} - -// MARK: - Timeline - -extension Request { - var timeline: Timeline { - let requestStartTime = self.startTime ?? CFAbsoluteTimeGetCurrent() - let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() - let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime - - return Timeline( - requestStartTime: requestStartTime, - initialResponseTime: initialResponseTime, - requestCompletedTime: requestCompletedTime, - serializationCompletedTime: CFAbsoluteTimeGetCurrent() - ) - } -} - -// MARK: - Default - -extension DataRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self { - delegate.queue.addOperation { - (queue ?? DispatchQueue.main).async { - var dataResponse = DefaultDataResponse( - request: self.request, - response: self.response, - data: self.delegate.data, - error: self.delegate.error, - timeline: self.timeline - ) - - dataResponse.add(self.delegate.metrics) - - completionHandler(dataResponse) - } - } - - return self - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, - /// and data. - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func response( - queue: DispatchQueue? = nil, - responseSerializer: T, - completionHandler: @escaping (DataResponse) -> Void) - -> Self { - delegate.queue.addOperation { - let result = responseSerializer.serializeResponse( - self.request, - self.response, - self.delegate.data, - self.delegate.error - ) - - var dataResponse = DataResponse( - request: self.request, - response: self.response, - data: self.delegate.data, - result: result, - timeline: self.timeline - ) - - dataResponse.add(self.delegate.metrics) - - (queue ?? DispatchQueue.main).async { completionHandler(dataResponse) } - } - - return self - } -} - -extension DownloadRequest { - /// Adds a handler to be called once the request has finished. - /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func response( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DefaultDownloadResponse) -> Void) - -> Self { - delegate.queue.addOperation { - (queue ?? DispatchQueue.main).async { - var downloadResponse = DefaultDownloadResponse( - request: self.request, - response: self.response, - temporaryURL: self.downloadDelegate.temporaryURL, - destinationURL: self.downloadDelegate.destinationURL, - resumeData: self.downloadDelegate.resumeData, - error: self.downloadDelegate.error, - timeline: self.timeline - ) - - downloadResponse.add(self.delegate.metrics) - - completionHandler(downloadResponse) - } - } - - return self - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter queue: The queue on which the completion handler is dispatched. - /// - parameter responseSerializer: The response serializer responsible for serializing the request, response, - /// and data contained in the destination url. - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func response( - queue: DispatchQueue? = nil, - responseSerializer: T, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self { - delegate.queue.addOperation { - let result = responseSerializer.serializeResponse( - self.request, - self.response, - self.downloadDelegate.fileURL, - self.downloadDelegate.error - ) - - var downloadResponse = DownloadResponse( - request: self.request, - response: self.response, - temporaryURL: self.downloadDelegate.temporaryURL, - destinationURL: self.downloadDelegate.destinationURL, - resumeData: self.downloadDelegate.resumeData, - result: result, - timeline: self.timeline - ) - - downloadResponse.add(self.delegate.metrics) - - (queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) } - } - - return self - } -} - -// MARK: - Data - -extension Request { - /// Returns a result data type that contains the response data as-is. - /// - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. - /// - /// - returns: The result data type. - public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) } - - guard let validData = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - return .success(validData) - } -} - -extension DataRequest { - /// Creates a response serializer that returns the associated data as-is. - /// - /// - returns: A data response serializer. - public static func dataResponseSerializer() -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponseData(response: response, data: data, error: error) - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseData( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DataResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DataRequest.dataResponseSerializer(), - completionHandler: completionHandler - ) - } -} - -extension DownloadRequest { - /// Creates a response serializer that returns the associated data as-is. - /// - /// - returns: A data response serializer. - public static func dataResponseSerializer() -> DownloadResponseSerializer { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } - - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } - - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponseData(response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) - } - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter completionHandler: The code to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseData( - queue: DispatchQueue? = nil, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DownloadRequest.dataResponseSerializer(), - completionHandler: completionHandler - ) - } -} - -// MARK: - String - -extension Request { - /// Returns a result string type initialized from the response data with the specified string encoding. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server - /// response, falling back to the default HTTP default character set, ISO-8859-1. - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. - /// - /// - returns: The result data type. - public static func serializeResponseString( - encoding: String.Encoding?, - response: HTTPURLResponse?, - data: Data?, - error: Error?) - -> Result { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") } - - guard let validData = data else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNil)) - } - - var convertedEncoding = encoding - - if let encodingName = response?.textEncodingName as CFString?, convertedEncoding == nil { - convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding( - CFStringConvertIANACharSetNameToEncoding(encodingName)) - ) - } - - let actualEncoding = convertedEncoding ?? .isoLatin1 - - if let string = String(data: validData, encoding: actualEncoding) { - return .success(string) - } else { - return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding))) - } - } -} - -extension DataRequest { - /// Creates a response serializer that returns a result string type initialized from the response data with - /// the specified string encoding. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server - /// response, falling back to the default HTTP default character set, ISO-8859-1. - /// - /// - returns: A string response serializer. - public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the - /// server response, falling back to the default HTTP default character set, - /// ISO-8859-1. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseString( - queue: DispatchQueue? = nil, - encoding: String.Encoding? = nil, - completionHandler: @escaping (DataResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding), - completionHandler: completionHandler - ) - } -} - -extension DownloadRequest { - /// Creates a response serializer that returns a result string type initialized from the response data with - /// the specified string encoding. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server - /// response, falling back to the default HTTP default character set, ISO-8859-1. - /// - /// - returns: A string response serializer. - public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } - - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } - - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) - } - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the - /// server response, falling back to the default HTTP default character set, - /// ISO-8859-1. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseString( - queue: DispatchQueue? = nil, - encoding: String.Encoding? = nil, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding), - completionHandler: completionHandler - ) - } -} - -// MARK: - JSON - -extension Request { - /// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization` - /// with the specified reading options. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. - /// - /// - returns: The result data type. - public static func serializeResponseJSON( - options: JSONSerialization.ReadingOptions, - response: HTTPURLResponse?, - data: Data?, - error: Error?) - -> Result { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } - - guard let validData = data, validData.count > 0 else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) - } - - do { - let json = try JSONSerialization.jsonObject(with: validData, options: options) - return .success(json) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error))) - } - } -} - -extension DataRequest { - /// Creates a response serializer that returns a JSON object result type constructed from the response data using - /// `JSONSerialization` with the specified reading options. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - /// - returns: A JSON object response serializer. - public static func jsonResponseSerializer( - options: JSONSerialization.ReadingOptions = .allowFragments) - -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseJSON( - queue: DispatchQueue? = nil, - options: JSONSerialization.ReadingOptions = .allowFragments, - completionHandler: @escaping (DataResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DataRequest.jsonResponseSerializer(options: options), - completionHandler: completionHandler - ) - } -} - -extension DownloadRequest { - /// Creates a response serializer that returns a JSON object result type constructed from the response data using - /// `JSONSerialization` with the specified reading options. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - /// - returns: A JSON object response serializer. - public static func jsonResponseSerializer( - options: JSONSerialization.ReadingOptions = .allowFragments) - -> DownloadResponseSerializer { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } - - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } - - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponseJSON(options: options, response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) - } - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responseJSON( - queue: DispatchQueue? = nil, - options: JSONSerialization.ReadingOptions = .allowFragments, - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DownloadRequest.jsonResponseSerializer(options: options), - completionHandler: completionHandler - ) - } -} - -// MARK: - Property List - -extension Request { - /// Returns a plist object contained in a result type constructed from the response data using - /// `PropertyListSerialization` with the specified reading options. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - parameter response: The response from the server. - /// - parameter data: The data returned from the server. - /// - parameter error: The error already encountered if it exists. - /// - /// - returns: The result data type. - public static func serializeResponsePropertyList( - options: PropertyListSerialization.ReadOptions, - response: HTTPURLResponse?, - data: Data?, - error: Error?) - -> Result { - guard error == nil else { return .failure(error!) } - - if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) } - - guard let validData = data, validData.count > 0 else { - return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength)) - } - - do { - let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil) - return .success(plist) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error))) - } - } -} - -extension DataRequest { - /// Creates a response serializer that returns an object constructed from the response data using - /// `PropertyListSerialization` with the specified reading options. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - /// - returns: A property list object response serializer. - public static func propertyListResponseSerializer( - options: PropertyListSerialization.ReadOptions = []) - -> DataResponseSerializer { - return DataResponseSerializer { _, response, data, error in - return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responsePropertyList( - queue: DispatchQueue? = nil, - options: PropertyListSerialization.ReadOptions = [], - completionHandler: @escaping (DataResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DataRequest.propertyListResponseSerializer(options: options), - completionHandler: completionHandler - ) - } -} - -extension DownloadRequest { - /// Creates a response serializer that returns an object constructed from the response data using - /// `PropertyListSerialization` with the specified reading options. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - /// - returns: A property list object response serializer. - public static func propertyListResponseSerializer( - options: PropertyListSerialization.ReadOptions = []) - -> DownloadResponseSerializer { - return DownloadResponseSerializer { _, response, fileURL, error in - guard error == nil else { return .failure(error!) } - - guard let fileURL = fileURL else { - return .failure(AFError.responseSerializationFailed(reason: .inputFileNil)) - } - - do { - let data = try Data(contentsOf: fileURL) - return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error) - } catch { - return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL))) - } - } - } - - /// Adds a handler to be called once the request has finished. - /// - /// - parameter options: The property list reading options. Defaults to `[]`. - /// - parameter completionHandler: A closure to be executed once the request has finished. - /// - /// - returns: The request. - @discardableResult - public func responsePropertyList( - queue: DispatchQueue? = nil, - options: PropertyListSerialization.ReadOptions = [], - completionHandler: @escaping (DownloadResponse) -> Void) - -> Self { - return response( - queue: queue, - responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options), - completionHandler: completionHandler - ) - } -} - -/// A set of HTTP response status code that do not contain response data. -private let emptyDataStatusCodes: Set = [204, 205] diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Result.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Result.swift deleted file mode 100644 index e0928089ab73..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Result.swift +++ /dev/null @@ -1,300 +0,0 @@ -// -// Result.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Used to represent whether a request was successful or encountered an error. -/// -/// - success: The request and all post processing operations were successful resulting in the serialization of the -/// provided associated value. -/// -/// - failure: The request encountered an error resulting in a failure. The associated values are the original data -/// provided by the server as well as the error that caused the failure. -public enum Result { - case success(Value) - case failure(Error) - - /// Returns `true` if the result is a success, `false` otherwise. - public var isSuccess: Bool { - switch self { - case .success: - return true - case .failure: - return false - } - } - - /// Returns `true` if the result is a failure, `false` otherwise. - public var isFailure: Bool { - return !isSuccess - } - - /// Returns the associated value if the result is a success, `nil` otherwise. - public var value: Value? { - switch self { - case .success(let value): - return value - case .failure: - return nil - } - } - - /// Returns the associated error value if the result is a failure, `nil` otherwise. - public var error: Error? { - switch self { - case .success: - return nil - case .failure(let error): - return error - } - } -} - -// MARK: - CustomStringConvertible - -extension Result: CustomStringConvertible { - /// The textual representation used when written to an output stream, which includes whether the result was a - /// success or failure. - public var description: String { - switch self { - case .success: - return "SUCCESS" - case .failure: - return "FAILURE" - } - } -} - -// MARK: - CustomDebugStringConvertible - -extension Result: CustomDebugStringConvertible { - /// The debug textual representation used when written to an output stream, which includes whether the result was a - /// success or failure in addition to the value or error. - public var debugDescription: String { - switch self { - case .success(let value): - return "SUCCESS: \(value)" - case .failure(let error): - return "FAILURE: \(error)" - } - } -} - -// MARK: - Functional APIs - -extension Result { - /// Creates a `Result` instance from the result of a closure. - /// - /// A failure result is created when the closure throws, and a success result is created when the closure - /// succeeds without throwing an error. - /// - /// func someString() throws -> String { ... } - /// - /// let result = Result(value: { - /// return try someString() - /// }) - /// - /// // The type of result is Result - /// - /// The trailing closure syntax is also supported: - /// - /// let result = Result { try someString() } - /// - /// - parameter value: The closure to execute and create the result for. - public init(value: () throws -> Value) { - do { - self = try .success(value()) - } catch { - self = .failure(error) - } - } - - /// Returns the success value, or throws the failure error. - /// - /// let possibleString: Result = .success("success") - /// try print(possibleString.unwrap()) - /// // Prints "success" - /// - /// let noString: Result = .failure(error) - /// try print(noString.unwrap()) - /// // Throws error - public func unwrap() throws -> Value { - switch self { - case .success(let value): - return value - case .failure(let error): - throw error - } - } - - /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. - /// - /// Use the `map` method with a closure that does not throw. For example: - /// - /// let possibleData: Result = .success(Data()) - /// let possibleInt = possibleData.map { $0.count } - /// try print(possibleInt.unwrap()) - /// // Prints "0" - /// - /// let noData: Result = .failure(error) - /// let noInt = noData.map { $0.count } - /// try print(noInt.unwrap()) - /// // Throws error - /// - /// - parameter transform: A closure that takes the success value of the `Result` instance. - /// - /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the - /// same failure. - public func map(_ transform: (Value) -> T) -> Result { - switch self { - case .success(let value): - return .success(transform(value)) - case .failure(let error): - return .failure(error) - } - } - - /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. - /// - /// Use the `flatMap` method with a closure that may throw an error. For example: - /// - /// let possibleData: Result = .success(Data(...)) - /// let possibleObject = possibleData.flatMap { - /// try JSONSerialization.jsonObject(with: $0) - /// } - /// - /// - parameter transform: A closure that takes the success value of the instance. - /// - /// - returns: A `Result` containing the result of the given closure. If this instance is a failure, returns the - /// same failure. - public func flatMap(_ transform: (Value) throws -> T) -> Result { - switch self { - case .success(let value): - do { - return try .success(transform(value)) - } catch { - return .failure(error) - } - case .failure(let error): - return .failure(error) - } - } - - /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `mapError` function with a closure that does not throw. For example: - /// - /// let possibleData: Result = .failure(someError) - /// let withMyError: Result = possibleData.mapError { MyError.error($0) } - /// - /// - Parameter transform: A closure that takes the error of the instance. - /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns - /// the same instance. - public func mapError(_ transform: (Error) -> T) -> Result { - switch self { - case .failure(let error): - return .failure(transform(error)) - case .success: - return self - } - } - - /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `flatMapError` function with a closure that may throw an error. For example: - /// - /// let possibleData: Result = .success(Data(...)) - /// let possibleObject = possibleData.flatMapError { - /// try someFailableFunction(taking: $0) - /// } - /// - /// - Parameter transform: A throwing closure that takes the error of the instance. - /// - /// - Returns: A `Result` instance containing the result of the transform. If this instance is a success, returns - /// the same instance. - public func flatMapError(_ transform: (Error) throws -> T) -> Result { - switch self { - case .failure(let error): - do { - return try .failure(transform(error)) - } catch { - return .failure(error) - } - case .success: - return self - } - } - - /// Evaluates the specified closure when the `Result` is a success, passing the unwrapped value as a parameter. - /// - /// Use the `withValue` function to evaluate the passed closure without modifying the `Result` instance. - /// - /// - Parameter closure: A closure that takes the success value of this instance. - /// - Returns: This `Result` instance, unmodified. - @discardableResult - public func withValue(_ closure: (Value) throws -> Void) rethrows -> Result { - if case let .success(value) = self { try closure(value) } - - return self - } - - /// Evaluates the specified closure when the `Result` is a failure, passing the unwrapped error as a parameter. - /// - /// Use the `withError` function to evaluate the passed closure without modifying the `Result` instance. - /// - /// - Parameter closure: A closure that takes the success value of this instance. - /// - Returns: This `Result` instance, unmodified. - @discardableResult - public func withError(_ closure: (Error) throws -> Void) rethrows -> Result { - if case let .failure(error) = self { try closure(error) } - - return self - } - - /// Evaluates the specified closure when the `Result` is a success. - /// - /// Use the `ifSuccess` function to evaluate the passed closure without modifying the `Result` instance. - /// - /// - Parameter closure: A `Void` closure. - /// - Returns: This `Result` instance, unmodified. - @discardableResult - public func ifSuccess(_ closure: () throws -> Void) rethrows -> Result { - if isSuccess { try closure() } - - return self - } - - /// Evaluates the specified closure when the `Result` is a failure. - /// - /// Use the `ifFailure` function to evaluate the passed closure without modifying the `Result` instance. - /// - /// - Parameter closure: A `Void` closure. - /// - Returns: This `Result` instance, unmodified. - @discardableResult - public func ifFailure(_ closure: () throws -> Void) rethrows -> Result { - if isFailure { try closure() } - - return self - } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/ServerTrustPolicy.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/ServerTrustPolicy.swift deleted file mode 100644 index ad4d5632a019..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/ServerTrustPolicy.swift +++ /dev/null @@ -1,306 +0,0 @@ -// -// ServerTrustPolicy.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host. -open class ServerTrustPolicyManager { - /// The dictionary of policies mapped to a particular host. - public let policies: [String: ServerTrustPolicy] - - /// Initializes the `ServerTrustPolicyManager` instance with the given policies. - /// - /// Since different servers and web services can have different leaf certificates, intermediate and even root - /// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This - /// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key - /// pinning for host3 and disabling evaluation for host4. - /// - /// - parameter policies: A dictionary of all policies mapped to a particular host. - /// - /// - returns: The new `ServerTrustPolicyManager` instance. - public init(policies: [String: ServerTrustPolicy]) { - self.policies = policies - } - - /// Returns the `ServerTrustPolicy` for the given host if applicable. - /// - /// By default, this method will return the policy that perfectly matches the given host. Subclasses could override - /// this method and implement more complex mapping implementations such as wildcards. - /// - /// - parameter host: The host to use when searching for a matching policy. - /// - /// - returns: The server trust policy for the given host if found. - open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? { - return policies[host] - } -} - -// MARK: - - -extension URLSession { - private struct AssociatedKeys { - static var managerKey = "URLSession.ServerTrustPolicyManager" - } - - var serverTrustPolicyManager: ServerTrustPolicyManager? { - get { - return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager - } - set (manager) { - objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - } -} - -// MARK: - ServerTrustPolicy - -/// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when -/// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust -/// with a given set of criteria to determine whether the server trust is valid and the connection should be made. -/// -/// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other -/// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged -/// to route all communication over an HTTPS connection with pinning enabled. -/// -/// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to -/// validate the host provided by the challenge. Applications are encouraged to always -/// validate the host in production environments to guarantee the validity of the server's -/// certificate chain. -/// -/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to -/// validate the host provided by the challenge as well as specify the revocation flags for -/// testing for revoked certificates. Apple platforms did not start testing for revoked -/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is -/// demonstrated in our TLS tests. Applications are encouraged to always validate the host -/// in production environments to guarantee the validity of the server's certificate chain. -/// -/// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is -/// considered valid if one of the pinned certificates match one of the server certificates. -/// By validating both the certificate chain and host, certificate pinning provides a very -/// secure form of server trust validation mitigating most, if not all, MITM attacks. -/// Applications are encouraged to always validate the host and require a valid certificate -/// chain in production environments. -/// -/// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered -/// valid if one of the pinned public keys match one of the server certificate public keys. -/// By validating both the certificate chain and host, public key pinning provides a very -/// secure form of server trust validation mitigating most, if not all, MITM attacks. -/// Applications are encouraged to always validate the host and require a valid certificate -/// chain in production environments. -/// -/// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid. -/// -/// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust. -public enum ServerTrustPolicy { - case performDefaultEvaluation(validateHost: Bool) - case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags) - case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool) - case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool) - case disableEvaluation - case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool) - - // MARK: - Bundle Location - - /// Returns all certificates within the given bundle with a `.cer` file extension. - /// - /// - parameter bundle: The bundle to search for all `.cer` files. - /// - /// - returns: All certificates within the given bundle. - public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] { - var certificates: [SecCertificate] = [] - - let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in - bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil) - }.joined()) - - for path in paths { - if - let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData, - let certificate = SecCertificateCreateWithData(nil, certificateData) - { - certificates.append(certificate) - } - } - - return certificates - } - - /// Returns all public keys within the given bundle with a `.cer` file extension. - /// - /// - parameter bundle: The bundle to search for all `*.cer` files. - /// - /// - returns: All public keys within the given bundle. - public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] { - var publicKeys: [SecKey] = [] - - for certificate in certificates(in: bundle) { - if let publicKey = publicKey(for: certificate) { - publicKeys.append(publicKey) - } - } - - return publicKeys - } - - // MARK: - Evaluation - - /// Evaluates whether the server trust is valid for the given host. - /// - /// - parameter serverTrust: The server trust to evaluate. - /// - parameter host: The host of the challenge protection space. - /// - /// - returns: Whether the server trust is valid. - public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool { - var serverTrustIsValid = false - - switch self { - case let .performDefaultEvaluation(validateHost): - let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, policy) - - serverTrustIsValid = trustIsValid(serverTrust) - case let .performRevokedEvaluation(validateHost, revocationFlags): - let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - let revokedPolicy = SecPolicyCreateRevocation(revocationFlags) - SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef) - - serverTrustIsValid = trustIsValid(serverTrust) - case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost): - if validateCertificateChain { - let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, policy) - - SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray) - SecTrustSetAnchorCertificatesOnly(serverTrust, true) - - serverTrustIsValid = trustIsValid(serverTrust) - } else { - let serverCertificatesDataArray = certificateData(for: serverTrust) - let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates) - - outerLoop: for serverCertificateData in serverCertificatesDataArray { - for pinnedCertificateData in pinnedCertificatesDataArray { - if serverCertificateData == pinnedCertificateData { - serverTrustIsValid = true - break outerLoop - } - } - } - } - case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost): - var certificateChainEvaluationPassed = true - - if validateCertificateChain { - let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil) - SecTrustSetPolicies(serverTrust, policy) - - certificateChainEvaluationPassed = trustIsValid(serverTrust) - } - - if certificateChainEvaluationPassed { - outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] { - for pinnedPublicKey in pinnedPublicKeys as [AnyObject] { - if serverPublicKey.isEqual(pinnedPublicKey) { - serverTrustIsValid = true - break outerLoop - } - } - } - } - case .disableEvaluation: - serverTrustIsValid = true - case let .customEvaluation(closure): - serverTrustIsValid = closure(serverTrust, host) - } - - return serverTrustIsValid - } - - // MARK: - Private - Trust Validation - - private func trustIsValid(_ trust: SecTrust) -> Bool { - var isValid = false - - var result = SecTrustResultType.invalid - let status = SecTrustEvaluate(trust, &result) - - if status == errSecSuccess { - let unspecified = SecTrustResultType.unspecified - let proceed = SecTrustResultType.proceed - - isValid = result == unspecified || result == proceed - } - - return isValid - } - - // MARK: - Private - Certificate Data - - private func certificateData(for trust: SecTrust) -> [Data] { - var certificates: [SecCertificate] = [] - - for index in 0.. [Data] { - return certificates.map { SecCertificateCopyData($0) as Data } - } - - // MARK: - Private - Public Key Extraction - - private static func publicKeys(for trust: SecTrust) -> [SecKey] { - var publicKeys: [SecKey] = [] - - for index in 0.. SecKey? { - var publicKey: SecKey? - - let policy = SecPolicyCreateBasicX509() - var trust: SecTrust? - let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust) - - if let trust = trust, trustCreationStatus == errSecSuccess { - publicKey = SecTrustCopyPublicKey(trust) - } - - return publicKey - } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/SessionDelegate.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/SessionDelegate.swift deleted file mode 100644 index 5cf4a385b2a5..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/SessionDelegate.swift +++ /dev/null @@ -1,713 +0,0 @@ -// -// SessionDelegate.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Responsible for handling all delegate callbacks for the underlying session. -open class SessionDelegate: NSObject { - - // MARK: URLSessionDelegate Overrides - - /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`. - open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)? - - /// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`. - open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? - - /// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`. - open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`. - open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)? - - // MARK: URLSessionTaskDelegate Overrides - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`. - open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? - - /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and - /// requires the caller to call the `completionHandler`. - open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`. - open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? - - /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and - /// requires the caller to call the `completionHandler`. - open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`. - open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? - - /// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and - /// requires the caller to call the `completionHandler`. - open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, @escaping (InputStream?) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`. - open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? - - /// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`. - open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)? - - // MARK: URLSessionDataDelegate Overrides - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`. - open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? - - /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and - /// requires caller to call the `completionHandler`. - open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, @escaping (URLSession.ResponseDisposition) -> Void) -> Void)? - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`. - open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`. - open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? - - /// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`. - open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? - - /// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and - /// requires caller to call the `completionHandler`. - open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, @escaping (CachedURLResponse?) -> Void) -> Void)? - - // MARK: URLSessionDownloadDelegate Overrides - - /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`. - open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)? - - /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`. - open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? - - /// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`. - open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? - - // MARK: URLSessionStreamDelegate Overrides - -#if !os(watchOS) - - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)? { - get { - return _streamTaskReadClosed as? (URLSession, URLSessionStreamTask) -> Void - } - set { - _streamTaskReadClosed = newValue - } - } - - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)? { - get { - return _streamTaskWriteClosed as? (URLSession, URLSessionStreamTask) -> Void - } - set { - _streamTaskWriteClosed = newValue - } - } - - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)? { - get { - return _streamTaskBetterRouteDiscovered as? (URLSession, URLSessionStreamTask) -> Void - } - set { - _streamTaskBetterRouteDiscovered = newValue - } - } - - /// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`. - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)? { - get { - return _streamTaskDidBecomeInputStream as? (URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void - } - set { - _streamTaskDidBecomeInputStream = newValue - } - } - - var _streamTaskReadClosed: Any? - var _streamTaskWriteClosed: Any? - var _streamTaskBetterRouteDiscovered: Any? - var _streamTaskDidBecomeInputStream: Any? - -#endif - - // MARK: Properties - - var retrier: RequestRetrier? - weak var sessionManager: SessionManager? - - var requests: [Int: Request] = [:] - private let lock = NSLock() - - /// Access the task delegate for the specified task in a thread-safe manner. - open subscript(task: URLSessionTask) -> Request? { - get { - lock.lock() ; defer { lock.unlock() } - return requests[task.taskIdentifier] - } - set { - lock.lock() ; defer { lock.unlock() } - requests[task.taskIdentifier] = newValue - } - } - - // MARK: Lifecycle - - /// Initializes the `SessionDelegate` instance. - /// - /// - returns: The new `SessionDelegate` instance. - public override init() { - super.init() - } - - // MARK: NSObject Overrides - - /// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond - /// to a specified message. - /// - /// - parameter selector: A selector that identifies a message. - /// - /// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`. - open override func responds(to selector: Selector) -> Bool { - #if !os(macOS) - if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) { - return sessionDidFinishEventsForBackgroundURLSession != nil - } - #endif - - #if !os(watchOS) - if #available(iOS 9.0, macOS 10.11, tvOS 9.0, *) { - switch selector { - case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)): - return streamTaskReadClosed != nil - case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)): - return streamTaskWriteClosed != nil - case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)): - return streamTaskBetterRouteDiscovered != nil - case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)): - return streamTaskDidBecomeInputAndOutputStreams != nil - default: - break - } - } - #endif - - switch selector { - case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)): - return sessionDidBecomeInvalidWithError != nil - case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)): - return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil) - case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)): - return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil) - case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)): - return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil) - default: - return type(of: self).instancesRespond(to: selector) - } - } -} - -// MARK: - URLSessionDelegate - -extension SessionDelegate: URLSessionDelegate { - /// Tells the delegate that the session has been invalidated. - /// - /// - parameter session: The session object that was invalidated. - /// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. - open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) { - sessionDidBecomeInvalidWithError?(session, error) - } - - /// Requests credentials from the delegate in response to a session-level authentication request from the - /// remote server. - /// - /// - parameter session: The session containing the task that requested authentication. - /// - parameter challenge: An object that contains the request for authentication. - /// - parameter completionHandler: A handler that your delegate method must call providing the disposition - /// and credential. - open func urlSession( - _ session: URLSession, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { - guard sessionDidReceiveChallengeWithCompletion == nil else { - sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler) - return - } - - var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling - var credential: URLCredential? - - if let sessionDidReceiveChallenge = sessionDidReceiveChallenge { - (disposition, credential) = sessionDidReceiveChallenge(session, challenge) - } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { - let host = challenge.protectionSpace.host - - if - let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), - let serverTrust = challenge.protectionSpace.serverTrust - { - if serverTrustPolicy.evaluate(serverTrust, forHost: host) { - disposition = .useCredential - credential = URLCredential(trust: serverTrust) - } else { - disposition = .cancelAuthenticationChallenge - } - } - } - - completionHandler(disposition, credential) - } - -#if !os(macOS) - - /// Tells the delegate that all messages enqueued for a session have been delivered. - /// - /// - parameter session: The session that no longer has any outstanding requests. - open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { - sessionDidFinishEventsForBackgroundURLSession?(session) - } - -#endif -} - -// MARK: - URLSessionTaskDelegate - -extension SessionDelegate: URLSessionTaskDelegate { - /// Tells the delegate that the remote server requested an HTTP redirect. - /// - /// - parameter session: The session containing the task whose request resulted in a redirect. - /// - parameter task: The task whose request resulted in a redirect. - /// - parameter response: An object containing the server’s response to the original request. - /// - parameter request: A URL request object filled out with the new location. - /// - parameter completionHandler: A closure that your handler should call with either the value of the request - /// parameter, a modified URL request object, or NULL to refuse the redirect and - /// return the body of the redirect response. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest, - completionHandler: @escaping (URLRequest?) -> Void) { - guard taskWillPerformHTTPRedirectionWithCompletion == nil else { - taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler) - return - } - - var redirectRequest: URLRequest? = request - - if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { - redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) - } - - completionHandler(redirectRequest) - } - - /// Requests credentials from the delegate in response to an authentication request from the remote server. - /// - /// - parameter session: The session containing the task whose request requires authentication. - /// - parameter task: The task whose request requires authentication. - /// - parameter challenge: An object that contains the request for authentication. - /// - parameter completionHandler: A handler that your delegate method must call providing the disposition - /// and credential. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { - guard taskDidReceiveChallengeWithCompletion == nil else { - taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler) - return - } - - if let taskDidReceiveChallenge = taskDidReceiveChallenge { - let result = taskDidReceiveChallenge(session, task, challenge) - completionHandler(result.0, result.1) - } else if let delegate = self[task]?.delegate { - delegate.urlSession( - session, - task: task, - didReceive: challenge, - completionHandler: completionHandler - ) - } else { - urlSession(session, didReceive: challenge, completionHandler: completionHandler) - } - } - - /// Tells the delegate when a task requires a new request body stream to send to the remote server. - /// - /// - parameter session: The session containing the task that needs a new body stream. - /// - parameter task: The task that needs a new body stream. - /// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { - guard taskNeedNewBodyStreamWithCompletion == nil else { - taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler) - return - } - - if let taskNeedNewBodyStream = taskNeedNewBodyStream { - completionHandler(taskNeedNewBodyStream(session, task)) - } else if let delegate = self[task]?.delegate { - delegate.urlSession(session, task: task, needNewBodyStream: completionHandler) - } - } - - /// Periodically informs the delegate of the progress of sending body content to the server. - /// - /// - parameter session: The session containing the data task. - /// - parameter task: The data task. - /// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called. - /// - parameter totalBytesSent: The total number of bytes sent so far. - /// - parameter totalBytesExpectedToSend: The expected length of the body data. - open func urlSession( - _ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) { - if let taskDidSendBodyData = taskDidSendBodyData { - taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) - } else if let delegate = self[task]?.delegate as? UploadTaskDelegate { - delegate.URLSession( - session, - task: task, - didSendBodyData: bytesSent, - totalBytesSent: totalBytesSent, - totalBytesExpectedToSend: totalBytesExpectedToSend - ) - } - } - -#if !os(watchOS) - - /// Tells the delegate that the session finished collecting metrics for the task. - /// - /// - parameter session: The session collecting the metrics. - /// - parameter task: The task whose metrics have been collected. - /// - parameter metrics: The collected metrics. - @available(iOS 10.0, macOS 10.12, tvOS 10.0, *) - @objc(URLSession:task:didFinishCollectingMetrics:) - open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) { - self[task]?.delegate.metrics = metrics - } - -#endif - - /// Tells the delegate that the task finished transferring data. - /// - /// - parameter session: The session containing the task whose request finished transferring data. - /// - parameter task: The task whose request finished transferring data. - /// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil. - open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - /// Executed after it is determined that the request is not going to be retried - let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in - guard let strongSelf = self else { return } - - strongSelf.taskDidComplete?(session, task, error) - - strongSelf[task]?.delegate.urlSession(session, task: task, didCompleteWithError: error) - - var userInfo: [String: Any] = [Notification.Key.Task: task] - - if let data = (strongSelf[task]?.delegate as? DataTaskDelegate)?.data { - userInfo[Notification.Key.ResponseData] = data - } - - NotificationCenter.default.post( - name: Notification.Name.Task.DidComplete, - object: strongSelf, - userInfo: userInfo - ) - - strongSelf[task] = nil - } - - guard let request = self[task], let sessionManager = sessionManager else { - completeTask(session, task, error) - return - } - - // Run all validations on the request before checking if an error occurred - request.validations.forEach { $0() } - - // Determine whether an error has occurred - var error: Error? = error - - if request.delegate.error != nil { - error = request.delegate.error - } - - /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request - /// should be retried. Otherwise, complete the task by notifying the task delegate. - if let retrier = retrier, let error = error { - retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, timeDelay in - guard shouldRetry else { completeTask(session, task, error) ; return } - - DispatchQueue.utility.after(timeDelay) { [weak self] in - guard let strongSelf = self else { return } - - let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false - - if retrySucceeded, let task = request.task { - strongSelf[task] = request - return - } else { - completeTask(session, task, error) - } - } - } - } else { - completeTask(session, task, error) - } - } -} - -// MARK: - URLSessionDataDelegate - -extension SessionDelegate: URLSessionDataDelegate { - /// Tells the delegate that the data task received the initial reply (headers) from the server. - /// - /// - parameter session: The session containing the data task that received an initial reply. - /// - parameter dataTask: The data task that received an initial reply. - /// - parameter response: A URL response object populated with headers. - /// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a - /// constant to indicate whether the transfer should continue as a data task or - /// should become a download task. - open func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didReceive response: URLResponse, - completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { - guard dataTaskDidReceiveResponseWithCompletion == nil else { - dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler) - return - } - - var disposition: URLSession.ResponseDisposition = .allow - - if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { - disposition = dataTaskDidReceiveResponse(session, dataTask, response) - } - - completionHandler(disposition) - } - - /// Tells the delegate that the data task was changed to a download task. - /// - /// - parameter session: The session containing the task that was replaced by a download task. - /// - parameter dataTask: The data task that was replaced by a download task. - /// - parameter downloadTask: The new download task that replaced the data task. - open func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didBecome downloadTask: URLSessionDownloadTask) { - if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask { - dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) - } else { - self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask) - } - } - - /// Tells the delegate that the data task has received some of the expected data. - /// - /// - parameter session: The session containing the data task that provided data. - /// - parameter dataTask: The data task that provided data. - /// - parameter data: A data object containing the transferred data. - open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - if let dataTaskDidReceiveData = dataTaskDidReceiveData { - dataTaskDidReceiveData(session, dataTask, data) - } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { - delegate.urlSession(session, dataTask: dataTask, didReceive: data) - } - } - - /// Asks the delegate whether the data (or upload) task should store the response in the cache. - /// - /// - parameter session: The session containing the data (or upload) task. - /// - parameter dataTask: The data (or upload) task. - /// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current - /// caching policy and the values of certain received headers, such as the Pragma - /// and Cache-Control headers. - /// - parameter completionHandler: A block that your handler must call, providing either the original proposed - /// response, a modified version of that response, or NULL to prevent caching the - /// response. If your delegate implements this method, it must call this completion - /// handler; otherwise, your app leaks memory. - open func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse, - completionHandler: @escaping (CachedURLResponse?) -> Void) { - guard dataTaskWillCacheResponseWithCompletion == nil else { - dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler) - return - } - - if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { - completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) - } else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate { - delegate.urlSession( - session, - dataTask: dataTask, - willCacheResponse: proposedResponse, - completionHandler: completionHandler - ) - } else { - completionHandler(proposedResponse) - } - } -} - -// MARK: - URLSessionDownloadDelegate - -extension SessionDelegate: URLSessionDownloadDelegate { - /// Tells the delegate that a download task has finished downloading. - /// - /// - parameter session: The session containing the download task that finished. - /// - parameter downloadTask: The download task that finished. - /// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either - /// open the file for reading or move it to a permanent location in your app’s sandbox - /// container directory before returning from this delegate method. - open func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) { - if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL { - downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) - } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { - delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location) - } - } - - /// Periodically informs the delegate about the download’s progress. - /// - /// - parameter session: The session containing the download task. - /// - parameter downloadTask: The download task. - /// - parameter bytesWritten: The number of bytes transferred since the last time this delegate - /// method was called. - /// - parameter totalBytesWritten: The total number of bytes transferred so far. - /// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length - /// header. If this header was not provided, the value is - /// `NSURLSessionTransferSizeUnknown`. - open func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) { - if let downloadTaskDidWriteData = downloadTaskDidWriteData { - downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) - } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { - delegate.urlSession( - session, - downloadTask: downloadTask, - didWriteData: bytesWritten, - totalBytesWritten: totalBytesWritten, - totalBytesExpectedToWrite: totalBytesExpectedToWrite - ) - } - } - - /// Tells the delegate that the download task has resumed downloading. - /// - /// - parameter session: The session containing the download task that finished. - /// - parameter downloadTask: The download task that resumed. See explanation in the discussion. - /// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the - /// existing content, then this value is zero. Otherwise, this value is an - /// integer representing the number of bytes on disk that do not need to be - /// retrieved again. - /// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header. - /// If this header was not provided, the value is NSURLSessionTransferSizeUnknown. - open func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) { - if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { - downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) - } else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate { - delegate.urlSession( - session, - downloadTask: downloadTask, - didResumeAtOffset: fileOffset, - expectedTotalBytes: expectedTotalBytes - ) - } - } -} - -// MARK: - URLSessionStreamDelegate - -#if !os(watchOS) - -@available(iOS 9.0, macOS 10.11, tvOS 9.0, *) -extension SessionDelegate: URLSessionStreamDelegate { - /// Tells the delegate that the read side of the connection has been closed. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) { - streamTaskReadClosed?(session, streamTask) - } - - /// Tells the delegate that the write side of the connection has been closed. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) { - streamTaskWriteClosed?(session, streamTask) - } - - /// Tells the delegate that the system has determined that a better route to the host is available. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) { - streamTaskBetterRouteDiscovered?(session, streamTask) - } - - /// Tells the delegate that the stream task has been completed and provides the unopened stream objects. - /// - /// - parameter session: The session. - /// - parameter streamTask: The stream task. - /// - parameter inputStream: The new input stream. - /// - parameter outputStream: The new output stream. - open func urlSession( - _ session: URLSession, - streamTask: URLSessionStreamTask, - didBecome inputStream: InputStream, - outputStream: OutputStream) { - streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream) - } -} - -#endif diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/SessionManager.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/SessionManager.swift deleted file mode 100644 index 19725f287e0c..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/SessionManager.swift +++ /dev/null @@ -1,886 +0,0 @@ -// -// SessionManager.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. -open class SessionManager { - - // MARK: - Helper Types - - /// Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as - /// associated values. - /// - /// - Success: Represents a successful `MultipartFormData` encoding and contains the new `UploadRequest` along with - /// streaming information. - /// - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding - /// error. - public enum MultipartFormDataEncodingResult { - case success(request: UploadRequest, streamingFromDisk: Bool, streamFileURL: URL?) - case failure(Error) - } - - // MARK: - Properties - - /// A default instance of `SessionManager`, used by top-level Alamofire request methods, and suitable for use - /// directly for any ad hoc requests. - public static let `default`: SessionManager = { - let configuration = URLSessionConfiguration.default - configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders - - return SessionManager(configuration: configuration) - }() - - /// Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. - public static let defaultHTTPHeaders: HTTPHeaders = { - // Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3 - let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" - - // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 - let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { index, languageCode in - let quality = 1.0 - (Double(index) * 0.1) - return "\(languageCode);q=\(quality)" - }.joined(separator: ", ") - - // User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3 - // Example: `iOS Example/1.0 (org.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0` - let userAgent: String = { - if let info = Bundle.main.infoDictionary { - let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" - let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" - let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown" - let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown" - - let osNameVersion: String = { - let version = ProcessInfo.processInfo.operatingSystemVersion - let versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" - - let osName: String = { - #if os(iOS) - return "iOS" - #elseif os(watchOS) - return "watchOS" - #elseif os(tvOS) - return "tvOS" - #elseif os(macOS) - return "OS X" - #elseif os(Linux) - return "Linux" - #else - return "Unknown" - #endif - }() - - return "\(osName) \(versionString)" - }() - - let alamofireVersion: String = { - guard - let afInfo = Bundle(for: SessionManager.self).infoDictionary, - let build = afInfo["CFBundleShortVersionString"] - else { return "Unknown" } - - return "Alamofire/\(build)" - }() - - return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)" - } - - return "Alamofire" - }() - - return [ - "Accept-Encoding": acceptEncoding, - "Accept-Language": acceptLanguage, - "User-Agent": userAgent - ] - }() - - /// Default memory threshold used when encoding `MultipartFormData` in bytes. - public static let multipartFormDataEncodingMemoryThreshold: UInt64 = 10_000_000 - - /// The underlying session. - public let session: URLSession - - /// The session delegate handling all the task and session delegate callbacks. - public let delegate: SessionDelegate - - /// Whether to start requests immediately after being constructed. `true` by default. - open var startRequestsImmediately: Bool = true - - /// The request adapter called each time a new request is created. - open var adapter: RequestAdapter? - - /// The request retrier called each time a request encounters an error to determine whether to retry the request. - open var retrier: RequestRetrier? { - get { return delegate.retrier } - set { delegate.retrier = newValue } - } - - /// The background completion handler closure provided by the UIApplicationDelegate - /// `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background - /// completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation - /// will automatically call the handler. - /// - /// If you need to handle your own events before the handler is called, then you need to override the - /// SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. - /// - /// `nil` by default. - open var backgroundCompletionHandler: (() -> Void)? - - let queue = DispatchQueue(label: "org.alamofire.session-manager." + UUID().uuidString) - - // MARK: - Lifecycle - - /// Creates an instance with the specified `configuration`, `delegate` and `serverTrustPolicyManager`. - /// - /// - parameter configuration: The configuration used to construct the managed session. - /// `URLSessionConfiguration.default` by default. - /// - parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by - /// default. - /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust - /// challenges. `nil` by default. - /// - /// - returns: The new `SessionManager` instance. - public init( - configuration: URLSessionConfiguration = URLSessionConfiguration.default, - delegate: SessionDelegate = SessionDelegate(), - serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { - self.delegate = delegate - self.session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) - - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) - } - - /// Creates an instance with the specified `session`, `delegate` and `serverTrustPolicyManager`. - /// - /// - parameter session: The URL session. - /// - parameter delegate: The delegate of the URL session. Must equal the URL session's delegate. - /// - parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust - /// challenges. `nil` by default. - /// - /// - returns: The new `SessionManager` instance if the URL session's delegate matches; `nil` otherwise. - public init?( - session: URLSession, - delegate: SessionDelegate, - serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { - guard delegate === session.delegate else { return nil } - - self.delegate = delegate - self.session = session - - commonInit(serverTrustPolicyManager: serverTrustPolicyManager) - } - - private func commonInit(serverTrustPolicyManager: ServerTrustPolicyManager?) { - session.serverTrustPolicyManager = serverTrustPolicyManager - - delegate.sessionManager = self - - delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in - guard let strongSelf = self else { return } - DispatchQueue.main.async { strongSelf.backgroundCompletionHandler?() } - } - } - - deinit { - session.invalidateAndCancel() - } - - // MARK: - Data Request - - /// Creates a `DataRequest` to retrieve the contents of the specified `url`, `method`, `parameters`, `encoding` - /// and `headers`. - /// - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.get` by default. - /// - parameter parameters: The parameters. `nil` by default. - /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `DataRequest`. - @discardableResult - open func request( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil) - -> DataRequest { - var originalRequest: URLRequest? - - do { - originalRequest = try URLRequest(url: url, method: method, headers: headers) - let encodedURLRequest = try encoding.encode(originalRequest!, with: parameters) - return request(encodedURLRequest) - } catch { - return request(originalRequest, failedWith: error) - } - } - - /// Creates a `DataRequest` to retrieve the contents of a URL based on the specified `urlRequest`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `DataRequest`. - @discardableResult - open func request(_ urlRequest: URLRequestConvertible) -> DataRequest { - var originalRequest: URLRequest? - - do { - originalRequest = try urlRequest.asURLRequest() - let originalTask = DataRequest.Requestable(urlRequest: originalRequest!) - - let task = try originalTask.task(session: session, adapter: adapter, queue: queue) - let request = DataRequest(session: session, requestTask: .data(originalTask, task)) - - delegate[task] = request - - if startRequestsImmediately { request.resume() } - - return request - } catch { - return request(originalRequest, failedWith: error) - } - } - - // MARK: Private - Request Implementation - - private func request(_ urlRequest: URLRequest?, failedWith error: Error) -> DataRequest { - var requestTask: Request.RequestTask = .data(nil, nil) - - if let urlRequest = urlRequest { - let originalTask = DataRequest.Requestable(urlRequest: urlRequest) - requestTask = .data(originalTask, nil) - } - - let underlyingError = error.underlyingAdaptError ?? error - let request = DataRequest(session: session, requestTask: requestTask, error: underlyingError) - - if let retrier = retrier, error is AdaptError { - allowRetrier(retrier, toRetry: request, with: underlyingError) - } else { - if startRequestsImmediately { request.resume() } - } - - return request - } - - // MARK: - Download Request - - // MARK: URL Request - - /// Creates a `DownloadRequest` to retrieve the contents the specified `url`, `method`, `parameters`, `encoding`, - /// `headers` and save them to the `destination`. - /// - /// If `destination` is not specified, the contents will remain in the temporary location determined by the - /// underlying URL session. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.get` by default. - /// - parameter parameters: The parameters. `nil` by default. - /// - parameter encoding: The parameter encoding. `URLEncoding.default` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. - /// - /// - returns: The created `DownloadRequest`. - @discardableResult - open func download( - _ url: URLConvertible, - method: HTTPMethod = .get, - parameters: Parameters? = nil, - encoding: ParameterEncoding = URLEncoding.default, - headers: HTTPHeaders? = nil, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - let encodedURLRequest = try encoding.encode(urlRequest, with: parameters) - return download(encodedURLRequest, to: destination) - } catch { - return download(nil, to: destination, failedWith: error) - } - } - - /// Creates a `DownloadRequest` to retrieve the contents of a URL based on the specified `urlRequest` and save - /// them to the `destination`. - /// - /// If `destination` is not specified, the contents will remain in the temporary location determined by the - /// underlying URL session. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter urlRequest: The URL request - /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. - /// - /// - returns: The created `DownloadRequest`. - @discardableResult - open func download( - _ urlRequest: URLRequestConvertible, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - do { - let urlRequest = try urlRequest.asURLRequest() - return download(.request(urlRequest), to: destination) - } catch { - return download(nil, to: destination, failedWith: error) - } - } - - // MARK: Resume Data - - /// Creates a `DownloadRequest` from the `resumeData` produced from a previous request cancellation to retrieve - /// the contents of the original request and save them to the `destination`. - /// - /// If `destination` is not specified, the contents will remain in the temporary location determined by the - /// underlying URL session. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), `resumeData` is broken - /// on background URL session configurations. There's an underlying bug in the `resumeData` generation logic where the - /// data is written incorrectly and will always fail to resume the download. For more information about the bug and - /// possible workarounds, please refer to the following Stack Overflow post: - /// - /// - http://stackoverflow.com/a/39347461/1342462 - /// - /// - parameter resumeData: The resume data. This is an opaque data blob produced by `URLSessionDownloadTask` - /// when a task is cancelled. See `URLSession -downloadTask(withResumeData:)` for - /// additional information. - /// - parameter destination: The closure used to determine the destination of the downloaded file. `nil` by default. - /// - /// - returns: The created `DownloadRequest`. - @discardableResult - open func download( - resumingWith resumeData: Data, - to destination: DownloadRequest.DownloadFileDestination? = nil) - -> DownloadRequest { - return download(.resumeData(resumeData), to: destination) - } - - // MARK: Private - Download Implementation - - private func download( - _ downloadable: DownloadRequest.Downloadable, - to destination: DownloadRequest.DownloadFileDestination?) - -> DownloadRequest { - do { - let task = try downloadable.task(session: session, adapter: adapter, queue: queue) - let download = DownloadRequest(session: session, requestTask: .download(downloadable, task)) - - download.downloadDelegate.destination = destination - - delegate[task] = download - - if startRequestsImmediately { download.resume() } - - return download - } catch { - return download(downloadable, to: destination, failedWith: error) - } - } - - private func download( - _ downloadable: DownloadRequest.Downloadable?, - to destination: DownloadRequest.DownloadFileDestination?, - failedWith error: Error) - -> DownloadRequest { - var downloadTask: Request.RequestTask = .download(nil, nil) - - if let downloadable = downloadable { - downloadTask = .download(downloadable, nil) - } - - let underlyingError = error.underlyingAdaptError ?? error - - let download = DownloadRequest(session: session, requestTask: downloadTask, error: underlyingError) - download.downloadDelegate.destination = destination - - if let retrier = retrier, error is AdaptError { - allowRetrier(retrier, toRetry: download, with: underlyingError) - } else { - if startRequestsImmediately { download.resume() } - } - - return download - } - - // MARK: - Upload Request - - // MARK: File - - /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `file`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter file: The file to upload. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload( - _ fileURL: URL, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - return upload(fileURL, with: urlRequest) - } catch { - return upload(nil, failedWith: error) - } - } - - /// Creates a `UploadRequest` from the specified `urlRequest` for uploading the `file`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter file: The file to upload. - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload(_ fileURL: URL, with urlRequest: URLRequestConvertible) -> UploadRequest { - do { - let urlRequest = try urlRequest.asURLRequest() - return upload(.file(fileURL, urlRequest)) - } catch { - return upload(nil, failedWith: error) - } - } - - // MARK: Data - - /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `data`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter data: The data to upload. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload( - _ data: Data, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - return upload(data, with: urlRequest) - } catch { - return upload(nil, failedWith: error) - } - } - - /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `data`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter data: The data to upload. - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload(_ data: Data, with urlRequest: URLRequestConvertible) -> UploadRequest { - do { - let urlRequest = try urlRequest.asURLRequest() - return upload(.data(data, urlRequest)) - } catch { - return upload(nil, failedWith: error) - } - } - - // MARK: InputStream - - /// Creates an `UploadRequest` from the specified `url`, `method` and `headers` for uploading the `stream`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter stream: The stream to upload. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload( - _ stream: InputStream, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil) - -> UploadRequest { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - return upload(stream, with: urlRequest) - } catch { - return upload(nil, failedWith: error) - } - } - - /// Creates an `UploadRequest` from the specified `urlRequest` for uploading the `stream`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter stream: The stream to upload. - /// - parameter urlRequest: The URL request. - /// - /// - returns: The created `UploadRequest`. - @discardableResult - open func upload(_ stream: InputStream, with urlRequest: URLRequestConvertible) -> UploadRequest { - do { - let urlRequest = try urlRequest.asURLRequest() - return upload(.stream(stream, urlRequest)) - } catch { - return upload(nil, failedWith: error) - } - } - - // MARK: MultipartFormData - - /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new - /// `UploadRequest` using the `url`, `method` and `headers`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. - /// `multipartFormDataEncodingMemoryThreshold` by default. - /// - parameter url: The URL. - /// - parameter method: The HTTP method. `.post` by default. - /// - parameter headers: The HTTP headers. `nil` by default. - /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. - open func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - to url: URLConvertible, - method: HTTPMethod = .post, - headers: HTTPHeaders? = nil, - queue: DispatchQueue? = nil, - encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { - do { - let urlRequest = try URLRequest(url: url, method: method, headers: headers) - - return upload( - multipartFormData: multipartFormData, - usingThreshold: encodingMemoryThreshold, - with: urlRequest, - queue: queue, - encodingCompletion: encodingCompletion - ) - } catch { - (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } - } - } - - /// Encodes `multipartFormData` using `encodingMemoryThreshold` and calls `encodingCompletion` with new - /// `UploadRequest` using the `urlRequest`. - /// - /// It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative - /// payload is small, encoding the data in-memory and directly uploading to a server is the by far the most - /// efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to - /// be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory - /// footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be - /// used for larger payloads such as video content. - /// - /// The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory - /// or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, - /// encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk - /// during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding - /// technique was used. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - /// - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. - /// `multipartFormDataEncodingMemoryThreshold` by default. - /// - parameter urlRequest: The URL request. - /// - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. - open func upload( - multipartFormData: @escaping (MultipartFormData) -> Void, - usingThreshold encodingMemoryThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, - with urlRequest: URLRequestConvertible, - queue: DispatchQueue? = nil, - encodingCompletion: ((MultipartFormDataEncodingResult) -> Void)?) { - DispatchQueue.global(qos: .utility).async { - let formData = MultipartFormData() - multipartFormData(formData) - - var tempFileURL: URL? - - do { - var urlRequestWithContentType = try urlRequest.asURLRequest() - urlRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") - - let isBackgroundSession = self.session.configuration.identifier != nil - - if formData.contentLength < encodingMemoryThreshold && !isBackgroundSession { - let data = try formData.encode() - - let encodingResult = MultipartFormDataEncodingResult.success( - request: self.upload(data, with: urlRequestWithContentType), - streamingFromDisk: false, - streamFileURL: nil - ) - - (queue ?? DispatchQueue.main).async { encodingCompletion?(encodingResult) } - } else { - let fileManager = FileManager.default - let tempDirectoryURL = URL(fileURLWithPath: NSTemporaryDirectory()) - let directoryURL = tempDirectoryURL.appendingPathComponent("org.alamofire.manager/multipart.form.data") - let fileName = UUID().uuidString - let fileURL = directoryURL.appendingPathComponent(fileName) - - tempFileURL = fileURL - - var directoryError: Error? - - // Create directory inside serial queue to ensure two threads don't do this in parallel - self.queue.sync { - do { - try fileManager.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil) - } catch { - directoryError = error - } - } - - if let directoryError = directoryError { throw directoryError } - - try formData.writeEncodedData(to: fileURL) - - let upload = self.upload(fileURL, with: urlRequestWithContentType) - - // Cleanup the temp file once the upload is complete - upload.delegate.queue.addOperation { - do { - try FileManager.default.removeItem(at: fileURL) - } catch { - // No-op - } - } - - (queue ?? DispatchQueue.main).async { - let encodingResult = MultipartFormDataEncodingResult.success( - request: upload, - streamingFromDisk: true, - streamFileURL: fileURL - ) - - encodingCompletion?(encodingResult) - } - } - } catch { - // Cleanup the temp file in the event that the multipart form data encoding failed - if let tempFileURL = tempFileURL { - do { - try FileManager.default.removeItem(at: tempFileURL) - } catch { - // No-op - } - } - - (queue ?? DispatchQueue.main).async { encodingCompletion?(.failure(error)) } - } - } - } - - // MARK: Private - Upload Implementation - - private func upload(_ uploadable: UploadRequest.Uploadable) -> UploadRequest { - do { - let task = try uploadable.task(session: session, adapter: adapter, queue: queue) - let upload = UploadRequest(session: session, requestTask: .upload(uploadable, task)) - - if case let .stream(inputStream, _) = uploadable { - upload.delegate.taskNeedNewBodyStream = { _, _ in inputStream } - } - - delegate[task] = upload - - if startRequestsImmediately { upload.resume() } - - return upload - } catch { - return upload(uploadable, failedWith: error) - } - } - - private func upload(_ uploadable: UploadRequest.Uploadable?, failedWith error: Error) -> UploadRequest { - var uploadTask: Request.RequestTask = .upload(nil, nil) - - if let uploadable = uploadable { - uploadTask = .upload(uploadable, nil) - } - - let underlyingError = error.underlyingAdaptError ?? error - let upload = UploadRequest(session: session, requestTask: uploadTask, error: underlyingError) - - if let retrier = retrier, error is AdaptError { - allowRetrier(retrier, toRetry: upload, with: underlyingError) - } else { - if startRequestsImmediately { upload.resume() } - } - - return upload - } - -#if !os(watchOS) - - // MARK: - Stream Request - - // MARK: Hostname and Port - - /// Creates a `StreamRequest` for bidirectional streaming using the `hostname` and `port`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter hostName: The hostname of the server to connect to. - /// - parameter port: The port of the server to connect to. - /// - /// - returns: The created `StreamRequest`. - @discardableResult - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open func stream(withHostName hostName: String, port: Int) -> StreamRequest { - return stream(.stream(hostName: hostName, port: port)) - } - - // MARK: NetService - - /// Creates a `StreamRequest` for bidirectional streaming using the `netService`. - /// - /// If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - /// - /// - parameter netService: The net service used to identify the endpoint. - /// - /// - returns: The created `StreamRequest`. - @discardableResult - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - open func stream(with netService: NetService) -> StreamRequest { - return stream(.netService(netService)) - } - - // MARK: Private - Stream Implementation - - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - private func stream(_ streamable: StreamRequest.Streamable) -> StreamRequest { - do { - let task = try streamable.task(session: session, adapter: adapter, queue: queue) - let request = StreamRequest(session: session, requestTask: .stream(streamable, task)) - - delegate[task] = request - - if startRequestsImmediately { request.resume() } - - return request - } catch { - return stream(failedWith: error) - } - } - - @available(iOS 9.0, macOS 10.11, tvOS 9.0, *) - private func stream(failedWith error: Error) -> StreamRequest { - let stream = StreamRequest(session: session, requestTask: .stream(nil, nil), error: error) - if startRequestsImmediately { stream.resume() } - return stream - } - -#endif - - // MARK: - Internal - Retry Request - - func retry(_ request: Request) -> Bool { - guard let originalTask = request.originalTask else { return false } - - do { - let task = try originalTask.task(session: session, adapter: adapter, queue: queue) - - if let originalTask = request.task { - delegate[originalTask] = nil // removes the old request to avoid endless growth - } - - request.delegate.task = task // resets all task delegate data - - request.retryCount += 1 - request.startTime = CFAbsoluteTimeGetCurrent() - request.endTime = nil - - task.resume() - - return true - } catch { - request.delegate.error = error.underlyingAdaptError ?? error - return false - } - } - - private func allowRetrier(_ retrier: RequestRetrier, toRetry request: Request, with error: Error) { - DispatchQueue.utility.async { [weak self] in - guard let strongSelf = self else { return } - - retrier.should(strongSelf, retry: request, with: error) { shouldRetry, timeDelay in - guard let strongSelf = self else { return } - - guard shouldRetry else { - if strongSelf.startRequestsImmediately { request.resume() } - return - } - - DispatchQueue.utility.after(timeDelay) { - guard let strongSelf = self else { return } - - let retrySucceeded = strongSelf.retry(request) - - if retrySucceeded, let task = request.task { - strongSelf.delegate[task] = request - } else { - if strongSelf.startRequestsImmediately { request.resume() } - } - } - } - } - } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/TaskDelegate.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/TaskDelegate.swift deleted file mode 100644 index a25d80271d31..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/TaskDelegate.swift +++ /dev/null @@ -1,456 +0,0 @@ -// -// TaskDelegate.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as -/// executing all operations attached to the serial operation queue upon task completion. -open class TaskDelegate: NSObject { - - // MARK: Properties - - /// The serial operation queue used to execute all operations after the task completes. - public let queue: OperationQueue - - /// The data returned by the server. - public var data: Data? { return nil } - - /// The error generated throughout the lifecyle of the task. - public var error: Error? - - var task: URLSessionTask? { - set { - taskLock.lock(); defer { taskLock.unlock() } - _task = newValue - } - get { - taskLock.lock(); defer { taskLock.unlock() } - return _task - } - } - - var initialResponseTime: CFAbsoluteTime? - var credential: URLCredential? - var metrics: AnyObject? // URLSessionTaskMetrics - - private var _task: URLSessionTask? { - didSet { reset() } - } - - private let taskLock = NSLock() - - // MARK: Lifecycle - - init(task: URLSessionTask?) { - _task = task - - self.queue = { - let operationQueue = OperationQueue() - - operationQueue.maxConcurrentOperationCount = 1 - operationQueue.isSuspended = true - operationQueue.qualityOfService = .utility - - return operationQueue - }() - } - - func reset() { - error = nil - initialResponseTime = nil - } - - // MARK: URLSessionTaskDelegate - - var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)? - var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))? - var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)? - var taskDidCompleteWithError: ((URLSession, URLSessionTask, Error?) -> Void)? - - @objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:) - func urlSession( - _ session: URLSession, - task: URLSessionTask, - willPerformHTTPRedirection response: HTTPURLResponse, - newRequest request: URLRequest, - completionHandler: @escaping (URLRequest?) -> Void) { - var redirectRequest: URLRequest? = request - - if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection { - redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) - } - - completionHandler(redirectRequest) - } - - @objc(URLSession:task:didReceiveChallenge:completionHandler:) - func urlSession( - _ session: URLSession, - task: URLSessionTask, - didReceive challenge: URLAuthenticationChallenge, - completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { - var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling - var credential: URLCredential? - - if let taskDidReceiveChallenge = taskDidReceiveChallenge { - (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) - } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { - let host = challenge.protectionSpace.host - - if - let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host), - let serverTrust = challenge.protectionSpace.serverTrust - { - if serverTrustPolicy.evaluate(serverTrust, forHost: host) { - disposition = .useCredential - credential = URLCredential(trust: serverTrust) - } else { - disposition = .cancelAuthenticationChallenge - } - } - } else { - if challenge.previousFailureCount > 0 { - disposition = .rejectProtectionSpace - } else { - credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) - - if credential != nil { - disposition = .useCredential - } - } - } - - completionHandler(disposition, credential) - } - - @objc(URLSession:task:needNewBodyStream:) - func urlSession( - _ session: URLSession, - task: URLSessionTask, - needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) { - var bodyStream: InputStream? - - if let taskNeedNewBodyStream = taskNeedNewBodyStream { - bodyStream = taskNeedNewBodyStream(session, task) - } - - completionHandler(bodyStream) - } - - @objc(URLSession:task:didCompleteWithError:) - func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { - if let taskDidCompleteWithError = taskDidCompleteWithError { - taskDidCompleteWithError(session, task, error) - } else { - if let error = error { - if self.error == nil { self.error = error } - - if - let downloadDelegate = self as? DownloadTaskDelegate, - let resumeData = (error as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as? Data - { - downloadDelegate.resumeData = resumeData - } - } - - queue.isSuspended = false - } - } -} - -// MARK: - - -class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate { - - // MARK: Properties - - var dataTask: URLSessionDataTask { return task as! URLSessionDataTask } - - override var data: Data? { - if dataStream != nil { - return nil - } else { - return mutableData - } - } - - var progress: Progress - var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? - - var dataStream: ((_ data: Data) -> Void)? - - private var totalBytesReceived: Int64 = 0 - private var mutableData: Data - - private var expectedContentLength: Int64? - - // MARK: Lifecycle - - override init(task: URLSessionTask?) { - mutableData = Data() - progress = Progress(totalUnitCount: 0) - - super.init(task: task) - } - - override func reset() { - super.reset() - - progress = Progress(totalUnitCount: 0) - totalBytesReceived = 0 - mutableData = Data() - expectedContentLength = nil - } - - // MARK: URLSessionDataDelegate - - var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)? - var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)? - var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)? - var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)? - - func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didReceive response: URLResponse, - completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) { - var disposition: URLSession.ResponseDisposition = .allow - - expectedContentLength = response.expectedContentLength - - if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse { - disposition = dataTaskDidReceiveResponse(session, dataTask, response) - } - - completionHandler(disposition) - } - - func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - didBecome downloadTask: URLSessionDownloadTask) { - dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask) - } - - func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { - if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } - - if let dataTaskDidReceiveData = dataTaskDidReceiveData { - dataTaskDidReceiveData(session, dataTask, data) - } else { - if let dataStream = dataStream { - dataStream(data) - } else { - mutableData.append(data) - } - - let bytesReceived = Int64(data.count) - totalBytesReceived += bytesReceived - let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown - - progress.totalUnitCount = totalBytesExpected - progress.completedUnitCount = totalBytesReceived - - if let progressHandler = progressHandler { - progressHandler.queue.async { progressHandler.closure(self.progress) } - } - } - } - - func urlSession( - _ session: URLSession, - dataTask: URLSessionDataTask, - willCacheResponse proposedResponse: CachedURLResponse, - completionHandler: @escaping (CachedURLResponse?) -> Void) { - var cachedResponse: CachedURLResponse? = proposedResponse - - if let dataTaskWillCacheResponse = dataTaskWillCacheResponse { - cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse) - } - - completionHandler(cachedResponse) - } -} - -// MARK: - - -class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { - - // MARK: Properties - - var downloadTask: URLSessionDownloadTask { return task as! URLSessionDownloadTask } - - var progress: Progress - var progressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? - - var resumeData: Data? - override var data: Data? { return resumeData } - - var destination: DownloadRequest.DownloadFileDestination? - - var temporaryURL: URL? - var destinationURL: URL? - - var fileURL: URL? { return destination != nil ? destinationURL : temporaryURL } - - // MARK: Lifecycle - - override init(task: URLSessionTask?) { - progress = Progress(totalUnitCount: 0) - super.init(task: task) - } - - override func reset() { - super.reset() - - progress = Progress(totalUnitCount: 0) - resumeData = nil - } - - // MARK: URLSessionDownloadDelegate - - var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? - var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)? - var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)? - - func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didFinishDownloadingTo location: URL) { - temporaryURL = location - - guard - let destination = destination, - let response = downloadTask.response as? HTTPURLResponse - else { return } - - let result = destination(location, response) - let destinationURL = result.destinationURL - let options = result.options - - self.destinationURL = destinationURL - - do { - if options.contains(.removePreviousFile), FileManager.default.fileExists(atPath: destinationURL.path) { - try FileManager.default.removeItem(at: destinationURL) - } - - if options.contains(.createIntermediateDirectories) { - let directory = destinationURL.deletingLastPathComponent() - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - } - - try FileManager.default.moveItem(at: location, to: destinationURL) - } catch { - self.error = error - } - } - - func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didWriteData bytesWritten: Int64, - totalBytesWritten: Int64, - totalBytesExpectedToWrite: Int64) { - if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } - - if let downloadTaskDidWriteData = downloadTaskDidWriteData { - downloadTaskDidWriteData( - session, - downloadTask, - bytesWritten, - totalBytesWritten, - totalBytesExpectedToWrite - ) - } else { - progress.totalUnitCount = totalBytesExpectedToWrite - progress.completedUnitCount = totalBytesWritten - - if let progressHandler = progressHandler { - progressHandler.queue.async { progressHandler.closure(self.progress) } - } - } - } - - func urlSession( - _ session: URLSession, - downloadTask: URLSessionDownloadTask, - didResumeAtOffset fileOffset: Int64, - expectedTotalBytes: Int64) { - if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset { - downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) - } else { - progress.totalUnitCount = expectedTotalBytes - progress.completedUnitCount = fileOffset - } - } -} - -// MARK: - - -class UploadTaskDelegate: DataTaskDelegate { - - // MARK: Properties - - var uploadTask: URLSessionUploadTask { return task as! URLSessionUploadTask } - - var uploadProgress: Progress - var uploadProgressHandler: (closure: Request.ProgressHandler, queue: DispatchQueue)? - - // MARK: Lifecycle - - override init(task: URLSessionTask?) { - uploadProgress = Progress(totalUnitCount: 0) - super.init(task: task) - } - - override func reset() { - super.reset() - uploadProgress = Progress(totalUnitCount: 0) - } - - // MARK: URLSessionTaskDelegate - - var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)? - - func URLSession( - _ session: URLSession, - task: URLSessionTask, - didSendBodyData bytesSent: Int64, - totalBytesSent: Int64, - totalBytesExpectedToSend: Int64) { - if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() } - - if let taskDidSendBodyData = taskDidSendBodyData { - taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) - } else { - uploadProgress.totalUnitCount = totalBytesExpectedToSend - uploadProgress.completedUnitCount = totalBytesSent - - if let uploadProgressHandler = uploadProgressHandler { - uploadProgressHandler.queue.async { uploadProgressHandler.closure(self.uploadProgress) } - } - } - } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Timeline.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Timeline.swift deleted file mode 100644 index 2c27dd29f74b..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Timeline.swift +++ /dev/null @@ -1,135 +0,0 @@ -// -// Timeline.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. -public struct Timeline { - /// The time the request was initialized. - public let requestStartTime: CFAbsoluteTime - - /// The time the first bytes were received from or sent to the server. - public let initialResponseTime: CFAbsoluteTime - - /// The time when the request was completed. - public let requestCompletedTime: CFAbsoluteTime - - /// The time when the response serialization was completed. - public let serializationCompletedTime: CFAbsoluteTime - - /// The time interval in seconds from the time the request started to the initial response from the server. - public let latency: TimeInterval - - /// The time interval in seconds from the time the request started to the time the request completed. - public let requestDuration: TimeInterval - - /// The time interval in seconds from the time the request completed to the time response serialization completed. - public let serializationDuration: TimeInterval - - /// The time interval in seconds from the time the request started to the time response serialization completed. - public let totalDuration: TimeInterval - - /// Creates a new `Timeline` instance with the specified request times. - /// - /// - parameter requestStartTime: The time the request was initialized. Defaults to `0.0`. - /// - parameter initialResponseTime: The time the first bytes were received from or sent to the server. - /// Defaults to `0.0`. - /// - parameter requestCompletedTime: The time when the request was completed. Defaults to `0.0`. - /// - parameter serializationCompletedTime: The time when the response serialization was completed. Defaults - /// to `0.0`. - /// - /// - returns: The new `Timeline` instance. - public init( - requestStartTime: CFAbsoluteTime = 0.0, - initialResponseTime: CFAbsoluteTime = 0.0, - requestCompletedTime: CFAbsoluteTime = 0.0, - serializationCompletedTime: CFAbsoluteTime = 0.0) { - self.requestStartTime = requestStartTime - self.initialResponseTime = initialResponseTime - self.requestCompletedTime = requestCompletedTime - self.serializationCompletedTime = serializationCompletedTime - - self.latency = initialResponseTime - requestStartTime - self.requestDuration = requestCompletedTime - requestStartTime - self.serializationDuration = serializationCompletedTime - requestCompletedTime - self.totalDuration = serializationCompletedTime - requestStartTime - } -} - -// MARK: - CustomStringConvertible - -extension Timeline: CustomStringConvertible { - /// The textual representation used when written to an output stream, which includes the latency, the request - /// duration and the total duration. - public var description: String { - let latency = String(format: "%.3f", self.latency) - let requestDuration = String(format: "%.3f", self.requestDuration) - let serializationDuration = String(format: "%.3f", self.serializationDuration) - let totalDuration = String(format: "%.3f", self.totalDuration) - - // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is - // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. - let timings = [ - "\"Latency\": " + latency + " secs", - "\"Request Duration\": " + requestDuration + " secs", - "\"Serialization Duration\": " + serializationDuration + " secs", - "\"Total Duration\": " + totalDuration + " secs" - ] - - return "Timeline: { " + timings.joined(separator: ", ") + " }" - } -} - -// MARK: - CustomDebugStringConvertible - -extension Timeline: CustomDebugStringConvertible { - /// The textual representation used when written to an output stream, which includes the request start time, the - /// initial response time, the request completed time, the serialization completed time, the latency, the request - /// duration and the total duration. - public var debugDescription: String { - let requestStartTime = String(format: "%.3f", self.requestStartTime) - let initialResponseTime = String(format: "%.3f", self.initialResponseTime) - let requestCompletedTime = String(format: "%.3f", self.requestCompletedTime) - let serializationCompletedTime = String(format: "%.3f", self.serializationCompletedTime) - let latency = String(format: "%.3f", self.latency) - let requestDuration = String(format: "%.3f", self.requestDuration) - let serializationDuration = String(format: "%.3f", self.serializationDuration) - let totalDuration = String(format: "%.3f", self.totalDuration) - - // NOTE: Had to move to string concatenation due to memory leak filed as rdar://26761490. Once memory leak is - // fixed, we should move back to string interpolation by reverting commit 7d4a43b1. - let timings = [ - "\"Request Start Time\": " + requestStartTime, - "\"Initial Response Time\": " + initialResponseTime, - "\"Request Completed Time\": " + requestCompletedTime, - "\"Serialization Completed Time\": " + serializationCompletedTime, - "\"Latency\": " + latency + " secs", - "\"Request Duration\": " + requestDuration + " secs", - "\"Serialization Duration\": " + serializationDuration + " secs", - "\"Total Duration\": " + totalDuration + " secs" - ] - - return "Timeline: { " + timings.joined(separator: ", ") + " }" - } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Validation.swift b/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Validation.swift deleted file mode 100644 index 3c37e24d847f..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Alamofire/Source/Validation.swift +++ /dev/null @@ -1,319 +0,0 @@ -// -// Validation.swift -// -// Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -// - -import Foundation - -extension Request { - - // MARK: Helper Types - - fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason - - /// Used to represent whether validation was successful or encountered an error resulting in a failure. - /// - /// - success: The validation was successful. - /// - failure: The validation failed encountering the provided error. - public enum ValidationResult { - case success - case failure(Error) - } - - fileprivate struct MIMEType { - let type: String - let subtype: String - - var isWildcard: Bool { return type == "*" && subtype == "*" } - - init?(_ string: String) { - let components: [String] = { - let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines) - - #if swift(>=3.2) - let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)] - #else - let split = stripped.substring(to: stripped.range(of: ";")?.lowerBound ?? stripped.endIndex) - #endif - - return split.components(separatedBy: "/") - }() - - if let type = components.first, let subtype = components.last { - self.type = type - self.subtype = subtype - } else { - return nil - } - } - - func matches(_ mime: MIMEType) -> Bool { - switch (type, subtype) { - case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"): - return true - default: - return false - } - } - } - - // MARK: Properties - - fileprivate var acceptableStatusCodes: [Int] { return Array(200..<300) } - - fileprivate var acceptableContentTypes: [String] { - if let accept = request?.value(forHTTPHeaderField: "Accept") { - return accept.components(separatedBy: ",") - } - - return ["*/*"] - } - - // MARK: Status Code - - fileprivate func validate( - statusCode acceptableStatusCodes: S, - response: HTTPURLResponse) - -> ValidationResult - where S.Iterator.Element == Int { - if acceptableStatusCodes.contains(response.statusCode) { - return .success - } else { - let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode) - return .failure(AFError.responseValidationFailed(reason: reason)) - } - } - - // MARK: Content Type - - fileprivate func validate( - contentType acceptableContentTypes: S, - response: HTTPURLResponse, - data: Data?) - -> ValidationResult - where S.Iterator.Element == String { - guard let data = data, data.count > 0 else { return .success } - - guard - let responseContentType = response.mimeType, - let responseMIMEType = MIMEType(responseContentType) - else { - for contentType in acceptableContentTypes { - if let mimeType = MIMEType(contentType), mimeType.isWildcard { - return .success - } - } - - let error: AFError = { - let reason: ErrorReason = .missingContentType(acceptableContentTypes: Array(acceptableContentTypes)) - return AFError.responseValidationFailed(reason: reason) - }() - - return .failure(error) - } - - for contentType in acceptableContentTypes { - if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) { - return .success - } - } - - let error: AFError = { - let reason: ErrorReason = .unacceptableContentType( - acceptableContentTypes: Array(acceptableContentTypes), - responseContentType: responseContentType - ) - - return AFError.responseValidationFailed(reason: reason) - }() - - return .failure(error) - } -} - -// MARK: - - -extension DataRequest { - /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the - /// request was valid. - public typealias Validation = (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult - - /// Validates the request, using the specified closure. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter validation: A closure to validate the request. - /// - /// - returns: The request. - @discardableResult - public func validate(_ validation: @escaping Validation) -> Self { - let validationExecution: () -> Void = { [unowned self] in - if - let response = self.response, - self.delegate.error == nil, - case let .failure(error) = validation(self.request, response, self.delegate.data) - { - self.delegate.error = error - } - } - - validations.append(validationExecution) - - return self - } - - /// Validates that the response has a status code in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter range: The range of acceptable status codes. - /// - /// - returns: The request. - @discardableResult - public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { - return validate { [unowned self] _, response, _ in - return self.validate(statusCode: acceptableStatusCodes, response: response) - } - } - - /// Validates that the response has a content type in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - /// - /// - returns: The request. - @discardableResult - public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { - return validate { [unowned self] _, response, data in - return self.validate(contentType: acceptableContentTypes, response: response, data: data) - } - } - - /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content - /// type matches any specified in the Accept HTTP header field. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - returns: The request. - @discardableResult - public func validate() -> Self { - let contentTypes = { [unowned self] in - self.acceptableContentTypes - } - return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) - } -} - -// MARK: - - -extension DownloadRequest { - /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a - /// destination URL, and returns whether the request was valid. - public typealias Validation = ( - _ request: URLRequest?, - _ response: HTTPURLResponse, - _ temporaryURL: URL?, - _ destinationURL: URL?) - -> ValidationResult - - /// Validates the request, using the specified closure. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter validation: A closure to validate the request. - /// - /// - returns: The request. - @discardableResult - public func validate(_ validation: @escaping Validation) -> Self { - let validationExecution: () -> Void = { [unowned self] in - let request = self.request - let temporaryURL = self.downloadDelegate.temporaryURL - let destinationURL = self.downloadDelegate.destinationURL - - if - let response = self.response, - self.delegate.error == nil, - case let .failure(error) = validation(request, response, temporaryURL, destinationURL) - { - self.delegate.error = error - } - } - - validations.append(validationExecution) - - return self - } - - /// Validates that the response has a status code in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter range: The range of acceptable status codes. - /// - /// - returns: The request. - @discardableResult - public func validate(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int { - return validate { [unowned self] _, response, _, _ in - return self.validate(statusCode: acceptableStatusCodes, response: response) - } - } - - /// Validates that the response has a content type in the specified sequence. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes. - /// - /// - returns: The request. - @discardableResult - public func validate(contentType acceptableContentTypes: S) -> Self where S.Iterator.Element == String { - return validate { [unowned self] _, response, _, _ in - let fileURL = self.downloadDelegate.fileURL - - guard let validFileURL = fileURL else { - return .failure(AFError.responseValidationFailed(reason: .dataFileNil)) - } - - do { - let data = try Data(contentsOf: validFileURL) - return self.validate(contentType: acceptableContentTypes, response: response, data: data) - } catch { - return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: validFileURL))) - } - } - } - - /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content - /// type matches any specified in the Accept HTTP header field. - /// - /// If validation fails, subsequent calls to response handlers will have an associated error. - /// - /// - returns: The request. - @discardableResult - public func validate() -> Self { - let contentTypes = { [unowned self] in - self.acceptableContentTypes - } - return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes()) - } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Local Podspecs/TestClient.podspec.json b/samples/client/test/swift4/default/TestClientApp/Pods/Local Podspecs/TestClient.podspec.json deleted file mode 100644 index 80f8fe312c0f..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Local Podspecs/TestClient.podspec.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "TestClient", - "platforms": { - "ios": "9.0", - "osx": "10.11", - "tvos": "9.0" - }, - "version": "1.0", - "source": { - "git": "git@github.com:OpenAPITools/openapi-generator.git", - "tag": "v1.0" - }, - "authors": "", - "license": "Proprietary", - "homepage": "https://github.com/openapitools/openapi-generator", - "summary": "TestClient", - "source_files": "TestClient/Classes/**/*.swift", - "dependencies": { - "Alamofire": [ - "~> 4.9.0" - ] - } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Manifest.lock b/samples/client/test/swift4/default/TestClientApp/Pods/Manifest.lock deleted file mode 100644 index 52635b1df2f5..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Manifest.lock +++ /dev/null @@ -1,23 +0,0 @@ -PODS: - - Alamofire (4.9.0) - - TestClient (1.0): - - Alamofire (~> 4.9.0) - -DEPENDENCIES: - - TestClient (from `../`) - -SPEC REPOS: - trunk: - - Alamofire - -EXTERNAL SOURCES: - TestClient: - :path: "../" - -SPEC CHECKSUMS: - Alamofire: afc3e7c6db61476cb45cdd23fed06bad03bbc321 - TestClient: 4923530f672e09a8d020c93372c5ecc195a00ff2 - -PODFILE CHECKSUM: 837b06bfc9f93ccd7664fd918d113c8e3824bde3 - -COCOAPODS: 1.8.4 diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/test/swift4/default/TestClientApp/Pods/Pods.xcodeproj/project.pbxproj deleted file mode 100644 index 30f8f8c924a7..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Pods.xcodeproj/project.pbxproj +++ /dev/null @@ -1,1203 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 48; - objects = { - -/* Begin PBXBuildFile section */ - 0C5E11DE24DAA737704B355F5F2F3426 /* ParameterEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D01BA8472F25D39F718F71557EDC8DD /* ParameterEncoding.swift */; }; - 12485BB17F1B593089682A7D25D36444 /* ModelDoubleArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17D094D080BDBEC408B793F0F216EFCF /* ModelDoubleArray.swift */; }; - 132E0F619E4338E5D1B27E4C72076B3F /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = B06639F7A76DB8A9D0D0E41CDD7A6684 /* Notifications.swift */; }; - 1945CD5D63A1C164AEAAA9A33E85571E /* Alamofire-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 341BDAD0026CDA8E7BCE35AC122E1C8C /* Alamofire-dummy.m */; }; - 1986B50C74F1697EA43F68335C93CEB3 /* MultipartFormData.swift in Sources */ = {isa = PBXBuildFile; fileRef = BFCE3D7EDCA41F256D471B40BBFD3FCE /* MultipartFormData.swift */; }; - 1BA59BA3C7FE2F4014CAA166078A3563 /* ModelWithIntAdditionalPropertiesOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 299F072E4AFA8FB1C36AE60DA78EF042 /* ModelWithIntAdditionalPropertiesOnly.swift */; }; - 23199033AA456927228CC332765604E9 /* BaseCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FE55FA90038DEE66A5EDEBF07F82F23 /* BaseCard.swift */; }; - 26A4930730AD363E43B6A6136D64CCF4 /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 870A2AA13DC481F63D4C0ABD3E167DEB /* Extensions.swift */; }; - 2AF2D3DD4E057C707BF76B1A96289715 /* SampleSubClassAllOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = A52A7F01C4B528FAFA16A97F20E4EFA3 /* SampleSubClassAllOf.swift */; }; - 2C226F0B3865E9C3023B3AB26F1476A6 /* GetAllModelsResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBE53F08153F6B7876485D66586809B0 /* GetAllModelsResult.swift */; }; - 2C61B040BA6A9A7AE66C4D9BA26D5520 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = F640F61D5BEE8132009BAEAA65B587A4 /* SessionDelegate.swift */; }; - 2C96155A8C6B388AFA7F5ADD07A19BFB /* PlaceCardAllOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = 807F8843E823DBAD26F437F3722249E9 /* PlaceCardAllOf.swift */; }; - 2F3BFEC80B05AD380146C3C7A1BEBEF3 /* Pods-TestClientApp-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = DE94C910653499F2AB069ACEE0FDC2DD /* Pods-TestClientApp-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 3571F958A3907B3A806E62D50C2550D4 /* NetworkReachabilityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5460AD0F6241621B45A17AB23A8E5B7 /* NetworkReachabilityManager.swift */; }; - 359A4FEBE1E669DEBDB42BEF26D79E2D /* ModelStringArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = B045D50AF74E268DC06AAF9756759AFF /* ModelStringArray.swift */; }; - 36CB2BFCBA80A87C16A51C4A47802510 /* SampleBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9A4FDCCF4C2D1BD1844E7908D64C8C8A /* SampleBase.swift */; }; - 40411299E20A708A576C1036DAA1C8E8 /* Swift4TestAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = D528EC824000A950933C99A2035DB64C /* Swift4TestAPI.swift */; }; - 4435680E8AEC40C0D41102941C65F54E /* Pods-TestClientAppTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 18C6EC373298C48FCAFA0DDA13E26347 /* Pods-TestClientAppTests-dummy.m */; }; - 4EB1C58438B49F7980C530253973BDE8 /* JSONEncodingHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE08CCAD86A95EB42209718C5CD86FA7 /* JSONEncodingHelper.swift */; }; - 53791F5E5F07400F92CFDFC89A432305 /* Validation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33115EC2A5164913C68F8BD170389EEE /* Validation.swift */; }; - 547A0FE0170B79FC9599FF084F490E7E /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62DA595C49D99EE9F8DEE860042947D2 /* APIs.swift */; }; - 59C7680A0456D58849B9B3AB85DEE251 /* ModelErrorInfoArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 49CF9A8F3C21F3B5BCC104B5FBADBF3C /* ModelErrorInfoArray.swift */; }; - 5A594D84E8050062AD1BD694858D5718 /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F64B53811FD573F2445A18D95497479 /* APIHelper.swift */; }; - 60DC6AA4E42E79B6BB0CC7C68D5FD00F /* ModelWithStringAdditionalPropertiesOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = 60CBE81959613010337321C9321DD994 /* ModelWithStringAdditionalPropertiesOnly.swift */; }; - 6277449D5C1FA4A4E093CCC4C44111C2 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */; }; - 62BA30B7C24824EB5B7CA078172826DC /* Alamofire.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4B03B07DFA7C8BB60693AE1DE30731E2 /* Alamofire.framework */; }; - 64744C911253C3E01461FAD7C935C8D7 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD807F155301ECA538A2C1C296E1186D /* Result.swift */; }; - 68CE9775FFC70C3C9BD07784265DAC03 /* ErrorInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = AC53220A7AD949C4B064008EB8FC1039 /* ErrorInfo.swift */; }; - 7664FD4F59A0C00866CBAE60B0A3AD64 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */; }; - 7D9B1F57B8F8D0AF0463A828BD1A6AA3 /* ModelWithPropertiesAndAdditionalProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = D49DF9408453E6FBD84822A56E113C54 /* ModelWithPropertiesAndAdditionalProperties.swift */; }; - 83956E20859CDBBE7BC38ABADE0170FB /* AFError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D5A0E300C04A6DF88D620788FE38780 /* AFError.swift */; }; - 86D2ECC005235F2AD4E5296367091AA2 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */; }; - 8AD62C8872F6FA42190BFA06AC70CAC6 /* PersonCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 977CD642D5F0719588E44AA35CAE19BD /* PersonCard.swift */; }; - 920CF4F6EAB785A9B589425A37F29941 /* JSONEncodableEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56033BD62B18845FF5154ECDA1D862BE /* JSONEncodableEncoding.swift */; }; - 931BBB8230A25161D5C37528A8F9FECF /* SessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3D7E25E371731FAE44F46A9F392CB5D5 /* SessionManager.swift */; }; - 933FDA5970AA525D6CB92BFEBA2BAB4A /* Timeline.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32DB5272AD01ECD0B09A86818A7754C4 /* Timeline.swift */; }; - 979535C1A9DF8D29E0DBE1711F238D92 /* AllPrimitives.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B69A6B8F518932026AE93FAA46AAF21 /* AllPrimitives.swift */; }; - 98A929C8E9012AB167672714FFD2113C /* Request.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D59E1AD3CC394A93392FF3DC8CF2961 /* Request.swift */; }; - A6FDAB4AF6D731309E6CAF56806FC9CC /* TestClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 80801F1124463057961D00ADCF819795 /* TestClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - AFC64B1097F7355FF423D6A73E9C7210 /* TaskDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75C759635F88377BD7E2DEDE04C23C62 /* TaskDelegate.swift */; }; - BEE6B677416CA71C981D1D3F60B18C96 /* Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1C15C076B531E2E7744C358418A0C0B5 /* Alamofire.swift */; }; - CA05270750D546623EE439985A2A03BA /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE2446064FED210EA015BCC571B2FA28 /* Configuration.swift */; }; - CE1B56EF711E5F1D3A28A0FF8F653894 /* SampleSubClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9ADAEF140A5EC22E51521C038915793E /* SampleSubClass.swift */; }; - D106A26A1C7F7D74BC6999463635F6A6 /* VariableNameTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62C07E26D5913B6DA2011EA426BB4F56 /* VariableNameTest.swift */; }; - D12FA3CCFAE73E216CB32477B62341C3 /* Pods-TestClientApp-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = ECC55036EDA2E6A74F2ABC59EEEF0D23 /* Pods-TestClientApp-dummy.m */; }; - D3750B7200C7CD62E8234B012BB95B8A /* PersonCardAllOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = 137B0A5819AB93366ABA443363269CD2 /* PersonCardAllOf.swift */; }; - D3D8C379C6E4FB487E5ABD6800AD7B7E /* DispatchQueue+Alamofire.swift in Sources */ = {isa = PBXBuildFile; fileRef = AFF7F7716086D54E6308EE52C8227B87 /* DispatchQueue+Alamofire.swift */; }; - D65C254F5ABF2CB5ECEE50FE8F8E1A80 /* Response.swift in Sources */ = {isa = PBXBuildFile; fileRef = CCC6858C85690F7AFEA7F6542EE9A69A /* Response.swift */; }; - E3747EC31FCCA97D75A81FC700CF7E24 /* ResponseSerialization.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B03859BDC36782899379E222720A297 /* ResponseSerialization.swift */; }; - E708DB732C1BC60401EC1F4CFC4718FA /* Pods-TestClientAppTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = E3BC082537CA1630DA1E1DCFDB9BC495 /* Pods-TestClientAppTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - E783597BB960AF9120D584702E5AC563 /* AlamofireImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80E250521A44F61D3318F7C013D848C2 /* AlamofireImplementations.swift */; }; - F13F2AA7F2E6D95A181CAB99B900D531 /* ServerTrustPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4453BE339B79900FDC53E34FE5589CB /* ServerTrustPolicy.swift */; }; - F1BF1C79940B91D8B67D1CAFA7506B0D /* PlaceCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = C10EE97A6312473F6C13575444BA30BD /* PlaceCard.swift */; }; - F6803BA0CA9D3C85F1790ABEF5336887 /* StringEnum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8891F56576815B3139090EC4D95D8338 /* StringEnum.swift */; }; - F7B74645E07C39771156A1FA413B98D4 /* Alamofire-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = D54AEF5647A987180EDAD7E1CEF7387B /* Alamofire-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - F85DC3EE76D5D82F58025ABE937C20A7 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD9A340D3A5FC46E7B4490A12FFD9411 /* Models.swift */; }; - F8721FAD144309DC1BBB53EA4B5D1623 /* TestClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = B2F71CFDBE63BBFE09407C6FC1C6BCDD /* TestClient-dummy.m */; }; - FB1B41E362DD221C7C148BD4543B6C1A /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */; }; - FFAD4C38BE70DF38A8FFB2BFC834316C /* CodableHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EDEDFC5554B8ECE611026F9BC151B1A /* CodableHelper.swift */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 30A30DF1F50AAD505D03DFC304446E2D /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; - remoteInfo = Alamofire; - }; - B94D06C70F0DCC751FF0252CE08EA603 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = B72EF653ED86BEBAF8987EA7602289AA; - remoteInfo = TestClient; - }; - CD0CE61925295850DA1287648FA25A5E /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = EAAA1AD3A8A1B59AB91319EE40752C6D; - remoteInfo = Alamofire; - }; - D46C3A7D874BD540F75F8C8EE656DAA2 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 9B2D563D3B39C8B41B45CEC35AFF91AB; - remoteInfo = "Pods-TestClientApp"; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXFileReference section */ - 03158506844BE7CC7E89C1B0570590EE /* Pods-TestClientApp-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestClientApp-Info.plist"; sourceTree = ""; }; - 064E5A2DE1D813C1B2FB080DFC4CC4C7 /* StringEnum.md */ = {isa = PBXFileReference; includeInIndex = 1; name = StringEnum.md; path = docs/StringEnum.md; sourceTree = ""; }; - 090858F08C40F0EBB7996B31518500DE /* PlaceCardAllOf.md */ = {isa = PBXFileReference; includeInIndex = 1; name = PlaceCardAllOf.md; path = docs/PlaceCardAllOf.md; sourceTree = ""; }; - 0D01BA8472F25D39F718F71557EDC8DD /* ParameterEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ParameterEncoding.swift; path = Source/ParameterEncoding.swift; sourceTree = ""; }; - 137B0A5819AB93366ABA443363269CD2 /* PersonCardAllOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PersonCardAllOf.swift; sourceTree = ""; }; - 17D094D080BDBEC408B793F0F216EFCF /* ModelDoubleArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelDoubleArray.swift; sourceTree = ""; }; - 18C6EC373298C48FCAFA0DDA13E26347 /* Pods-TestClientAppTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-TestClientAppTests-dummy.m"; sourceTree = ""; }; - 1B69A6B8F518932026AE93FAA46AAF21 /* AllPrimitives.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AllPrimitives.swift; sourceTree = ""; }; - 1C15C076B531E2E7744C358418A0C0B5 /* Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Alamofire.swift; path = Source/Alamofire.swift; sourceTree = ""; }; - 251D951D3D9825BAF3D91C44369A2C6D /* BaseCard.md */ = {isa = PBXFileReference; includeInIndex = 1; name = BaseCard.md; path = docs/BaseCard.md; sourceTree = ""; }; - 299F072E4AFA8FB1C36AE60DA78EF042 /* ModelWithIntAdditionalPropertiesOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelWithIntAdditionalPropertiesOnly.swift; sourceTree = ""; }; - 2EDEDFC5554B8ECE611026F9BC151B1A /* CodableHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CodableHelper.swift; path = TestClient/Classes/OpenAPIs/CodableHelper.swift; sourceTree = ""; }; - 30F24E13BF7C1EE2AC4960B45522E513 /* TestClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = TestClient.modulemap; sourceTree = ""; }; - 32DB5272AD01ECD0B09A86818A7754C4 /* Timeline.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeline.swift; path = Source/Timeline.swift; sourceTree = ""; }; - 33115EC2A5164913C68F8BD170389EEE /* Validation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Validation.swift; path = Source/Validation.swift; sourceTree = ""; }; - 341BDAD0026CDA8E7BCE35AC122E1C8C /* Alamofire-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Alamofire-dummy.m"; sourceTree = ""; }; - 3D7E25E371731FAE44F46A9F392CB5D5 /* SessionManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionManager.swift; path = Source/SessionManager.swift; sourceTree = ""; }; - 3FE55FA90038DEE66A5EDEBF07F82F23 /* BaseCard.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = BaseCard.swift; sourceTree = ""; }; - 48C4EB9FB0827F886ABA8B7EBE8EEA8E /* Pods-TestClientAppTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestClientAppTests.release.xcconfig"; sourceTree = ""; }; - 49CF9A8F3C21F3B5BCC104B5FBADBF3C /* ModelErrorInfoArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelErrorInfoArray.swift; sourceTree = ""; }; - 4B03B07DFA7C8BB60693AE1DE30731E2 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 54B147F15F98ADAC3818B86BFC5E69A1 /* PersonCard.md */ = {isa = PBXFileReference; includeInIndex = 1; name = PersonCard.md; path = docs/PersonCard.md; sourceTree = ""; }; - 56033BD62B18845FF5154ECDA1D862BE /* JSONEncodableEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodableEncoding.swift; path = TestClient/Classes/OpenAPIs/JSONEncodableEncoding.swift; sourceTree = ""; }; - 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Alamofire.framework; path = Alamofire.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 5DC57D75B5D78687B4DC11CDCF20AD10 /* Pods_TestClientAppTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_TestClientAppTests.framework; path = "Pods-TestClientAppTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 5F64B53811FD573F2445A18D95497479 /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIHelper.swift; path = TestClient/Classes/OpenAPIs/APIHelper.swift; sourceTree = ""; }; - 60CBE81959613010337321C9321DD994 /* ModelWithStringAdditionalPropertiesOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelWithStringAdditionalPropertiesOnly.swift; sourceTree = ""; }; - 62C07E26D5913B6DA2011EA426BB4F56 /* VariableNameTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = VariableNameTest.swift; sourceTree = ""; }; - 62DA595C49D99EE9F8DEE860042947D2 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIs.swift; path = TestClient/Classes/OpenAPIs/APIs.swift; sourceTree = ""; }; - 67C27532BE4A284FD37538129F082B40 /* Swift4TestAPI.md */ = {isa = PBXFileReference; includeInIndex = 1; name = Swift4TestAPI.md; path = docs/Swift4TestAPI.md; sourceTree = ""; }; - 67E805AB339F5A4435CFA410C5A75FF3 /* ErrorInfo.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ErrorInfo.md; path = docs/ErrorInfo.md; sourceTree = ""; }; - 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; - 6C0A5E2C8C285A84F0535811E0B1B7FA /* VariableNameTest.md */ = {isa = PBXFileReference; includeInIndex = 1; name = VariableNameTest.md; path = docs/VariableNameTest.md; sourceTree = ""; }; - 70F56C80D730D3B8BFEAFA8D78BA4A38 /* SampleSubClassAllOf.md */ = {isa = PBXFileReference; includeInIndex = 1; name = SampleSubClassAllOf.md; path = docs/SampleSubClassAllOf.md; sourceTree = ""; }; - 71E43A261C89DDC20D905C57FFEC3202 /* TestClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = TestClient.xcconfig; sourceTree = ""; }; - 75C759635F88377BD7E2DEDE04C23C62 /* TaskDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TaskDelegate.swift; path = Source/TaskDelegate.swift; sourceTree = ""; }; - 7B03859BDC36782899379E222720A297 /* ResponseSerialization.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ResponseSerialization.swift; path = Source/ResponseSerialization.swift; sourceTree = ""; }; - 7E7CB11C6E8EF71424C6D3725EE67DE8 /* Pods-TestClientAppTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestClientAppTests.debug.xcconfig"; sourceTree = ""; }; - 7FFDF46D7409B56C30D6FA0A2E40215E /* Pods-TestClientAppTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestClientAppTests-Info.plist"; sourceTree = ""; }; - 807F8843E823DBAD26F437F3722249E9 /* PlaceCardAllOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PlaceCardAllOf.swift; sourceTree = ""; }; - 80801F1124463057961D00ADCF819795 /* TestClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "TestClient-umbrella.h"; sourceTree = ""; }; - 80E250521A44F61D3318F7C013D848C2 /* AlamofireImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AlamofireImplementations.swift; path = TestClient/Classes/OpenAPIs/AlamofireImplementations.swift; sourceTree = ""; }; - 820E4E7862CE82209B45326DAC71F308 /* ModelWithPropertiesAndAdditionalProperties.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelWithPropertiesAndAdditionalProperties.md; path = docs/ModelWithPropertiesAndAdditionalProperties.md; sourceTree = ""; }; - 82FD0B66B6128354B30FB2FF3088F3A4 /* Pods-TestClientApp.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestClientApp.debug.xcconfig"; sourceTree = ""; }; - 870A2AA13DC481F63D4C0ABD3E167DEB /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Extensions.swift; path = TestClient/Classes/OpenAPIs/Extensions.swift; sourceTree = ""; }; - 8891F56576815B3139090EC4D95D8338 /* StringEnum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StringEnum.swift; sourceTree = ""; }; - 8CCF5680F207FEEDAFE39D854FA65C54 /* SampleSubClass.md */ = {isa = PBXFileReference; includeInIndex = 1; name = SampleSubClass.md; path = docs/SampleSubClass.md; sourceTree = ""; }; - 8D31EB0CEF9BECFAED11CF838ECBCD09 /* PersonCardAllOf.md */ = {isa = PBXFileReference; includeInIndex = 1; name = PersonCardAllOf.md; path = docs/PersonCardAllOf.md; sourceTree = ""; }; - 8D5A0E300C04A6DF88D620788FE38780 /* AFError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AFError.swift; path = Source/AFError.swift; sourceTree = ""; }; - 90EDF49BF34FA25846EA72CA3767DCAB /* ModelWithIntAdditionalPropertiesOnly.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelWithIntAdditionalPropertiesOnly.md; path = docs/ModelWithIntAdditionalPropertiesOnly.md; sourceTree = ""; }; - 9166C0537D2798D1EE20F58CDEDA48C2 /* Pods-TestClientAppTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-TestClientAppTests.modulemap"; sourceTree = ""; }; - 977CD642D5F0719588E44AA35CAE19BD /* PersonCard.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PersonCard.swift; sourceTree = ""; }; - 985417470B9341C92A5160D4B2FF2B08 /* Alamofire.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Alamofire.xcconfig; sourceTree = ""; }; - 9A4FDCCF4C2D1BD1844E7908D64C8C8A /* SampleBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SampleBase.swift; sourceTree = ""; }; - 9ADAEF140A5EC22E51521C038915793E /* SampleSubClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SampleSubClass.swift; sourceTree = ""; }; - 9CB84DD2456DAE669F6C380A70F0D5F5 /* ModelWithStringAdditionalPropertiesOnly.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelWithStringAdditionalPropertiesOnly.md; path = docs/ModelWithStringAdditionalPropertiesOnly.md; sourceTree = ""; }; - 9D59E1AD3CC394A93392FF3DC8CF2961 /* Request.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Request.swift; path = Source/Request.swift; sourceTree = ""; }; - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - A25FAAF27E0D5D3F9BBA5CC0B11E525E /* ModelStringArray.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelStringArray.md; path = docs/ModelStringArray.md; sourceTree = ""; }; - A2C44571511EE10C5013D963197B890D /* Pods-TestClientApp-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-TestClientApp-acknowledgements.markdown"; sourceTree = ""; }; - A4C2E7C4FC74158B642EF7353C920280 /* Pods-TestClientAppTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestClientAppTests-acknowledgements.plist"; sourceTree = ""; }; - A52A7F01C4B528FAFA16A97F20E4EFA3 /* SampleSubClassAllOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SampleSubClassAllOf.swift; sourceTree = ""; }; - AC53220A7AD949C4B064008EB8FC1039 /* ErrorInfo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ErrorInfo.swift; sourceTree = ""; }; - ACE09A7B35C4BD2100B7556591CDD452 /* GetAllModelsResult.md */ = {isa = PBXFileReference; includeInIndex = 1; name = GetAllModelsResult.md; path = docs/GetAllModelsResult.md; sourceTree = ""; }; - AD8710F26B62AABFF387E9CA4F6899A4 /* Alamofire.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Alamofire.modulemap; sourceTree = ""; }; - AFBE3D468DBC68112B42C229014117EF /* Pods-TestClientApp-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestClientApp-acknowledgements.plist"; sourceTree = ""; }; - AFF7F7716086D54E6308EE52C8227B87 /* DispatchQueue+Alamofire.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Alamofire.swift"; path = "Source/DispatchQueue+Alamofire.swift"; sourceTree = ""; }; - B045D50AF74E268DC06AAF9756759AFF /* ModelStringArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelStringArray.swift; sourceTree = ""; }; - B06639F7A76DB8A9D0D0E41CDD7A6684 /* Notifications.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Notifications.swift; path = Source/Notifications.swift; sourceTree = ""; }; - B15FFDCE43CCDD20175AF4575E291ED6 /* SampleBase.md */ = {isa = PBXFileReference; includeInIndex = 1; name = SampleBase.md; path = docs/SampleBase.md; sourceTree = ""; }; - B1D5F61FD93DB03C60173A799F6B967D /* Pods-TestClientApp.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestClientApp.release.xcconfig"; sourceTree = ""; }; - B2F71CFDBE63BBFE09407C6FC1C6BCDD /* TestClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "TestClient-dummy.m"; sourceTree = ""; }; - B464EEB28AE56DEC88BA2908B67FEA2B /* TestClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = TestClient.framework; path = TestClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - B63BBEF68EDA25B03A0F32C48EB924DE /* Pods-TestClientApp.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-TestClientApp.modulemap"; sourceTree = ""; }; - B6CF2FC9353E5E59AE9C271DEBA6E291 /* TestClient.podspec */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; path = TestClient.podspec; sourceTree = ""; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - BD9A340D3A5FC46E7B4490A12FFD9411 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Models.swift; path = TestClient/Classes/OpenAPIs/Models.swift; sourceTree = ""; }; - BFCE3D7EDCA41F256D471B40BBFD3FCE /* MultipartFormData.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MultipartFormData.swift; path = Source/MultipartFormData.swift; sourceTree = ""; }; - C10EE97A6312473F6C13575444BA30BD /* PlaceCard.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PlaceCard.swift; sourceTree = ""; }; - C2475B69B16D8E2208218F7AAAA39C7E /* Pods-TestClientAppTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-TestClientAppTests-acknowledgements.markdown"; sourceTree = ""; }; - C2DC35BBDEE95DC406F9CE456B32B924 /* PlaceCard.md */ = {isa = PBXFileReference; includeInIndex = 1; name = PlaceCard.md; path = docs/PlaceCard.md; sourceTree = ""; }; - C4453BE339B79900FDC53E34FE5589CB /* ServerTrustPolicy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ServerTrustPolicy.swift; path = Source/ServerTrustPolicy.swift; sourceTree = ""; }; - C9C3EF964FFA8A9F78851B59A8D4FFBC /* Alamofire-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-prefix.pch"; sourceTree = ""; }; - CCC6858C85690F7AFEA7F6542EE9A69A /* Response.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Response.swift; path = Source/Response.swift; sourceTree = ""; }; - D028F56BC75EBEA144850A99325DF4AC /* TestClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "TestClient-prefix.pch"; sourceTree = ""; }; - D49DF9408453E6FBD84822A56E113C54 /* ModelWithPropertiesAndAdditionalProperties.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelWithPropertiesAndAdditionalProperties.swift; sourceTree = ""; }; - D528EC824000A950933C99A2035DB64C /* Swift4TestAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Swift4TestAPI.swift; sourceTree = ""; }; - D54AEF5647A987180EDAD7E1CEF7387B /* Alamofire-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Alamofire-umbrella.h"; sourceTree = ""; }; - DBE53F08153F6B7876485D66586809B0 /* GetAllModelsResult.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = GetAllModelsResult.swift; sourceTree = ""; }; - DD807F155301ECA538A2C1C296E1186D /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Source/Result.swift; sourceTree = ""; }; - DE08CCAD86A95EB42209718C5CD86FA7 /* JSONEncodingHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodingHelper.swift; path = TestClient/Classes/OpenAPIs/JSONEncodingHelper.swift; sourceTree = ""; }; - DE36AED4DF687B2D37BD230D9D2F69B6 /* Alamofire-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Alamofire-Info.plist"; sourceTree = ""; }; - DE94C910653499F2AB069ACEE0FDC2DD /* Pods-TestClientApp-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-TestClientApp-umbrella.h"; sourceTree = ""; }; - E3BC082537CA1630DA1E1DCFDB9BC495 /* Pods-TestClientAppTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-TestClientAppTests-umbrella.h"; sourceTree = ""; }; - E64E970612B808A04B0C7AA69EE0D00F /* Pods-TestClientApp-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-TestClientApp-frameworks.sh"; sourceTree = ""; }; - EB61785404905353201587085B2A9BFD /* ModelDoubleArray.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelDoubleArray.md; path = docs/ModelDoubleArray.md; sourceTree = ""; }; - ECC55036EDA2E6A74F2ABC59EEEF0D23 /* Pods-TestClientApp-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-TestClientApp-dummy.m"; sourceTree = ""; }; - EEE7348046CC9A0FC1CBD943B0C5AC26 /* TestClient-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "TestClient-Info.plist"; sourceTree = ""; }; - F17FE2EEE7B311741C0597FD36B00EE2 /* ModelErrorInfoArray.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelErrorInfoArray.md; path = docs/ModelErrorInfoArray.md; sourceTree = ""; }; - F1A0A81627A3F69C344EAB9D8D5DBAD8 /* AllPrimitives.md */ = {isa = PBXFileReference; includeInIndex = 1; name = AllPrimitives.md; path = docs/AllPrimitives.md; sourceTree = ""; }; - F5460AD0F6241621B45A17AB23A8E5B7 /* NetworkReachabilityManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NetworkReachabilityManager.swift; path = Source/NetworkReachabilityManager.swift; sourceTree = ""; }; - F640F61D5BEE8132009BAEAA65B587A4 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Source/SessionDelegate.swift; sourceTree = ""; }; - F9FF90ED623D49FB5D83BBFF22D266F2 /* README.md */ = {isa = PBXFileReference; includeInIndex = 1; path = README.md; sourceTree = ""; }; - FE2446064FED210EA015BCC571B2FA28 /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = TestClient/Classes/OpenAPIs/Configuration.swift; sourceTree = ""; }; - FED082EE959E5B5A9579D3EA6B287F66 /* Pods_TestClientApp.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_TestClientApp.framework; path = "Pods-TestClientApp.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 090C1D63463ACF622287EFF9D5C9392D /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 7664FD4F59A0C00866CBAE60B0A3AD64 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 3671827958974BD456D133DFBF46D873 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 62BA30B7C24824EB5B7CA078172826DC /* Alamofire.framework in Frameworks */, - FB1B41E362DD221C7C148BD4543B6C1A /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 392A821448B69621350AA800ED9F71E7 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 86D2ECC005235F2AD4E5296367091AA2 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 54B50DB8B7D7164CE18CA0FC9FCAB915 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 6277449D5C1FA4A4E093CCC4C44111C2 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 01252A1AF71ABEED85368EE93297092D /* Pods-TestClientApp */ = { - isa = PBXGroup; - children = ( - B63BBEF68EDA25B03A0F32C48EB924DE /* Pods-TestClientApp.modulemap */, - A2C44571511EE10C5013D963197B890D /* Pods-TestClientApp-acknowledgements.markdown */, - AFBE3D468DBC68112B42C229014117EF /* Pods-TestClientApp-acknowledgements.plist */, - ECC55036EDA2E6A74F2ABC59EEEF0D23 /* Pods-TestClientApp-dummy.m */, - E64E970612B808A04B0C7AA69EE0D00F /* Pods-TestClientApp-frameworks.sh */, - 03158506844BE7CC7E89C1B0570590EE /* Pods-TestClientApp-Info.plist */, - DE94C910653499F2AB069ACEE0FDC2DD /* Pods-TestClientApp-umbrella.h */, - 82FD0B66B6128354B30FB2FF3088F3A4 /* Pods-TestClientApp.debug.xcconfig */, - B1D5F61FD93DB03C60173A799F6B967D /* Pods-TestClientApp.release.xcconfig */, - ); - name = "Pods-TestClientApp"; - path = "Target Support Files/Pods-TestClientApp"; - sourceTree = ""; - }; - 19AE33914731D882DECABAA84A8CAE65 /* Support Files */ = { - isa = PBXGroup; - children = ( - 30F24E13BF7C1EE2AC4960B45522E513 /* TestClient.modulemap */, - 71E43A261C89DDC20D905C57FFEC3202 /* TestClient.xcconfig */, - B2F71CFDBE63BBFE09407C6FC1C6BCDD /* TestClient-dummy.m */, - EEE7348046CC9A0FC1CBD943B0C5AC26 /* TestClient-Info.plist */, - D028F56BC75EBEA144850A99325DF4AC /* TestClient-prefix.pch */, - 80801F1124463057961D00ADCF819795 /* TestClient-umbrella.h */, - ); - name = "Support Files"; - path = "TestClientApp/Pods/Target Support Files/TestClient"; - sourceTree = ""; - }; - 2B9E5065DD311AE82CAECB5D52F0FC74 /* Pods-TestClientAppTests */ = { - isa = PBXGroup; - children = ( - 9166C0537D2798D1EE20F58CDEDA48C2 /* Pods-TestClientAppTests.modulemap */, - C2475B69B16D8E2208218F7AAAA39C7E /* Pods-TestClientAppTests-acknowledgements.markdown */, - A4C2E7C4FC74158B642EF7353C920280 /* Pods-TestClientAppTests-acknowledgements.plist */, - 18C6EC373298C48FCAFA0DDA13E26347 /* Pods-TestClientAppTests-dummy.m */, - 7FFDF46D7409B56C30D6FA0A2E40215E /* Pods-TestClientAppTests-Info.plist */, - E3BC082537CA1630DA1E1DCFDB9BC495 /* Pods-TestClientAppTests-umbrella.h */, - 7E7CB11C6E8EF71424C6D3725EE67DE8 /* Pods-TestClientAppTests.debug.xcconfig */, - 48C4EB9FB0827F886ABA8B7EBE8EEA8E /* Pods-TestClientAppTests.release.xcconfig */, - ); - name = "Pods-TestClientAppTests"; - path = "Target Support Files/Pods-TestClientAppTests"; - sourceTree = ""; - }; - 2F2A6FCCD7293377A61DF5D10894ACF2 /* Frameworks */ = { - isa = PBXGroup; - children = ( - 4B03B07DFA7C8BB60693AE1DE30731E2 /* Alamofire.framework */, - DBBD239EB7C1C83EA80124D1A53485AB /* iOS */, - ); - name = Frameworks; - sourceTree = ""; - }; - 3C4C30950B0A5E0D571BF164238CE41C /* Targets Support Files */ = { - isa = PBXGroup; - children = ( - 01252A1AF71ABEED85368EE93297092D /* Pods-TestClientApp */, - 2B9E5065DD311AE82CAECB5D52F0FC74 /* Pods-TestClientAppTests */, - ); - name = "Targets Support Files"; - sourceTree = ""; - }; - 3CEA0B2ABE2AD50C8E524BA45C22B1D8 /* APIs */ = { - isa = PBXGroup; - children = ( - D528EC824000A950933C99A2035DB64C /* Swift4TestAPI.swift */, - ); - name = APIs; - path = TestClient/Classes/OpenAPIs/APIs; - sourceTree = ""; - }; - 5C26875CAEBEFEDA19F66418CD7AE5DB /* Support Files */ = { - isa = PBXGroup; - children = ( - AD8710F26B62AABFF387E9CA4F6899A4 /* Alamofire.modulemap */, - 985417470B9341C92A5160D4B2FF2B08 /* Alamofire.xcconfig */, - 341BDAD0026CDA8E7BCE35AC122E1C8C /* Alamofire-dummy.m */, - DE36AED4DF687B2D37BD230D9D2F69B6 /* Alamofire-Info.plist */, - C9C3EF964FFA8A9F78851B59A8D4FFBC /* Alamofire-prefix.pch */, - D54AEF5647A987180EDAD7E1CEF7387B /* Alamofire-umbrella.h */, - ); - name = "Support Files"; - path = "../Target Support Files/Alamofire"; - sourceTree = ""; - }; - 64C312E3B3AD385F6402CACED742A4F6 /* Models */ = { - isa = PBXGroup; - children = ( - 1B69A6B8F518932026AE93FAA46AAF21 /* AllPrimitives.swift */, - 3FE55FA90038DEE66A5EDEBF07F82F23 /* BaseCard.swift */, - AC53220A7AD949C4B064008EB8FC1039 /* ErrorInfo.swift */, - DBE53F08153F6B7876485D66586809B0 /* GetAllModelsResult.swift */, - 17D094D080BDBEC408B793F0F216EFCF /* ModelDoubleArray.swift */, - 49CF9A8F3C21F3B5BCC104B5FBADBF3C /* ModelErrorInfoArray.swift */, - B045D50AF74E268DC06AAF9756759AFF /* ModelStringArray.swift */, - 299F072E4AFA8FB1C36AE60DA78EF042 /* ModelWithIntAdditionalPropertiesOnly.swift */, - D49DF9408453E6FBD84822A56E113C54 /* ModelWithPropertiesAndAdditionalProperties.swift */, - 60CBE81959613010337321C9321DD994 /* ModelWithStringAdditionalPropertiesOnly.swift */, - 977CD642D5F0719588E44AA35CAE19BD /* PersonCard.swift */, - 137B0A5819AB93366ABA443363269CD2 /* PersonCardAllOf.swift */, - C10EE97A6312473F6C13575444BA30BD /* PlaceCard.swift */, - 807F8843E823DBAD26F437F3722249E9 /* PlaceCardAllOf.swift */, - 9A4FDCCF4C2D1BD1844E7908D64C8C8A /* SampleBase.swift */, - 9ADAEF140A5EC22E51521C038915793E /* SampleSubClass.swift */, - A52A7F01C4B528FAFA16A97F20E4EFA3 /* SampleSubClassAllOf.swift */, - 8891F56576815B3139090EC4D95D8338 /* StringEnum.swift */, - 62C07E26D5913B6DA2011EA426BB4F56 /* VariableNameTest.swift */, - ); - name = Models; - path = TestClient/Classes/OpenAPIs/Models; - sourceTree = ""; - }; - 65B38C0DC6B578734A2C764AE972BBF9 /* Development Pods */ = { - isa = PBXGroup; - children = ( - B318DDADFFD1F22485C54FABBFB5CF0D /* TestClient */, - ); - name = "Development Pods"; - sourceTree = ""; - }; - 8B7D05AAC8C2B810D8C4CFF993FA6F6A /* Products */ = { - isa = PBXGroup; - children = ( - 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire.framework */, - FED082EE959E5B5A9579D3EA6B287F66 /* Pods_TestClientApp.framework */, - 5DC57D75B5D78687B4DC11CDCF20AD10 /* Pods_TestClientAppTests.framework */, - B464EEB28AE56DEC88BA2908B67FEA2B /* TestClient.framework */, - ); - name = Products; - sourceTree = ""; - }; - 90FDDC7F5D24472360CA259A8D40AE98 /* Pods */ = { - isa = PBXGroup; - children = ( - ABBD6121E62B33A53CF07892A75F2030 /* Alamofire */, - ); - name = Pods; - sourceTree = ""; - }; - ABBD6121E62B33A53CF07892A75F2030 /* Alamofire */ = { - isa = PBXGroup; - children = ( - 8D5A0E300C04A6DF88D620788FE38780 /* AFError.swift */, - 1C15C076B531E2E7744C358418A0C0B5 /* Alamofire.swift */, - AFF7F7716086D54E6308EE52C8227B87 /* DispatchQueue+Alamofire.swift */, - BFCE3D7EDCA41F256D471B40BBFD3FCE /* MultipartFormData.swift */, - F5460AD0F6241621B45A17AB23A8E5B7 /* NetworkReachabilityManager.swift */, - B06639F7A76DB8A9D0D0E41CDD7A6684 /* Notifications.swift */, - 0D01BA8472F25D39F718F71557EDC8DD /* ParameterEncoding.swift */, - 9D59E1AD3CC394A93392FF3DC8CF2961 /* Request.swift */, - CCC6858C85690F7AFEA7F6542EE9A69A /* Response.swift */, - 7B03859BDC36782899379E222720A297 /* ResponseSerialization.swift */, - DD807F155301ECA538A2C1C296E1186D /* Result.swift */, - C4453BE339B79900FDC53E34FE5589CB /* ServerTrustPolicy.swift */, - F640F61D5BEE8132009BAEAA65B587A4 /* SessionDelegate.swift */, - 3D7E25E371731FAE44F46A9F392CB5D5 /* SessionManager.swift */, - 75C759635F88377BD7E2DEDE04C23C62 /* TaskDelegate.swift */, - 32DB5272AD01ECD0B09A86818A7754C4 /* Timeline.swift */, - 33115EC2A5164913C68F8BD170389EEE /* Validation.swift */, - 5C26875CAEBEFEDA19F66418CD7AE5DB /* Support Files */, - ); - name = Alamofire; - path = Alamofire; - sourceTree = ""; - }; - B318DDADFFD1F22485C54FABBFB5CF0D /* TestClient */ = { - isa = PBXGroup; - children = ( - 80E250521A44F61D3318F7C013D848C2 /* AlamofireImplementations.swift */, - 5F64B53811FD573F2445A18D95497479 /* APIHelper.swift */, - 62DA595C49D99EE9F8DEE860042947D2 /* APIs.swift */, - 2EDEDFC5554B8ECE611026F9BC151B1A /* CodableHelper.swift */, - FE2446064FED210EA015BCC571B2FA28 /* Configuration.swift */, - 870A2AA13DC481F63D4C0ABD3E167DEB /* Extensions.swift */, - 56033BD62B18845FF5154ECDA1D862BE /* JSONEncodableEncoding.swift */, - DE08CCAD86A95EB42209718C5CD86FA7 /* JSONEncodingHelper.swift */, - BD9A340D3A5FC46E7B4490A12FFD9411 /* Models.swift */, - 3CEA0B2ABE2AD50C8E524BA45C22B1D8 /* APIs */, - 64C312E3B3AD385F6402CACED742A4F6 /* Models */, - D855D89B57A9DADD9BC61F5DDBE5240A /* Pod */, - 19AE33914731D882DECABAA84A8CAE65 /* Support Files */, - ); - name = TestClient; - path = ../..; - sourceTree = ""; - }; - CF1408CF629C7361332E53B88F7BD30C = { - isa = PBXGroup; - children = ( - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, - 65B38C0DC6B578734A2C764AE972BBF9 /* Development Pods */, - 2F2A6FCCD7293377A61DF5D10894ACF2 /* Frameworks */, - 90FDDC7F5D24472360CA259A8D40AE98 /* Pods */, - 8B7D05AAC8C2B810D8C4CFF993FA6F6A /* Products */, - 3C4C30950B0A5E0D571BF164238CE41C /* Targets Support Files */, - ); - sourceTree = ""; - }; - D855D89B57A9DADD9BC61F5DDBE5240A /* Pod */ = { - isa = PBXGroup; - children = ( - F1A0A81627A3F69C344EAB9D8D5DBAD8 /* AllPrimitives.md */, - 251D951D3D9825BAF3D91C44369A2C6D /* BaseCard.md */, - 67E805AB339F5A4435CFA410C5A75FF3 /* ErrorInfo.md */, - ACE09A7B35C4BD2100B7556591CDD452 /* GetAllModelsResult.md */, - EB61785404905353201587085B2A9BFD /* ModelDoubleArray.md */, - F17FE2EEE7B311741C0597FD36B00EE2 /* ModelErrorInfoArray.md */, - A25FAAF27E0D5D3F9BBA5CC0B11E525E /* ModelStringArray.md */, - 90EDF49BF34FA25846EA72CA3767DCAB /* ModelWithIntAdditionalPropertiesOnly.md */, - 820E4E7862CE82209B45326DAC71F308 /* ModelWithPropertiesAndAdditionalProperties.md */, - 9CB84DD2456DAE669F6C380A70F0D5F5 /* ModelWithStringAdditionalPropertiesOnly.md */, - 54B147F15F98ADAC3818B86BFC5E69A1 /* PersonCard.md */, - 8D31EB0CEF9BECFAED11CF838ECBCD09 /* PersonCardAllOf.md */, - C2DC35BBDEE95DC406F9CE456B32B924 /* PlaceCard.md */, - 090858F08C40F0EBB7996B31518500DE /* PlaceCardAllOf.md */, - F9FF90ED623D49FB5D83BBFF22D266F2 /* README.md */, - B15FFDCE43CCDD20175AF4575E291ED6 /* SampleBase.md */, - 8CCF5680F207FEEDAFE39D854FA65C54 /* SampleSubClass.md */, - 70F56C80D730D3B8BFEAFA8D78BA4A38 /* SampleSubClassAllOf.md */, - 064E5A2DE1D813C1B2FB080DFC4CC4C7 /* StringEnum.md */, - 67C27532BE4A284FD37538129F082B40 /* Swift4TestAPI.md */, - B6CF2FC9353E5E59AE9C271DEBA6E291 /* TestClient.podspec */, - 6C0A5E2C8C285A84F0535811E0B1B7FA /* VariableNameTest.md */, - ); - name = Pod; - sourceTree = ""; - }; - DBBD239EB7C1C83EA80124D1A53485AB /* iOS */ = { - isa = PBXGroup; - children = ( - 69DAB41DE6AF59D8362CBC670CDF0EEC /* Foundation.framework */, - ); - name = iOS; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXHeadersBuildPhase section */ - 1625DA99DEAB471D03A5C4F33FCBE807 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 2F3BFEC80B05AD380146C3C7A1BEBEF3 /* Pods-TestClientApp-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 2582784E4FA6A1AC5D23FC53AC3F6EE2 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - F7B74645E07C39771156A1FA413B98D4 /* Alamofire-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 84F640D82F145024C1C7E3A9AD013CF0 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - A6FDAB4AF6D731309E6CAF56806FC9CC /* TestClient-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F85310E66C57158DB3FA693AF79EDAC7 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - E708DB732C1BC60401EC1F4CFC4718FA /* Pods-TestClientAppTests-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - -/* Begin PBXNativeTarget section */ - 2D75029181FED2A76CE4D7E9C7324E1A /* Pods-TestClientAppTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = F5DCF5CCC2DD022C81242D669FBA2A53 /* Build configuration list for PBXNativeTarget "Pods-TestClientAppTests" */; - buildPhases = ( - F85310E66C57158DB3FA693AF79EDAC7 /* Headers */, - FEBEDF2CD3F3F14C05232EC28A5EF48C /* Sources */, - 54B50DB8B7D7164CE18CA0FC9FCAB915 /* Frameworks */, - 03481D112E7D051F903DE8784BF22687 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - EC9E65DA36BCE418EF8ACAEA50766BBA /* PBXTargetDependency */, - ); - name = "Pods-TestClientAppTests"; - productName = "Pods-TestClientAppTests"; - productReference = 5DC57D75B5D78687B4DC11CDCF20AD10 /* Pods_TestClientAppTests.framework */; - productType = "com.apple.product-type.framework"; - }; - 9B2D563D3B39C8B41B45CEC35AFF91AB /* Pods-TestClientApp */ = { - isa = PBXNativeTarget; - buildConfigurationList = 3BDEFD821948711ED22101CF8DE0F428 /* Build configuration list for PBXNativeTarget "Pods-TestClientApp" */; - buildPhases = ( - 1625DA99DEAB471D03A5C4F33FCBE807 /* Headers */, - 7D8B54F6A6A81B2A1D69F893805FF2C2 /* Sources */, - 392A821448B69621350AA800ED9F71E7 /* Frameworks */, - 6534C4273EE6D041F2C267ED7441C61A /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - E5196B4FCD09587B304B7CBCC94DF454 /* PBXTargetDependency */, - 432EAB20630656836F893785C6D03D3E /* PBXTargetDependency */, - ); - name = "Pods-TestClientApp"; - productName = "Pods-TestClientApp"; - productReference = FED082EE959E5B5A9579D3EA6B287F66 /* Pods_TestClientApp.framework */; - productType = "com.apple.product-type.framework"; - }; - B72EF653ED86BEBAF8987EA7602289AA /* TestClient */ = { - isa = PBXNativeTarget; - buildConfigurationList = D5FA9A404A9150C3C03B9D50CB242EAD /* Build configuration list for PBXNativeTarget "TestClient" */; - buildPhases = ( - 84F640D82F145024C1C7E3A9AD013CF0 /* Headers */, - 2119061E557666BFA861E27591C1C233 /* Sources */, - 3671827958974BD456D133DFBF46D873 /* Frameworks */, - 9E9162386635DD4BB7BA8112A107FB16 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - FDE34033B146C1F13B4C5DD97CAB9626 /* PBXTargetDependency */, - ); - name = TestClient; - productName = TestClient; - productReference = B464EEB28AE56DEC88BA2908B67FEA2B /* TestClient.framework */; - productType = "com.apple.product-type.framework"; - }; - EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */ = { - isa = PBXNativeTarget; - buildConfigurationList = E4A5194ABAF7A4780609E0E581DA6B54 /* Build configuration list for PBXNativeTarget "Alamofire" */; - buildPhases = ( - 2582784E4FA6A1AC5D23FC53AC3F6EE2 /* Headers */, - 2DDFD9AC10F181CD7130BDF5F9E0502B /* Sources */, - 090C1D63463ACF622287EFF9D5C9392D /* Frameworks */, - 473D3E892ABB6C798CFF290644259B34 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = Alamofire; - productName = Alamofire; - productReference = 5D797E9A5C5782CE845840781FA1CC81 /* Alamofire.framework */; - productType = "com.apple.product-type.framework"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - BFDFE7DC352907FC980B868725387E98 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1100; - LastUpgradeCheck = 1100; - }; - buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; - compatibilityVersion = "Xcode 8.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = CF1408CF629C7361332E53B88F7BD30C; - productRefGroup = 8B7D05AAC8C2B810D8C4CFF993FA6F6A /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */, - 9B2D563D3B39C8B41B45CEC35AFF91AB /* Pods-TestClientApp */, - 2D75029181FED2A76CE4D7E9C7324E1A /* Pods-TestClientAppTests */, - B72EF653ED86BEBAF8987EA7602289AA /* TestClient */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 03481D112E7D051F903DE8784BF22687 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 473D3E892ABB6C798CFF290644259B34 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 6534C4273EE6D041F2C267ED7441C61A /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 9E9162386635DD4BB7BA8112A107FB16 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 2119061E557666BFA861E27591C1C233 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - E783597BB960AF9120D584702E5AC563 /* AlamofireImplementations.swift in Sources */, - 979535C1A9DF8D29E0DBE1711F238D92 /* AllPrimitives.swift in Sources */, - 5A594D84E8050062AD1BD694858D5718 /* APIHelper.swift in Sources */, - 547A0FE0170B79FC9599FF084F490E7E /* APIs.swift in Sources */, - 23199033AA456927228CC332765604E9 /* BaseCard.swift in Sources */, - FFAD4C38BE70DF38A8FFB2BFC834316C /* CodableHelper.swift in Sources */, - CA05270750D546623EE439985A2A03BA /* Configuration.swift in Sources */, - 68CE9775FFC70C3C9BD07784265DAC03 /* ErrorInfo.swift in Sources */, - 26A4930730AD363E43B6A6136D64CCF4 /* Extensions.swift in Sources */, - 2C226F0B3865E9C3023B3AB26F1476A6 /* GetAllModelsResult.swift in Sources */, - 920CF4F6EAB785A9B589425A37F29941 /* JSONEncodableEncoding.swift in Sources */, - 4EB1C58438B49F7980C530253973BDE8 /* JSONEncodingHelper.swift in Sources */, - 12485BB17F1B593089682A7D25D36444 /* ModelDoubleArray.swift in Sources */, - 59C7680A0456D58849B9B3AB85DEE251 /* ModelErrorInfoArray.swift in Sources */, - F85DC3EE76D5D82F58025ABE937C20A7 /* Models.swift in Sources */, - 359A4FEBE1E669DEBDB42BEF26D79E2D /* ModelStringArray.swift in Sources */, - 1BA59BA3C7FE2F4014CAA166078A3563 /* ModelWithIntAdditionalPropertiesOnly.swift in Sources */, - 7D9B1F57B8F8D0AF0463A828BD1A6AA3 /* ModelWithPropertiesAndAdditionalProperties.swift in Sources */, - 60DC6AA4E42E79B6BB0CC7C68D5FD00F /* ModelWithStringAdditionalPropertiesOnly.swift in Sources */, - 8AD62C8872F6FA42190BFA06AC70CAC6 /* PersonCard.swift in Sources */, - D3750B7200C7CD62E8234B012BB95B8A /* PersonCardAllOf.swift in Sources */, - F1BF1C79940B91D8B67D1CAFA7506B0D /* PlaceCard.swift in Sources */, - 2C96155A8C6B388AFA7F5ADD07A19BFB /* PlaceCardAllOf.swift in Sources */, - 36CB2BFCBA80A87C16A51C4A47802510 /* SampleBase.swift in Sources */, - CE1B56EF711E5F1D3A28A0FF8F653894 /* SampleSubClass.swift in Sources */, - 2AF2D3DD4E057C707BF76B1A96289715 /* SampleSubClassAllOf.swift in Sources */, - F6803BA0CA9D3C85F1790ABEF5336887 /* StringEnum.swift in Sources */, - 40411299E20A708A576C1036DAA1C8E8 /* Swift4TestAPI.swift in Sources */, - F8721FAD144309DC1BBB53EA4B5D1623 /* TestClient-dummy.m in Sources */, - D106A26A1C7F7D74BC6999463635F6A6 /* VariableNameTest.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 2DDFD9AC10F181CD7130BDF5F9E0502B /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 83956E20859CDBBE7BC38ABADE0170FB /* AFError.swift in Sources */, - 1945CD5D63A1C164AEAAA9A33E85571E /* Alamofire-dummy.m in Sources */, - BEE6B677416CA71C981D1D3F60B18C96 /* Alamofire.swift in Sources */, - D3D8C379C6E4FB487E5ABD6800AD7B7E /* DispatchQueue+Alamofire.swift in Sources */, - 1986B50C74F1697EA43F68335C93CEB3 /* MultipartFormData.swift in Sources */, - 3571F958A3907B3A806E62D50C2550D4 /* NetworkReachabilityManager.swift in Sources */, - 132E0F619E4338E5D1B27E4C72076B3F /* Notifications.swift in Sources */, - 0C5E11DE24DAA737704B355F5F2F3426 /* ParameterEncoding.swift in Sources */, - 98A929C8E9012AB167672714FFD2113C /* Request.swift in Sources */, - D65C254F5ABF2CB5ECEE50FE8F8E1A80 /* Response.swift in Sources */, - E3747EC31FCCA97D75A81FC700CF7E24 /* ResponseSerialization.swift in Sources */, - 64744C911253C3E01461FAD7C935C8D7 /* Result.swift in Sources */, - F13F2AA7F2E6D95A181CAB99B900D531 /* ServerTrustPolicy.swift in Sources */, - 2C61B040BA6A9A7AE66C4D9BA26D5520 /* SessionDelegate.swift in Sources */, - 931BBB8230A25161D5C37528A8F9FECF /* SessionManager.swift in Sources */, - AFC64B1097F7355FF423D6A73E9C7210 /* TaskDelegate.swift in Sources */, - 933FDA5970AA525D6CB92BFEBA2BAB4A /* Timeline.swift in Sources */, - 53791F5E5F07400F92CFDFC89A432305 /* Validation.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 7D8B54F6A6A81B2A1D69F893805FF2C2 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - D12FA3CCFAE73E216CB32477B62341C3 /* Pods-TestClientApp-dummy.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - FEBEDF2CD3F3F14C05232EC28A5EF48C /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4435680E8AEC40C0D41102941C65F54E /* Pods-TestClientAppTests-dummy.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - 432EAB20630656836F893785C6D03D3E /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = TestClient; - target = B72EF653ED86BEBAF8987EA7602289AA /* TestClient */; - targetProxy = B94D06C70F0DCC751FF0252CE08EA603 /* PBXContainerItemProxy */; - }; - E5196B4FCD09587B304B7CBCC94DF454 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Alamofire; - target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; - targetProxy = CD0CE61925295850DA1287648FA25A5E /* PBXContainerItemProxy */; - }; - EC9E65DA36BCE418EF8ACAEA50766BBA /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "Pods-TestClientApp"; - target = 9B2D563D3B39C8B41B45CEC35AFF91AB /* Pods-TestClientApp */; - targetProxy = D46C3A7D874BD540F75F8C8EE656DAA2 /* PBXContainerItemProxy */; - }; - FDE34033B146C1F13B4C5DD97CAB9626 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = Alamofire; - target = EAAA1AD3A8A1B59AB91319EE40752C6D /* Alamofire */; - targetProxy = 30A30DF1F50AAD505D03DFC304446E2D /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin XCBuildConfiguration section */ - 1DC2D30AF2300C0F22044BC761AB42AD /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = B1D5F61FD93DB03C60173A799F6B967D /* Pods-TestClientApp.release.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-TestClientApp/Pods-TestClientApp-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestClientApp/Pods-TestClientApp.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 2990DB3D5730943A136F50629A685508 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 71E43A261C89DDC20D905C57FFEC3202 /* TestClient.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/TestClient/TestClient-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/TestClient/TestClient-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/TestClient/TestClient.modulemap"; - PRODUCT_MODULE_NAME = TestClient; - PRODUCT_NAME = TestClient; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 4.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 314DD2576941BC5109AABA2E6BD37A27 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7E7CB11C6E8EF71424C6D3725EE67DE8 /* Pods-TestClientAppTests.debug.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 3F71DFC31DECEFF062CEC6C1760DAC4B /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 71E43A261C89DDC20D905C57FFEC3202 /* TestClient.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/TestClient/TestClient-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/TestClient/TestClient-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/TestClient/TestClient.modulemap"; - PRODUCT_MODULE_NAME = TestClient; - PRODUCT_NAME = TestClient; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 4.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 75BBB760DFD877E344322B54D29DFE64 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 985417470B9341C92A5160D4B2FF2B08 /* Alamofire.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - PRODUCT_MODULE_NAME = Alamofire; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.1; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 7A7BF9A37585C7049957F8A8F29F07E7 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 82FD0B66B6128354B30FB2FF3088F3A4 /* Pods-TestClientApp.debug.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-TestClientApp/Pods-TestClientApp-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestClientApp/Pods-TestClientApp.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 8F17DC3A99F99FBAD606CE6963886315 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_RELEASE=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - SWIFT_VERSION = 5.0; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Release; - }; - 916E0404255105F480DC4950B7625F7A /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_DEBUG=1", - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Debug; - }; - C8ED66A74D418771F0B335943A7704DC /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 48C4EB9FB0827F886ABA8B7EBE8EEA8E /* Pods-TestClientAppTests.release.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - F94FD07C591B17B7E61A1528AB9BCB3B /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 985417470B9341C92A5160D4B2FF2B08 /* Alamofire.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/Alamofire/Alamofire-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/Alamofire/Alamofire-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/Alamofire/Alamofire.modulemap"; - PRODUCT_MODULE_NAME = Alamofire; - PRODUCT_NAME = Alamofire; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 5.1; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 3BDEFD821948711ED22101CF8DE0F428 /* Build configuration list for PBXNativeTarget "Pods-TestClientApp" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 7A7BF9A37585C7049957F8A8F29F07E7 /* Debug */, - 1DC2D30AF2300C0F22044BC761AB42AD /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 916E0404255105F480DC4950B7625F7A /* Debug */, - 8F17DC3A99F99FBAD606CE6963886315 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - D5FA9A404A9150C3C03B9D50CB242EAD /* Build configuration list for PBXNativeTarget "TestClient" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 3F71DFC31DECEFF062CEC6C1760DAC4B /* Debug */, - 2990DB3D5730943A136F50629A685508 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - E4A5194ABAF7A4780609E0E581DA6B54 /* Build configuration list for PBXNativeTarget "Alamofire" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 75BBB760DFD877E344322B54D29DFE64 /* Debug */, - F94FD07C591B17B7E61A1528AB9BCB3B /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - F5DCF5CCC2DD022C81242D669FBA2A53 /* Build configuration list for PBXNativeTarget "Pods-TestClientAppTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 314DD2576941BC5109AABA2E6BD37A27 /* Debug */, - C8ED66A74D418771F0B335943A7704DC /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-Info.plist b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-Info.plist deleted file mode 100644 index bb5a9ffc808b..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 4.9.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-dummy.m b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-dummy.m deleted file mode 100644 index a6c4594242e9..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Alamofire : NSObject -@end -@implementation PodsDummy_Alamofire -@end diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch deleted file mode 100644 index beb2a2441835..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h deleted file mode 100644 index 00014e3cd82a..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double AlamofireVersionNumber; -FOUNDATION_EXPORT const unsigned char AlamofireVersionString[]; - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire.modulemap b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire.modulemap deleted file mode 100644 index d1f125fab6b0..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Alamofire { - umbrella header "Alamofire-umbrella.h" - - export * - module * { export * } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire.xcconfig b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire.xcconfig deleted file mode 100644 index 243af4f18249..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Alamofire/Alamofire.xcconfig +++ /dev/null @@ -1,10 +0,0 @@ -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/Alamofire -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_ROOT = ${SRCROOT} -PODS_TARGET_SRCROOT = ${PODS_ROOT}/Alamofire -PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} -SKIP_INSTALL = YES -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-Info.plist b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-Info.plist deleted file mode 100644 index 2243fe6e27dc..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.markdown b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.markdown deleted file mode 100644 index 973d79a75d26..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.markdown +++ /dev/null @@ -1,26 +0,0 @@ -# Acknowledgements -This application makes use of the following third party libraries: - -## Alamofire - -Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.plist b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.plist deleted file mode 100644 index 5c049b5d2a3b..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.plist +++ /dev/null @@ -1,58 +0,0 @@ - - - - - PreferenceSpecifiers - - - FooterText - This application makes use of the following third party libraries: - Title - Acknowledgements - Type - PSGroupSpecifier - - - FooterText - Copyright (c) 2014 Alamofire Software Foundation (http://alamofire.org/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - License - MIT - Title - Alamofire - Type - PSGroupSpecifier - - - FooterText - Generated by CocoaPods - https://cocoapods.org - Title - - Type - PSGroupSpecifier - - - StringsTable - Acknowledgements - Title - Acknowledgements - - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-dummy.m b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-dummy.m deleted file mode 100644 index 7403e9c5dead..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods_TestClientApp : NSObject -@end -@implementation PodsDummy_Pods_TestClientApp -@end diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-frameworks.sh b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-frameworks.sh deleted file mode 100755 index aefc1e47dabe..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-frameworks.sh +++ /dev/null @@ -1,173 +0,0 @@ -#!/bin/sh -set -e -set -u -set -o pipefail - -function on_error { - echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" -} -trap 'on_error $LINENO' ERR - -if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then - # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy - # frameworks to, so exit 0 (signalling the script phase was successful). - exit 0 -fi - -echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" -mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - -COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" -SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" - -# Used as a return value for each invocation of `strip_invalid_archs` function. -STRIP_BINARY_RETVAL=0 - -# This protects against multiple targets copying the same framework dependency at the same time. The solution -# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html -RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") - -# Copies and strips a vendored framework -install_framework() -{ - if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then - local source="${BUILT_PRODUCTS_DIR}/$1" - elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then - local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" - elif [ -r "$1" ]; then - local source="$1" - fi - - local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - - if [ -L "${source}" ]; then - echo "Symlinked..." - source="$(readlink "${source}")" - fi - - # Use filter instead of exclude so missing patterns don't throw errors. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" - - local basename - basename="$(basename -s .framework "$1")" - binary="${destination}/${basename}.framework/${basename}" - - if ! [ -r "$binary" ]; then - binary="${destination}/${basename}" - elif [ -L "${binary}" ]; then - echo "Destination binary is symlinked..." - dirname="$(dirname "${binary}")" - binary="${dirname}/$(readlink "${binary}")" - fi - - # Strip invalid architectures so "fat" simulator / device frameworks work on device - if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then - strip_invalid_archs "$binary" - fi - - # Resign the code if required by the build settings to avoid unstable apps - code_sign_if_enabled "${destination}/$(basename "$1")" - - # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. - if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then - local swift_runtime_libs - swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) - for lib in $swift_runtime_libs; do - echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" - rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" - code_sign_if_enabled "${destination}/${lib}" - done - fi -} - -# Copies and strips a vendored dSYM -install_dsym() { - local source="$1" - if [ -r "$source" ]; then - # Copy the dSYM into a the targets temp dir. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" - - local basename - basename="$(basename -s .framework.dSYM "$source")" - binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" - - # Strip invalid architectures so "fat" simulator / device frameworks work on device - if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then - strip_invalid_archs "$binary" - fi - - if [[ $STRIP_BINARY_RETVAL == 1 ]]; then - # Move the stripped file into its final destination. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" - else - # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. - touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" - fi - fi -} - -# Copies the bcsymbolmap files of a vendored framework -install_bcsymbolmap() { - local bcsymbolmap_path="$1" - local destination="${BUILT_PRODUCTS_DIR}" - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" -} - -# Signs a framework with the provided identity -code_sign_if_enabled() { - if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then - # Use the current code_sign_identity - echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" - local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" - - if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then - code_sign_cmd="$code_sign_cmd &" - fi - echo "$code_sign_cmd" - eval "$code_sign_cmd" - fi -} - -# Strip invalid architectures -strip_invalid_archs() { - binary="$1" - # Get architectures for current target binary - binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" - # Intersect them with the architectures we are building for - intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" - # If there are no archs supported by this binary then warn the user - if [[ -z "$intersected_archs" ]]; then - echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." - STRIP_BINARY_RETVAL=0 - return - fi - stripped="" - for arch in $binary_archs; do - if ! [[ "${ARCHS}" == *"$arch"* ]]; then - # Strip non-valid architectures in-place - lipo -remove "$arch" -output "$binary" "$binary" - stripped="$stripped $arch" - fi - done - if [[ "$stripped" ]]; then - echo "Stripped $binary of architectures:$stripped" - fi - STRIP_BINARY_RETVAL=1 -} - - -if [[ "$CONFIGURATION" == "Debug" ]]; then - install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" - install_framework "${BUILT_PRODUCTS_DIR}/TestClient/TestClient.framework" -fi -if [[ "$CONFIGURATION" == "Release" ]]; then - install_framework "${BUILT_PRODUCTS_DIR}/Alamofire/Alamofire.framework" - install_framework "${BUILT_PRODUCTS_DIR}/TestClient/TestClient.framework" -fi -if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then - wait -fi diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-umbrella.h b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-umbrella.h deleted file mode 100644 index 1004f0f70412..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double Pods_TestClientAppVersionNumber; -FOUNDATION_EXPORT const unsigned char Pods_TestClientAppVersionString[]; - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.debug.xcconfig b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.debug.xcconfig deleted file mode 100644 index ae21d42906b6..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.debug.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/TestClient" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/TestClient/TestClient.framework/Headers" -LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "TestClient" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.modulemap b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.modulemap deleted file mode 100644 index 6f2c78be7491..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Pods_TestClientApp { - umbrella header "Pods-TestClientApp-umbrella.h" - - export * - module * { export * } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.release.xcconfig b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.release.xcconfig deleted file mode 100644 index ae21d42906b6..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.release.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/TestClient" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/TestClient/TestClient.framework/Headers" -LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "TestClient" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-Info.plist b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-Info.plist deleted file mode 100644 index 2243fe6e27dc..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.markdown b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.markdown deleted file mode 100644 index 102af7538517..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.markdown +++ /dev/null @@ -1,3 +0,0 @@ -# Acknowledgements -This application makes use of the following third party libraries: -Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.plist b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.plist deleted file mode 100644 index 7acbad1eabbf..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.plist +++ /dev/null @@ -1,29 +0,0 @@ - - - - - PreferenceSpecifiers - - - FooterText - This application makes use of the following third party libraries: - Title - Acknowledgements - Type - PSGroupSpecifier - - - FooterText - Generated by CocoaPods - https://cocoapods.org - Title - - Type - PSGroupSpecifier - - - StringsTable - Acknowledgements - Title - Acknowledgements - - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-dummy.m b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-dummy.m deleted file mode 100644 index 391cf05865f7..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods_TestClientAppTests : NSObject -@end -@implementation PodsDummy_Pods_TestClientAppTests -@end diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-umbrella.h b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-umbrella.h deleted file mode 100644 index f3c84c4c89dc..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double Pods_TestClientAppTestsVersionNumber; -FOUNDATION_EXPORT const unsigned char Pods_TestClientAppTestsVersionString[]; - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.debug.xcconfig b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.debug.xcconfig deleted file mode 100644 index 9f921a266745..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.debug.xcconfig +++ /dev/null @@ -1,9 +0,0 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/TestClient" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/TestClient/TestClient.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "TestClient" -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.modulemap b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.modulemap deleted file mode 100644 index a763c71493f7..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Pods_TestClientAppTests { - umbrella header "Pods-TestClientAppTests-umbrella.h" - - export * - module * { export * } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.release.xcconfig b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.release.xcconfig deleted file mode 100644 index 9f921a266745..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.release.xcconfig +++ /dev/null @@ -1,9 +0,0 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" "${PODS_CONFIGURATION_BUILD_DIR}/TestClient" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire/Alamofire.framework/Headers" "${PODS_CONFIGURATION_BUILD_DIR}/TestClient/TestClient.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "Alamofire" -framework "TestClient" -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-Info.plist b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-Info.plist deleted file mode 100644 index 2243fe6e27dc..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-dummy.m b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-dummy.m deleted file mode 100644 index e9a709a985a2..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_TestClient : NSObject -@end -@implementation PodsDummy_TestClient -@end diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-prefix.pch b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-prefix.pch deleted file mode 100644 index beb2a2441835..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-umbrella.h b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-umbrella.h deleted file mode 100644 index 57d4c595bc87..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double TestClientVersionNumber; -FOUNDATION_EXPORT const unsigned char TestClientVersionString[]; - diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.modulemap b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.modulemap deleted file mode 100644 index 645349a23a1c..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module TestClient { - umbrella header "TestClient-umbrella.h" - - export * - module * { export * } -} diff --git a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.xcconfig b/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.xcconfig deleted file mode 100644 index 439083561ed3..000000000000 --- a/samples/client/test/swift4/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.xcconfig +++ /dev/null @@ -1,11 +0,0 @@ -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/TestClient -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/Alamofire" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_ROOT = ${SRCROOT} -PODS_TARGET_SRCROOT = ${PODS_ROOT}/../.. -PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} -SKIP_INSTALL = YES -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/samples/client/test/swift5/default/TestClientApp/.gitignore b/samples/client/test/swift5/default/TestClientApp/.gitignore new file mode 100644 index 000000000000..0269c2f56db9 --- /dev/null +++ b/samples/client/test/swift5/default/TestClientApp/.gitignore @@ -0,0 +1,72 @@ +### https://raw.github.com/github/gitignore/7792e50daeaa6c07460484704671d1dc9f0045a7/Swift.gitignore + +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## Build generated +build/ +DerivedData/ + +## Various settings +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +xcuserdata/ + +## Other +*.moved-aside +*.xccheckout +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +.build/ + +# CocoaPods +# +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# +Pods/ + +# Carthage +# +# Add this line if you want to avoid checking in source code from Carthage dependencies. +Carthage/Checkouts + +Carthage/Build + +# fastlane +# +# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the +# screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots +fastlane/test_output + + diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Local Podspecs/TestClient.podspec.json b/samples/client/test/swift5/default/TestClientApp/Pods/Local Podspecs/TestClient.podspec.json deleted file mode 100644 index b456341de85f..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Local Podspecs/TestClient.podspec.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "TestClient", - "platforms": { - "ios": "9.0", - "osx": "10.11", - "tvos": "9.0", - "watchos": "3.0" - }, - "version": "1.0", - "source": { - "git": "git@github.com:OpenAPITools/openapi-generator.git", - "tag": "v1.0" - }, - "authors": "", - "license": "Proprietary", - "homepage": "https://github.com/openapitools/openapi-generator", - "summary": "TestClient", - "source_files": "TestClient/Classes/**/*.swift" -} diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Manifest.lock b/samples/client/test/swift5/default/TestClientApp/Pods/Manifest.lock deleted file mode 100644 index a22ff8bcb6f4..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Manifest.lock +++ /dev/null @@ -1,16 +0,0 @@ -PODS: - - TestClient (1.0) - -DEPENDENCIES: - - TestClient (from `../`) - -EXTERNAL SOURCES: - TestClient: - :path: "../" - -SPEC CHECKSUMS: - TestClient: 2c0d16f42076221adbf579221827fd034c3c4a85 - -PODFILE CHECKSUM: 837b06bfc9f93ccd7664fd918d113c8e3824bde3 - -COCOAPODS: 1.8.4 diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/test/swift5/default/TestClientApp/Pods/Pods.xcodeproj/project.pbxproj deleted file mode 100644 index 98ed66c7eb03..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Pods.xcodeproj/project.pbxproj +++ /dev/null @@ -1,946 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 48; - objects = { - -/* Begin PBXBuildFile section */ - 02FFBA90EA5EADA19A336739D6DCCEB0 /* PlaceCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA531D40F1343004B17AB92D6ABE3FAE /* PlaceCard.swift */; }; - 05F5ACD702C860CE19DEC8FCAB87E40B /* TestClient-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 56BA21CEA2FE0A2984C2309B26309A86 /* TestClient-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - 095D99ED77DB34E158D6487D64C577FB /* ModelDoubleArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = D96CAC1AD94153EABEA61CF4AD6F1297 /* ModelDoubleArray.swift */; }; - 23C7A6763A7E2DFD10B081432E36AB01 /* APIs.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42E3FBE2279497BCA853AAC22E8FC920 /* APIs.swift */; }; - 268A90C42CD895FDF00F71736B67DEE9 /* Pods-TestClientApp-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = ECC55036EDA2E6A74F2ABC59EEEF0D23 /* Pods-TestClientApp-dummy.m */; }; - 26966BEE6C13D2513B7AFFAD84F57AFF /* Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = D345901DAC44CC1C78E4390C24010A72 /* Extensions.swift */; }; - 279D52D2BBF4F9F41806CB559BBCC323 /* ModelWithIntAdditionalPropertiesOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = EACAE8683B0F549B3AF4101125D897B6 /* ModelWithIntAdditionalPropertiesOnly.swift */; }; - 3AF8B7B1239281A3B72182D5BF29DECE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3212113385A8FBBDB272BD23C409FF61 /* Foundation.framework */; }; - 3F82E278BBF49865698F48C2BDD3A8C8 /* ModelErrorInfoArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = CDFE1170689EB9D3A4C951DEDACB7863 /* ModelErrorInfoArray.swift */; }; - 438C479E9FDDCDD436CA20CB1D2523E9 /* PlaceCardAllOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = 443036458E47FB04182CB654C827E88F /* PlaceCardAllOf.swift */; }; - 4435680E8AEC40C0D41102941C65F54E /* Pods-TestClientAppTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 18C6EC373298C48FCAFA0DDA13E26347 /* Pods-TestClientAppTests-dummy.m */; }; - 46F6C1F49012FFD9B45EDDB8C6F9DEE8 /* APIHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43377E32ED406BE472E3C2BE793D1D6F /* APIHelper.swift */; }; - 479A7BE76F5560BBE0042A2F6E43CBB0 /* URLSessionImplementations.swift in Sources */ = {isa = PBXBuildFile; fileRef = AD30F80249F5BB6CE3807EB6F8992144 /* URLSessionImplementations.swift */; }; - 4EC1AA6BB0AD6DDE9689926005084DFB /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D6CBEFA67141C1B6F630B3A6CCFCD25 /* Models.swift */; }; - 59B3866FA296D6B33751F37409FFEC57 /* ErrorInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 84118CF8982F9E76C323C67EE2F647DF /* ErrorInfo.swift */; }; - 5F369A3A957334C7121219B52C9D65AA /* SampleSubClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1168715462C609C65DF977569FD58727 /* SampleSubClass.swift */; }; - 6277449D5C1FA4A4E093CCC4C44111C2 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3212113385A8FBBDB272BD23C409FF61 /* Foundation.framework */; }; - 6DA3FAE017CD3551A3E2AA7BA913D351 /* JSONDataEncoding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2FB5502C079427A0D868D1B2B6B92086 /* JSONDataEncoding.swift */; }; - 7357B46081E64E0AE6ECAD986CA5DD6A /* CodableHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 259FECA51D72C4664609815109F5FD3B /* CodableHelper.swift */; }; - 73D33A91FD9B2D8B5535B1A21680A1EE /* TestClient-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 564BBF3C5D0BB297545FD0A05DE6D8B7 /* TestClient-dummy.m */; }; - 8429C4D45B15BBDDD2798A7CD92A8F43 /* StringEnum.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0BFCAC223EB3E5661E180C8E4CBF82F /* StringEnum.swift */; }; - 87C3C30946F53347EDA3F9060C63F8D7 /* PersonCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7CB472C5319EDB53D712FD7CF2C0AD8 /* PersonCard.swift */; }; - 9AF02BB5E3C4D96BF5E6FC80237AA940 /* Configuration.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD1711B3F916640CDACA0326190016EC /* Configuration.swift */; }; - 9FF109F83DB17F92E6076CB9E90596E9 /* SampleSubClassAllOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CF197DC7916DC38C05966304592E840 /* SampleSubClassAllOf.swift */; }; - A5EAA2E7E946EB46ADBE60E63142C7DC /* VariableNameTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = DDB02FEDB97F5D4032D466D9FA25874A /* VariableNameTest.swift */; }; - A99CABE1AF2E62510C9288326F245BD8 /* GetAllModelsResult.swift in Sources */ = {isa = PBXBuildFile; fileRef = A76B0FAEC0C5A0BF72809C3E2A1F77A9 /* GetAllModelsResult.swift */; }; - AD0D89AAFA166B9B38C1F838C00C636D /* ModelWithStringAdditionalPropertiesOnly.swift in Sources */ = {isa = PBXBuildFile; fileRef = A8E88820BF62E8EDB8DF4D02D41978AC /* ModelWithStringAdditionalPropertiesOnly.swift */; }; - B33500DB9D0190B3A8592E43E12A6866 /* ModelStringArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1CBA1A8875AAAF41A6D4BDAD2C1EB8D /* ModelStringArray.swift */; }; - C07F9AA95A46282A1D273A214786D5FB /* AllPrimitives.swift in Sources */ = {isa = PBXBuildFile; fileRef = 183109838DC5804EA6FD674A8CC55417 /* AllPrimitives.swift */; }; - C1B9AB334A57F9328EF1A7C6F7F7C385 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 3212113385A8FBBDB272BD23C409FF61 /* Foundation.framework */; }; - C872EC896D31C3BD2C655456D24AEC79 /* OpenISO8601DateFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 661B3CB0BB3F17022477B8A3C61996A4 /* OpenISO8601DateFormatter.swift */; }; - D61D04428EA4D5471DF5C44394840076 /* SampleBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 403EB1B1F8417E00D264E9115BFF9778 /* SampleBase.swift */; }; - D73D105F4B969E14B6BF95A954EAB4B9 /* JSONEncodingHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B28C8A1EE76A12DB43A5FDB8342E8BE /* JSONEncodingHelper.swift */; }; - D82F0987580977B789D60461C5CD2354 /* Swift5TestAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D4A17DEA66E914BC4DC9C690C032025 /* Swift5TestAPI.swift */; }; - D8ABC53F70A4A3DD12BB92195A4F5EA2 /* SynchronizedDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90C3FED83273102287DF463DA9523A58 /* SynchronizedDictionary.swift */; }; - DB43CC6E8B07E962C68B1E61347FB2AB /* PersonCardAllOf.swift in Sources */ = {isa = PBXBuildFile; fileRef = A01E32F0EF05821EB4D322A2E29B6B0D /* PersonCardAllOf.swift */; }; - E05C861EDA3401C16204431A09D75379 /* Pods-TestClientApp-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = DE94C910653499F2AB069ACEE0FDC2DD /* Pods-TestClientApp-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - E708DB732C1BC60401EC1F4CFC4718FA /* Pods-TestClientAppTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = E3BC082537CA1630DA1E1DCFDB9BC495 /* Pods-TestClientAppTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; - F3BF0BB9E24D6FA4514D39E0900E9092 /* BaseCard.swift in Sources */ = {isa = PBXBuildFile; fileRef = 789B567B495ACBF903AB14F7C396DCF4 /* BaseCard.swift */; }; - FBFF8FA7141150DE0DDB3996C07017EF /* ModelWithPropertiesAndAdditionalProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1BEA3B4071F1F70319AE9907756D7F4C /* ModelWithPropertiesAndAdditionalProperties.swift */; }; -/* End PBXBuildFile section */ - -/* Begin PBXContainerItemProxy section */ - 8788B4EA1EE8B4ABC69B264C82484356 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = B72EF653ED86BEBAF8987EA7602289AA; - remoteInfo = TestClient; - }; - D46C3A7D874BD540F75F8C8EE656DAA2 /* PBXContainerItemProxy */ = { - isa = PBXContainerItemProxy; - containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; - proxyType = 1; - remoteGlobalIDString = 9B2D563D3B39C8B41B45CEC35AFF91AB; - remoteInfo = "Pods-TestClientApp"; - }; -/* End PBXContainerItemProxy section */ - -/* Begin PBXFileReference section */ - 03158506844BE7CC7E89C1B0570590EE /* Pods-TestClientApp-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestClientApp-Info.plist"; sourceTree = ""; }; - 0B6986E11921769A3669DC7C6D277B81 /* TestClient.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = TestClient.modulemap; sourceTree = ""; }; - 0FB13DF3D35D4A25F6F47E32680D9927 /* TestClient-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "TestClient-Info.plist"; sourceTree = ""; }; - 1168715462C609C65DF977569FD58727 /* SampleSubClass.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SampleSubClass.swift; sourceTree = ""; }; - 17FDC3E431E2399A6939534930387170 /* BaseCard.md */ = {isa = PBXFileReference; includeInIndex = 1; name = BaseCard.md; path = docs/BaseCard.md; sourceTree = ""; }; - 183109838DC5804EA6FD674A8CC55417 /* AllPrimitives.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AllPrimitives.swift; sourceTree = ""; }; - 18C6EC373298C48FCAFA0DDA13E26347 /* Pods-TestClientAppTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-TestClientAppTests-dummy.m"; sourceTree = ""; }; - 193297BCDCD102E9B7B9AAA7C4B454B4 /* SampleBase.md */ = {isa = PBXFileReference; includeInIndex = 1; name = SampleBase.md; path = docs/SampleBase.md; sourceTree = ""; }; - 1BEA3B4071F1F70319AE9907756D7F4C /* ModelWithPropertiesAndAdditionalProperties.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelWithPropertiesAndAdditionalProperties.swift; sourceTree = ""; }; - 204861306843B9E8C98A4E9620D67592 /* TestClient-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "TestClient-prefix.pch"; sourceTree = ""; }; - 23A1759B79F1A6D85541C7C67500B41B /* SampleSubClassAllOf.md */ = {isa = PBXFileReference; includeInIndex = 1; name = SampleSubClassAllOf.md; path = docs/SampleSubClassAllOf.md; sourceTree = ""; }; - 259FECA51D72C4664609815109F5FD3B /* CodableHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CodableHelper.swift; path = TestClient/Classes/OpenAPIs/CodableHelper.swift; sourceTree = ""; }; - 2FB5502C079427A0D868D1B2B6B92086 /* JSONDataEncoding.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONDataEncoding.swift; path = TestClient/Classes/OpenAPIs/JSONDataEncoding.swift; sourceTree = ""; }; - 3212113385A8FBBDB272BD23C409FF61 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS12.2.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; - 3561CB379752919C3A72CDEBF8AF05E2 /* ErrorInfo.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ErrorInfo.md; path = docs/ErrorInfo.md; sourceTree = ""; }; - 3B28C8A1EE76A12DB43A5FDB8342E8BE /* JSONEncodingHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = JSONEncodingHelper.swift; path = TestClient/Classes/OpenAPIs/JSONEncodingHelper.swift; sourceTree = ""; }; - 3D0B805B8B34B9DFEB640A6DA64E1D60 /* PersonCard.md */ = {isa = PBXFileReference; includeInIndex = 1; name = PersonCard.md; path = docs/PersonCard.md; sourceTree = ""; }; - 403EB1B1F8417E00D264E9115BFF9778 /* SampleBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SampleBase.swift; sourceTree = ""; }; - 42E3FBE2279497BCA853AAC22E8FC920 /* APIs.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIs.swift; path = TestClient/Classes/OpenAPIs/APIs.swift; sourceTree = ""; }; - 43377E32ED406BE472E3C2BE793D1D6F /* APIHelper.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = APIHelper.swift; path = TestClient/Classes/OpenAPIs/APIHelper.swift; sourceTree = ""; }; - 443036458E47FB04182CB654C827E88F /* PlaceCardAllOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PlaceCardAllOf.swift; sourceTree = ""; }; - 48C4EB9FB0827F886ABA8B7EBE8EEA8E /* Pods-TestClientAppTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestClientAppTests.release.xcconfig"; sourceTree = ""; }; - 49D81AF16AD6E9D1CD328A788E735467 /* Swift5TestAPI.md */ = {isa = PBXFileReference; includeInIndex = 1; name = Swift5TestAPI.md; path = docs/Swift5TestAPI.md; sourceTree = ""; }; - 514DC806E09C9C69D95FB60DFDC85628 /* SampleSubClass.md */ = {isa = PBXFileReference; includeInIndex = 1; name = SampleSubClass.md; path = docs/SampleSubClass.md; sourceTree = ""; }; - 564BBF3C5D0BB297545FD0A05DE6D8B7 /* TestClient-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "TestClient-dummy.m"; sourceTree = ""; }; - 56BA21CEA2FE0A2984C2309B26309A86 /* TestClient-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "TestClient-umbrella.h"; sourceTree = ""; }; - 5DC57D75B5D78687B4DC11CDCF20AD10 /* Pods_TestClientAppTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_TestClientAppTests.framework; path = "Pods-TestClientAppTests.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; - 661B3CB0BB3F17022477B8A3C61996A4 /* OpenISO8601DateFormatter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OpenISO8601DateFormatter.swift; path = TestClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift; sourceTree = ""; }; - 789B567B495ACBF903AB14F7C396DCF4 /* BaseCard.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = BaseCard.swift; sourceTree = ""; }; - 7D6CBEFA67141C1B6F630B3A6CCFCD25 /* Models.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Models.swift; path = TestClient/Classes/OpenAPIs/Models.swift; sourceTree = ""; }; - 7E7CB11C6E8EF71424C6D3725EE67DE8 /* Pods-TestClientAppTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestClientAppTests.debug.xcconfig"; sourceTree = ""; }; - 7FFDF46D7409B56C30D6FA0A2E40215E /* Pods-TestClientAppTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestClientAppTests-Info.plist"; sourceTree = ""; }; - 813BC85EFF5F450D59C6386A26635B0C /* PlaceCard.md */ = {isa = PBXFileReference; includeInIndex = 1; name = PlaceCard.md; path = docs/PlaceCard.md; sourceTree = ""; }; - 82FD0B66B6128354B30FB2FF3088F3A4 /* Pods-TestClientApp.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestClientApp.debug.xcconfig"; sourceTree = ""; }; - 84118CF8982F9E76C323C67EE2F647DF /* ErrorInfo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ErrorInfo.swift; sourceTree = ""; }; - 88F61FFF3738A9F3E86A9080DBE03AF9 /* ModelStringArray.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelStringArray.md; path = docs/ModelStringArray.md; sourceTree = ""; }; - 892BF895C1CF4CDD225A15EE546704C0 /* TestClient.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = TestClient.xcconfig; sourceTree = ""; }; - 8CE012DCCB8B5B967C29637C307A4EC1 /* StringEnum.md */ = {isa = PBXFileReference; includeInIndex = 1; name = StringEnum.md; path = docs/StringEnum.md; sourceTree = ""; }; - 8D4A17DEA66E914BC4DC9C690C032025 /* Swift5TestAPI.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = Swift5TestAPI.swift; sourceTree = ""; }; - 8FD8AC6EB7F6A69BAF69A91222B2FBE7 /* ModelErrorInfoArray.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelErrorInfoArray.md; path = docs/ModelErrorInfoArray.md; sourceTree = ""; }; - 90C3FED83273102287DF463DA9523A58 /* SynchronizedDictionary.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedDictionary.swift; path = TestClient/Classes/OpenAPIs/SynchronizedDictionary.swift; sourceTree = ""; }; - 9166C0537D2798D1EE20F58CDEDA48C2 /* Pods-TestClientAppTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-TestClientAppTests.modulemap"; sourceTree = ""; }; - 91CB91AB1B6089705AC6AC2667A91BFE /* PlaceCardAllOf.md */ = {isa = PBXFileReference; includeInIndex = 1; name = PlaceCardAllOf.md; path = docs/PlaceCardAllOf.md; sourceTree = ""; }; - 9B02CAAB34454FF0600319BD67306844 /* ModelWithPropertiesAndAdditionalProperties.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelWithPropertiesAndAdditionalProperties.md; path = docs/ModelWithPropertiesAndAdditionalProperties.md; sourceTree = ""; }; - 9CF197DC7916DC38C05966304592E840 /* SampleSubClassAllOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SampleSubClassAllOf.swift; sourceTree = ""; }; - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - 9F619F6315E550CE0BE8322DB2EDBCD3 /* VariableNameTest.md */ = {isa = PBXFileReference; includeInIndex = 1; name = VariableNameTest.md; path = docs/VariableNameTest.md; sourceTree = ""; }; - A01E32F0EF05821EB4D322A2E29B6B0D /* PersonCardAllOf.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PersonCardAllOf.swift; sourceTree = ""; }; - A0BFCAC223EB3E5661E180C8E4CBF82F /* StringEnum.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = StringEnum.swift; sourceTree = ""; }; - A2C44571511EE10C5013D963197B890D /* Pods-TestClientApp-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-TestClientApp-acknowledgements.markdown"; sourceTree = ""; }; - A4C2E7C4FC74158B642EF7353C920280 /* Pods-TestClientAppTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestClientAppTests-acknowledgements.plist"; sourceTree = ""; }; - A76B0FAEC0C5A0BF72809C3E2A1F77A9 /* GetAllModelsResult.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = GetAllModelsResult.swift; sourceTree = ""; }; - A7CB472C5319EDB53D712FD7CF2C0AD8 /* PersonCard.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PersonCard.swift; sourceTree = ""; }; - A8E88820BF62E8EDB8DF4D02D41978AC /* ModelWithStringAdditionalPropertiesOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelWithStringAdditionalPropertiesOnly.swift; sourceTree = ""; }; - AD30F80249F5BB6CE3807EB6F8992144 /* URLSessionImplementations.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = URLSessionImplementations.swift; path = TestClient/Classes/OpenAPIs/URLSessionImplementations.swift; sourceTree = ""; }; - AFBE3D468DBC68112B42C229014117EF /* Pods-TestClientApp-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-TestClientApp-acknowledgements.plist"; sourceTree = ""; }; - B1D5F61FD93DB03C60173A799F6B967D /* Pods-TestClientApp.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-TestClientApp.release.xcconfig"; sourceTree = ""; }; - B464EEB28AE56DEC88BA2908B67FEA2B /* TestClient.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = TestClient.framework; path = TestClient.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - B63BBEF68EDA25B03A0F32C48EB924DE /* Pods-TestClientApp.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-TestClientApp.modulemap"; sourceTree = ""; }; - B90B2B512EBCEAA1BDAD6D1D006F40ED /* GetAllModelsResult.md */ = {isa = PBXFileReference; includeInIndex = 1; name = GetAllModelsResult.md; path = docs/GetAllModelsResult.md; sourceTree = ""; }; - C2475B69B16D8E2208218F7AAAA39C7E /* Pods-TestClientAppTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-TestClientAppTests-acknowledgements.markdown"; sourceTree = ""; }; - CDFE1170689EB9D3A4C951DEDACB7863 /* ModelErrorInfoArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelErrorInfoArray.swift; sourceTree = ""; }; - CE5D349FC4CC6739E48AA3EE3BEF5193 /* PersonCardAllOf.md */ = {isa = PBXFileReference; includeInIndex = 1; name = PersonCardAllOf.md; path = docs/PersonCardAllOf.md; sourceTree = ""; }; - D0FEEC683C6A55ADE0A43EFD3F9D6E2D /* ModelWithStringAdditionalPropertiesOnly.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelWithStringAdditionalPropertiesOnly.md; path = docs/ModelWithStringAdditionalPropertiesOnly.md; sourceTree = ""; }; - D1CBA1A8875AAAF41A6D4BDAD2C1EB8D /* ModelStringArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelStringArray.swift; sourceTree = ""; }; - D345901DAC44CC1C78E4390C24010A72 /* Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Extensions.swift; path = TestClient/Classes/OpenAPIs/Extensions.swift; sourceTree = ""; }; - D96CAC1AD94153EABEA61CF4AD6F1297 /* ModelDoubleArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelDoubleArray.swift; sourceTree = ""; }; - DA531D40F1343004B17AB92D6ABE3FAE /* PlaceCard.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PlaceCard.swift; sourceTree = ""; }; - DDB02FEDB97F5D4032D466D9FA25874A /* VariableNameTest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = VariableNameTest.swift; sourceTree = ""; }; - DE94C910653499F2AB069ACEE0FDC2DD /* Pods-TestClientApp-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-TestClientApp-umbrella.h"; sourceTree = ""; }; - E3BC082537CA1630DA1E1DCFDB9BC495 /* Pods-TestClientAppTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-TestClientAppTests-umbrella.h"; sourceTree = ""; }; - E48311A95FCE734638F61C53CE6E0C37 /* TestClient.podspec */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; path = TestClient.podspec; sourceTree = ""; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; - E64E970612B808A04B0C7AA69EE0D00F /* Pods-TestClientApp-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-TestClientApp-frameworks.sh"; sourceTree = ""; }; - E92541535F215E7AE8AEFF9B43A2D82E /* ModelDoubleArray.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelDoubleArray.md; path = docs/ModelDoubleArray.md; sourceTree = ""; }; - EACAE8683B0F549B3AF4101125D897B6 /* ModelWithIntAdditionalPropertiesOnly.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = ModelWithIntAdditionalPropertiesOnly.swift; sourceTree = ""; }; - ECC55036EDA2E6A74F2ABC59EEEF0D23 /* Pods-TestClientApp-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-TestClientApp-dummy.m"; sourceTree = ""; }; - ED945DEFB21A893654BFD2176B34612B /* AllPrimitives.md */ = {isa = PBXFileReference; includeInIndex = 1; name = AllPrimitives.md; path = docs/AllPrimitives.md; sourceTree = ""; }; - F56DD477F6D4BD57530D442F87E1CA7E /* ModelWithIntAdditionalPropertiesOnly.md */ = {isa = PBXFileReference; includeInIndex = 1; name = ModelWithIntAdditionalPropertiesOnly.md; path = docs/ModelWithIntAdditionalPropertiesOnly.md; sourceTree = ""; }; - FD1711B3F916640CDACA0326190016EC /* Configuration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Configuration.swift; path = TestClient/Classes/OpenAPIs/Configuration.swift; sourceTree = ""; }; - FE01B70C59C9B12663E8EA208FEECF02 /* README.md */ = {isa = PBXFileReference; includeInIndex = 1; path = README.md; sourceTree = ""; }; - FED082EE959E5B5A9579D3EA6B287F66 /* Pods_TestClientApp.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Pods_TestClientApp.framework; path = "Pods-TestClientApp.framework"; sourceTree = BUILT_PRODUCTS_DIR; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - 327101568922D8A5864A1EA568754ADD /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 3AF8B7B1239281A3B72182D5BF29DECE /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 54B50DB8B7D7164CE18CA0FC9FCAB915 /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - 6277449D5C1FA4A4E093CCC4C44111C2 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - A5B936DFC8920559A0FA2490E8D9FC8A /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - C1B9AB334A57F9328EF1A7C6F7F7C385 /* Foundation.framework in Frameworks */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - 01252A1AF71ABEED85368EE93297092D /* Pods-TestClientApp */ = { - isa = PBXGroup; - children = ( - B63BBEF68EDA25B03A0F32C48EB924DE /* Pods-TestClientApp.modulemap */, - A2C44571511EE10C5013D963197B890D /* Pods-TestClientApp-acknowledgements.markdown */, - AFBE3D468DBC68112B42C229014117EF /* Pods-TestClientApp-acknowledgements.plist */, - ECC55036EDA2E6A74F2ABC59EEEF0D23 /* Pods-TestClientApp-dummy.m */, - E64E970612B808A04B0C7AA69EE0D00F /* Pods-TestClientApp-frameworks.sh */, - 03158506844BE7CC7E89C1B0570590EE /* Pods-TestClientApp-Info.plist */, - DE94C910653499F2AB069ACEE0FDC2DD /* Pods-TestClientApp-umbrella.h */, - 82FD0B66B6128354B30FB2FF3088F3A4 /* Pods-TestClientApp.debug.xcconfig */, - B1D5F61FD93DB03C60173A799F6B967D /* Pods-TestClientApp.release.xcconfig */, - ); - name = "Pods-TestClientApp"; - path = "Target Support Files/Pods-TestClientApp"; - sourceTree = ""; - }; - 2B9E5065DD311AE82CAECB5D52F0FC74 /* Pods-TestClientAppTests */ = { - isa = PBXGroup; - children = ( - 9166C0537D2798D1EE20F58CDEDA48C2 /* Pods-TestClientAppTests.modulemap */, - C2475B69B16D8E2208218F7AAAA39C7E /* Pods-TestClientAppTests-acknowledgements.markdown */, - A4C2E7C4FC74158B642EF7353C920280 /* Pods-TestClientAppTests-acknowledgements.plist */, - 18C6EC373298C48FCAFA0DDA13E26347 /* Pods-TestClientAppTests-dummy.m */, - 7FFDF46D7409B56C30D6FA0A2E40215E /* Pods-TestClientAppTests-Info.plist */, - E3BC082537CA1630DA1E1DCFDB9BC495 /* Pods-TestClientAppTests-umbrella.h */, - 7E7CB11C6E8EF71424C6D3725EE67DE8 /* Pods-TestClientAppTests.debug.xcconfig */, - 48C4EB9FB0827F886ABA8B7EBE8EEA8E /* Pods-TestClientAppTests.release.xcconfig */, - ); - name = "Pods-TestClientAppTests"; - path = "Target Support Files/Pods-TestClientAppTests"; - sourceTree = ""; - }; - 3789220B380FDAD8643BE44B7446E0C5 /* TestClient */ = { - isa = PBXGroup; - children = ( - 43377E32ED406BE472E3C2BE793D1D6F /* APIHelper.swift */, - 42E3FBE2279497BCA853AAC22E8FC920 /* APIs.swift */, - 259FECA51D72C4664609815109F5FD3B /* CodableHelper.swift */, - FD1711B3F916640CDACA0326190016EC /* Configuration.swift */, - D345901DAC44CC1C78E4390C24010A72 /* Extensions.swift */, - 2FB5502C079427A0D868D1B2B6B92086 /* JSONDataEncoding.swift */, - 3B28C8A1EE76A12DB43A5FDB8342E8BE /* JSONEncodingHelper.swift */, - 7D6CBEFA67141C1B6F630B3A6CCFCD25 /* Models.swift */, - 661B3CB0BB3F17022477B8A3C61996A4 /* OpenISO8601DateFormatter.swift */, - 90C3FED83273102287DF463DA9523A58 /* SynchronizedDictionary.swift */, - AD30F80249F5BB6CE3807EB6F8992144 /* URLSessionImplementations.swift */, - 8792629FA71C508FF0986C24235216A1 /* APIs */, - E64AF38AF1D0D81ABCA7EF5CFA5BD0E0 /* Models */, - 878CFB58CCBFBE1363538597FBB57530 /* Pod */, - C8A2DBD77EC3BF915B278C880B2533FE /* Support Files */, - ); - name = TestClient; - path = ../..; - sourceTree = ""; - }; - 3C4C30950B0A5E0D571BF164238CE41C /* Targets Support Files */ = { - isa = PBXGroup; - children = ( - 01252A1AF71ABEED85368EE93297092D /* Pods-TestClientApp */, - 2B9E5065DD311AE82CAECB5D52F0FC74 /* Pods-TestClientAppTests */, - ); - name = "Targets Support Files"; - sourceTree = ""; - }; - 7F969031BA2C2DCF934422D909C9DF33 /* Development Pods */ = { - isa = PBXGroup; - children = ( - 3789220B380FDAD8643BE44B7446E0C5 /* TestClient */, - ); - name = "Development Pods"; - sourceTree = ""; - }; - 82487862487832CCB0A8662A9AF1E6F4 /* Products */ = { - isa = PBXGroup; - children = ( - FED082EE959E5B5A9579D3EA6B287F66 /* Pods_TestClientApp.framework */, - 5DC57D75B5D78687B4DC11CDCF20AD10 /* Pods_TestClientAppTests.framework */, - B464EEB28AE56DEC88BA2908B67FEA2B /* TestClient.framework */, - ); - name = Products; - sourceTree = ""; - }; - 878CFB58CCBFBE1363538597FBB57530 /* Pod */ = { - isa = PBXGroup; - children = ( - ED945DEFB21A893654BFD2176B34612B /* AllPrimitives.md */, - 17FDC3E431E2399A6939534930387170 /* BaseCard.md */, - 3561CB379752919C3A72CDEBF8AF05E2 /* ErrorInfo.md */, - B90B2B512EBCEAA1BDAD6D1D006F40ED /* GetAllModelsResult.md */, - E92541535F215E7AE8AEFF9B43A2D82E /* ModelDoubleArray.md */, - 8FD8AC6EB7F6A69BAF69A91222B2FBE7 /* ModelErrorInfoArray.md */, - 88F61FFF3738A9F3E86A9080DBE03AF9 /* ModelStringArray.md */, - F56DD477F6D4BD57530D442F87E1CA7E /* ModelWithIntAdditionalPropertiesOnly.md */, - 9B02CAAB34454FF0600319BD67306844 /* ModelWithPropertiesAndAdditionalProperties.md */, - D0FEEC683C6A55ADE0A43EFD3F9D6E2D /* ModelWithStringAdditionalPropertiesOnly.md */, - 3D0B805B8B34B9DFEB640A6DA64E1D60 /* PersonCard.md */, - CE5D349FC4CC6739E48AA3EE3BEF5193 /* PersonCardAllOf.md */, - 813BC85EFF5F450D59C6386A26635B0C /* PlaceCard.md */, - 91CB91AB1B6089705AC6AC2667A91BFE /* PlaceCardAllOf.md */, - FE01B70C59C9B12663E8EA208FEECF02 /* README.md */, - 193297BCDCD102E9B7B9AAA7C4B454B4 /* SampleBase.md */, - 514DC806E09C9C69D95FB60DFDC85628 /* SampleSubClass.md */, - 23A1759B79F1A6D85541C7C67500B41B /* SampleSubClassAllOf.md */, - 8CE012DCCB8B5B967C29637C307A4EC1 /* StringEnum.md */, - 49D81AF16AD6E9D1CD328A788E735467 /* Swift5TestAPI.md */, - E48311A95FCE734638F61C53CE6E0C37 /* TestClient.podspec */, - 9F619F6315E550CE0BE8322DB2EDBCD3 /* VariableNameTest.md */, - ); - name = Pod; - sourceTree = ""; - }; - 8792629FA71C508FF0986C24235216A1 /* APIs */ = { - isa = PBXGroup; - children = ( - 8D4A17DEA66E914BC4DC9C690C032025 /* Swift5TestAPI.swift */, - ); - name = APIs; - path = TestClient/Classes/OpenAPIs/APIs; - sourceTree = ""; - }; - C0834CEBB1379A84116EF29F93051C60 /* iOS */ = { - isa = PBXGroup; - children = ( - 3212113385A8FBBDB272BD23C409FF61 /* Foundation.framework */, - ); - name = iOS; - sourceTree = ""; - }; - C8A2DBD77EC3BF915B278C880B2533FE /* Support Files */ = { - isa = PBXGroup; - children = ( - 0B6986E11921769A3669DC7C6D277B81 /* TestClient.modulemap */, - 892BF895C1CF4CDD225A15EE546704C0 /* TestClient.xcconfig */, - 564BBF3C5D0BB297545FD0A05DE6D8B7 /* TestClient-dummy.m */, - 0FB13DF3D35D4A25F6F47E32680D9927 /* TestClient-Info.plist */, - 204861306843B9E8C98A4E9620D67592 /* TestClient-prefix.pch */, - 56BA21CEA2FE0A2984C2309B26309A86 /* TestClient-umbrella.h */, - ); - name = "Support Files"; - path = "TestClientApp/Pods/Target Support Files/TestClient"; - sourceTree = ""; - }; - CF1408CF629C7361332E53B88F7BD30C = { - isa = PBXGroup; - children = ( - 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, - 7F969031BA2C2DCF934422D909C9DF33 /* Development Pods */, - D210D550F4EA176C3123ED886F8F87F5 /* Frameworks */, - 82487862487832CCB0A8662A9AF1E6F4 /* Products */, - 3C4C30950B0A5E0D571BF164238CE41C /* Targets Support Files */, - ); - sourceTree = ""; - }; - D210D550F4EA176C3123ED886F8F87F5 /* Frameworks */ = { - isa = PBXGroup; - children = ( - C0834CEBB1379A84116EF29F93051C60 /* iOS */, - ); - name = Frameworks; - sourceTree = ""; - }; - E64AF38AF1D0D81ABCA7EF5CFA5BD0E0 /* Models */ = { - isa = PBXGroup; - children = ( - 183109838DC5804EA6FD674A8CC55417 /* AllPrimitives.swift */, - 789B567B495ACBF903AB14F7C396DCF4 /* BaseCard.swift */, - 84118CF8982F9E76C323C67EE2F647DF /* ErrorInfo.swift */, - A76B0FAEC0C5A0BF72809C3E2A1F77A9 /* GetAllModelsResult.swift */, - D96CAC1AD94153EABEA61CF4AD6F1297 /* ModelDoubleArray.swift */, - CDFE1170689EB9D3A4C951DEDACB7863 /* ModelErrorInfoArray.swift */, - D1CBA1A8875AAAF41A6D4BDAD2C1EB8D /* ModelStringArray.swift */, - EACAE8683B0F549B3AF4101125D897B6 /* ModelWithIntAdditionalPropertiesOnly.swift */, - 1BEA3B4071F1F70319AE9907756D7F4C /* ModelWithPropertiesAndAdditionalProperties.swift */, - A8E88820BF62E8EDB8DF4D02D41978AC /* ModelWithStringAdditionalPropertiesOnly.swift */, - A7CB472C5319EDB53D712FD7CF2C0AD8 /* PersonCard.swift */, - A01E32F0EF05821EB4D322A2E29B6B0D /* PersonCardAllOf.swift */, - DA531D40F1343004B17AB92D6ABE3FAE /* PlaceCard.swift */, - 443036458E47FB04182CB654C827E88F /* PlaceCardAllOf.swift */, - 403EB1B1F8417E00D264E9115BFF9778 /* SampleBase.swift */, - 1168715462C609C65DF977569FD58727 /* SampleSubClass.swift */, - 9CF197DC7916DC38C05966304592E840 /* SampleSubClassAllOf.swift */, - A0BFCAC223EB3E5661E180C8E4CBF82F /* StringEnum.swift */, - DDB02FEDB97F5D4032D466D9FA25874A /* VariableNameTest.swift */, - ); - name = Models; - path = TestClient/Classes/OpenAPIs/Models; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXHeadersBuildPhase section */ - 858130C406B2CBB8EDA467FC3C16AC7B /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - 05F5ACD702C860CE19DEC8FCAB87E40B /* TestClient-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - E6E241430EFD0B12D73F2514BE42A902 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - E05C861EDA3401C16204431A09D75379 /* Pods-TestClientApp-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - F85310E66C57158DB3FA693AF79EDAC7 /* Headers */ = { - isa = PBXHeadersBuildPhase; - buildActionMask = 2147483647; - files = ( - E708DB732C1BC60401EC1F4CFC4718FA /* Pods-TestClientAppTests-umbrella.h in Headers */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXHeadersBuildPhase section */ - -/* Begin PBXNativeTarget section */ - 2D75029181FED2A76CE4D7E9C7324E1A /* Pods-TestClientAppTests */ = { - isa = PBXNativeTarget; - buildConfigurationList = F5DCF5CCC2DD022C81242D669FBA2A53 /* Build configuration list for PBXNativeTarget "Pods-TestClientAppTests" */; - buildPhases = ( - F85310E66C57158DB3FA693AF79EDAC7 /* Headers */, - FEBEDF2CD3F3F14C05232EC28A5EF48C /* Sources */, - 54B50DB8B7D7164CE18CA0FC9FCAB915 /* Frameworks */, - 03481D112E7D051F903DE8784BF22687 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - EC9E65DA36BCE418EF8ACAEA50766BBA /* PBXTargetDependency */, - ); - name = "Pods-TestClientAppTests"; - productName = "Pods-TestClientAppTests"; - productReference = 5DC57D75B5D78687B4DC11CDCF20AD10 /* Pods_TestClientAppTests.framework */; - productType = "com.apple.product-type.framework"; - }; - 9B2D563D3B39C8B41B45CEC35AFF91AB /* Pods-TestClientApp */ = { - isa = PBXNativeTarget; - buildConfigurationList = D8CA9B2C39BEDB78745943095DB0F76A /* Build configuration list for PBXNativeTarget "Pods-TestClientApp" */; - buildPhases = ( - E6E241430EFD0B12D73F2514BE42A902 /* Headers */, - 30376D28819EB4222324B1599818AA2E /* Sources */, - 327101568922D8A5864A1EA568754ADD /* Frameworks */, - 249B61D9BD8682D922DADE95CF024037 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - B6CB5A55B80757512913E8C17BE67BA1 /* PBXTargetDependency */, - ); - name = "Pods-TestClientApp"; - productName = "Pods-TestClientApp"; - productReference = FED082EE959E5B5A9579D3EA6B287F66 /* Pods_TestClientApp.framework */; - productType = "com.apple.product-type.framework"; - }; - B72EF653ED86BEBAF8987EA7602289AA /* TestClient */ = { - isa = PBXNativeTarget; - buildConfigurationList = 45A0725886CC4152E1A7A7895FD616FE /* Build configuration list for PBXNativeTarget "TestClient" */; - buildPhases = ( - 858130C406B2CBB8EDA467FC3C16AC7B /* Headers */, - 891FDC0ECDDDC0341FD69A8163332A57 /* Sources */, - A5B936DFC8920559A0FA2490E8D9FC8A /* Frameworks */, - 2BE7CABBA55E1D7FEFDEE56BE2272511 /* Resources */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = TestClient; - productName = TestClient; - productReference = B464EEB28AE56DEC88BA2908B67FEA2B /* TestClient.framework */; - productType = "com.apple.product-type.framework"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - BFDFE7DC352907FC980B868725387E98 /* Project object */ = { - isa = PBXProject; - attributes = { - LastSwiftUpdateCheck = 1100; - LastUpgradeCheck = 1100; - }; - buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; - compatibilityVersion = "Xcode 8.0"; - developmentRegion = en; - hasScannedForEncodings = 0; - knownRegions = ( - en, - Base, - ); - mainGroup = CF1408CF629C7361332E53B88F7BD30C; - productRefGroup = 82487862487832CCB0A8662A9AF1E6F4 /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - 9B2D563D3B39C8B41B45CEC35AFF91AB /* Pods-TestClientApp */, - 2D75029181FED2A76CE4D7E9C7324E1A /* Pods-TestClientAppTests */, - B72EF653ED86BEBAF8987EA7602289AA /* TestClient */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXResourcesBuildPhase section */ - 03481D112E7D051F903DE8784BF22687 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 249B61D9BD8682D922DADE95CF024037 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 2BE7CABBA55E1D7FEFDEE56BE2272511 /* Resources */ = { - isa = PBXResourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXResourcesBuildPhase section */ - -/* Begin PBXSourcesBuildPhase section */ - 30376D28819EB4222324B1599818AA2E /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 268A90C42CD895FDF00F71736B67DEE9 /* Pods-TestClientApp-dummy.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - 891FDC0ECDDDC0341FD69A8163332A57 /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - C07F9AA95A46282A1D273A214786D5FB /* AllPrimitives.swift in Sources */, - 46F6C1F49012FFD9B45EDDB8C6F9DEE8 /* APIHelper.swift in Sources */, - 23C7A6763A7E2DFD10B081432E36AB01 /* APIs.swift in Sources */, - F3BF0BB9E24D6FA4514D39E0900E9092 /* BaseCard.swift in Sources */, - 7357B46081E64E0AE6ECAD986CA5DD6A /* CodableHelper.swift in Sources */, - 9AF02BB5E3C4D96BF5E6FC80237AA940 /* Configuration.swift in Sources */, - 59B3866FA296D6B33751F37409FFEC57 /* ErrorInfo.swift in Sources */, - 26966BEE6C13D2513B7AFFAD84F57AFF /* Extensions.swift in Sources */, - A99CABE1AF2E62510C9288326F245BD8 /* GetAllModelsResult.swift in Sources */, - 6DA3FAE017CD3551A3E2AA7BA913D351 /* JSONDataEncoding.swift in Sources */, - D73D105F4B969E14B6BF95A954EAB4B9 /* JSONEncodingHelper.swift in Sources */, - 095D99ED77DB34E158D6487D64C577FB /* ModelDoubleArray.swift in Sources */, - 3F82E278BBF49865698F48C2BDD3A8C8 /* ModelErrorInfoArray.swift in Sources */, - 4EC1AA6BB0AD6DDE9689926005084DFB /* Models.swift in Sources */, - B33500DB9D0190B3A8592E43E12A6866 /* ModelStringArray.swift in Sources */, - 279D52D2BBF4F9F41806CB559BBCC323 /* ModelWithIntAdditionalPropertiesOnly.swift in Sources */, - FBFF8FA7141150DE0DDB3996C07017EF /* ModelWithPropertiesAndAdditionalProperties.swift in Sources */, - AD0D89AAFA166B9B38C1F838C00C636D /* ModelWithStringAdditionalPropertiesOnly.swift in Sources */, - C872EC896D31C3BD2C655456D24AEC79 /* OpenISO8601DateFormatter.swift in Sources */, - 87C3C30946F53347EDA3F9060C63F8D7 /* PersonCard.swift in Sources */, - DB43CC6E8B07E962C68B1E61347FB2AB /* PersonCardAllOf.swift in Sources */, - 02FFBA90EA5EADA19A336739D6DCCEB0 /* PlaceCard.swift in Sources */, - 438C479E9FDDCDD436CA20CB1D2523E9 /* PlaceCardAllOf.swift in Sources */, - D61D04428EA4D5471DF5C44394840076 /* SampleBase.swift in Sources */, - 5F369A3A957334C7121219B52C9D65AA /* SampleSubClass.swift in Sources */, - 9FF109F83DB17F92E6076CB9E90596E9 /* SampleSubClassAllOf.swift in Sources */, - 8429C4D45B15BBDDD2798A7CD92A8F43 /* StringEnum.swift in Sources */, - D82F0987580977B789D60461C5CD2354 /* Swift5TestAPI.swift in Sources */, - D8ABC53F70A4A3DD12BB92195A4F5EA2 /* SynchronizedDictionary.swift in Sources */, - 73D33A91FD9B2D8B5535B1A21680A1EE /* TestClient-dummy.m in Sources */, - 479A7BE76F5560BBE0042A2F6E43CBB0 /* URLSessionImplementations.swift in Sources */, - A5EAA2E7E946EB46ADBE60E63142C7DC /* VariableNameTest.swift in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; - FEBEDF2CD3F3F14C05232EC28A5EF48C /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - 4435680E8AEC40C0D41102941C65F54E /* Pods-TestClientAppTests-dummy.m in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin PBXTargetDependency section */ - B6CB5A55B80757512913E8C17BE67BA1 /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = TestClient; - target = B72EF653ED86BEBAF8987EA7602289AA /* TestClient */; - targetProxy = 8788B4EA1EE8B4ABC69B264C82484356 /* PBXContainerItemProxy */; - }; - EC9E65DA36BCE418EF8ACAEA50766BBA /* PBXTargetDependency */ = { - isa = PBXTargetDependency; - name = "Pods-TestClientApp"; - target = 9B2D563D3B39C8B41B45CEC35AFF91AB /* Pods-TestClientApp */; - targetProxy = D46C3A7D874BD540F75F8C8EE656DAA2 /* PBXContainerItemProxy */; - }; -/* End PBXTargetDependency section */ - -/* Begin XCBuildConfiguration section */ - 26821E448371EE4D3CACAB666C0DD54C /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = B1D5F61FD93DB03C60173A799F6B967D /* Pods-TestClientApp.release.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-TestClientApp/Pods-TestClientApp-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestClientApp/Pods-TestClientApp.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 314DD2576941BC5109AABA2E6BD37A27 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 7E7CB11C6E8EF71424C6D3725EE67DE8 /* Pods-TestClientAppTests.debug.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 6B10B4960C2B7D01BF4E0B482EAE4FF3 /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 892BF895C1CF4CDD225A15EE546704C0 /* TestClient.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/TestClient/TestClient-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/TestClient/TestClient-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/TestClient/TestClient.modulemap"; - PRODUCT_MODULE_NAME = TestClient; - PRODUCT_NAME = TestClient; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 4.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - 8F17DC3A99F99FBAD606CE6963886315 /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - ENABLE_STRICT_OBJC_MSGSEND = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_NO_COMMON_BLOCKS = YES; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_RELEASE=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - MTL_ENABLE_DEBUG_INFO = NO; - MTL_FAST_MATH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_COMPILATION_MODE = wholemodule; - SWIFT_OPTIMIZATION_LEVEL = "-O"; - SWIFT_VERSION = 5.0; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Release; - }; - 916E0404255105F480DC4950B7625F7A /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_ANALYZER_NONNULL = YES; - CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_MODULES = YES; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_ENABLE_OBJC_WEAK = YES; - CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_COMMA = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_DOCUMENTATION_COMMENTS = YES; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INFINITE_RECURSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; - CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; - CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; - CLANG_WARN_STRICT_PROTOTYPES = YES; - CLANG_WARN_SUSPICIOUS_MOVE = YES; - CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; - CLANG_WARN_UNREACHABLE_CODE = YES; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - DEBUG_INFORMATION_FORMAT = dwarf; - ENABLE_STRICT_OBJC_MSGSEND = YES; - ENABLE_TESTABILITY = YES; - GCC_C_LANGUAGE_STANDARD = gnu11; - GCC_DYNAMIC_NO_PIC = NO; - GCC_NO_COMMON_BLOCKS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "POD_CONFIGURATION_DEBUG=1", - "DEBUG=1", - "$(inherited)", - ); - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; - MTL_FAST_MATH = YES; - ONLY_ACTIVE_ARCH = YES; - PRODUCT_NAME = "$(TARGET_NAME)"; - STRIP_INSTALLED_PRODUCT = NO; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; - SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 5.0; - SYMROOT = "${SRCROOT}/../build"; - }; - name = Debug; - }; - 926D375A4143EDE2E3E666DCD5E26F99 /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 892BF895C1CF4CDD225A15EE546704C0 /* TestClient.xcconfig */; - buildSettings = { - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - GCC_PREFIX_HEADER = "Target Support Files/TestClient/TestClient-prefix.pch"; - INFOPLIST_FILE = "Target Support Files/TestClient/TestClient-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MODULEMAP_FILE = "Target Support Files/TestClient/TestClient.modulemap"; - PRODUCT_MODULE_NAME = TestClient; - PRODUCT_NAME = TestClient; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; - SWIFT_VERSION = 4.0; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; - 9E4BD420AF2B260F58836E81540845FA /* Debug */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 82FD0B66B6128354B30FB2FF3088F3A4 /* Pods-TestClientApp.debug.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-TestClientApp/Pods-TestClientApp-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestClientApp/Pods-TestClientApp.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Debug; - }; - C8ED66A74D418771F0B335943A7704DC /* Release */ = { - isa = XCBuildConfiguration; - baseConfigurationReference = 48C4EB9FB0827F886ABA8B7EBE8EEA8E /* Pods-TestClientAppTests.release.xcconfig */; - buildSettings = { - ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; - CODE_SIGN_IDENTITY = ""; - "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; - "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; - CURRENT_PROJECT_VERSION = 1; - DEFINES_MODULE = YES; - DYLIB_COMPATIBILITY_VERSION = 1; - DYLIB_CURRENT_VERSION = 1; - DYLIB_INSTALL_NAME_BASE = "@rpath"; - INFOPLIST_FILE = "Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-Info.plist"; - INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; - IPHONEOS_DEPLOYMENT_TARGET = 9.0; - LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; - MACH_O_TYPE = staticlib; - MODULEMAP_FILE = "Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.modulemap"; - OTHER_LDFLAGS = ""; - OTHER_LIBTOOLFLAGS = ""; - PODS_ROOT = "$(SRCROOT)"; - PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; - PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; - SDKROOT = iphoneos; - SKIP_INSTALL = YES; - TARGETED_DEVICE_FAMILY = "1,2"; - VALIDATE_PRODUCT = YES; - VERSIONING_SYSTEM = "apple-generic"; - VERSION_INFO_PREFIX = ""; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - 45A0725886CC4152E1A7A7895FD616FE /* Build configuration list for PBXNativeTarget "TestClient" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 6B10B4960C2B7D01BF4E0B482EAE4FF3 /* Debug */, - 926D375A4143EDE2E3E666DCD5E26F99 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 916E0404255105F480DC4950B7625F7A /* Debug */, - 8F17DC3A99F99FBAD606CE6963886315 /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - D8CA9B2C39BEDB78745943095DB0F76A /* Build configuration list for PBXNativeTarget "Pods-TestClientApp" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 9E4BD420AF2B260F58836E81540845FA /* Debug */, - 26821E448371EE4D3CACAB666C0DD54C /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - F5DCF5CCC2DD022C81242D669FBA2A53 /* Build configuration list for PBXNativeTarget "Pods-TestClientAppTests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - 314DD2576941BC5109AABA2E6BD37A27 /* Debug */, - C8ED66A74D418771F0B335943A7704DC /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; -} diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-Info.plist b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-Info.plist deleted file mode 100644 index 2243fe6e27dc..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.markdown b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.markdown deleted file mode 100644 index 102af7538517..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.markdown +++ /dev/null @@ -1,3 +0,0 @@ -# Acknowledgements -This application makes use of the following third party libraries: -Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.plist b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.plist deleted file mode 100644 index 7acbad1eabbf..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-acknowledgements.plist +++ /dev/null @@ -1,29 +0,0 @@ - - - - - PreferenceSpecifiers - - - FooterText - This application makes use of the following third party libraries: - Title - Acknowledgements - Type - PSGroupSpecifier - - - FooterText - Generated by CocoaPods - https://cocoapods.org - Title - - Type - PSGroupSpecifier - - - StringsTable - Acknowledgements - Title - Acknowledgements - - diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-dummy.m b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-dummy.m deleted file mode 100644 index 7403e9c5dead..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods_TestClientApp : NSObject -@end -@implementation PodsDummy_Pods_TestClientApp -@end diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-frameworks.sh b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-frameworks.sh deleted file mode 100755 index c56fc03c6b66..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-frameworks.sh +++ /dev/null @@ -1,171 +0,0 @@ -#!/bin/sh -set -e -set -u -set -o pipefail - -function on_error { - echo "$(realpath -mq "${0}"):$1: error: Unexpected failure" -} -trap 'on_error $LINENO' ERR - -if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then - # If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy - # frameworks to, so exit 0 (signalling the script phase was successful). - exit 0 -fi - -echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" -mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - -COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}" -SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}" - -# Used as a return value for each invocation of `strip_invalid_archs` function. -STRIP_BINARY_RETVAL=0 - -# This protects against multiple targets copying the same framework dependency at the same time. The solution -# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html -RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????") - -# Copies and strips a vendored framework -install_framework() -{ - if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then - local source="${BUILT_PRODUCTS_DIR}/$1" - elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then - local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")" - elif [ -r "$1" ]; then - local source="$1" - fi - - local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - - if [ -L "${source}" ]; then - echo "Symlinked..." - source="$(readlink "${source}")" - fi - - # Use filter instead of exclude so missing patterns don't throw errors. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}" - - local basename - basename="$(basename -s .framework "$1")" - binary="${destination}/${basename}.framework/${basename}" - - if ! [ -r "$binary" ]; then - binary="${destination}/${basename}" - elif [ -L "${binary}" ]; then - echo "Destination binary is symlinked..." - dirname="$(dirname "${binary}")" - binary="${dirname}/$(readlink "${binary}")" - fi - - # Strip invalid architectures so "fat" simulator / device frameworks work on device - if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then - strip_invalid_archs "$binary" - fi - - # Resign the code if required by the build settings to avoid unstable apps - code_sign_if_enabled "${destination}/$(basename "$1")" - - # Embed linked Swift runtime libraries. No longer necessary as of Xcode 7. - if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then - local swift_runtime_libs - swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u) - for lib in $swift_runtime_libs; do - echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\"" - rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}" - code_sign_if_enabled "${destination}/${lib}" - done - fi -} - -# Copies and strips a vendored dSYM -install_dsym() { - local source="$1" - if [ -r "$source" ]; then - # Copy the dSYM into a the targets temp dir. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}" - - local basename - basename="$(basename -s .framework.dSYM "$source")" - binary="${DERIVED_FILES_DIR}/${basename}.framework.dSYM/Contents/Resources/DWARF/${basename}" - - # Strip invalid architectures so "fat" simulator / device frameworks work on device - if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then - strip_invalid_archs "$binary" - fi - - if [[ $STRIP_BINARY_RETVAL == 1 ]]; then - # Move the stripped file into its final destination. - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.framework.dSYM" "${DWARF_DSYM_FOLDER_PATH}" - else - # The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing. - touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.framework.dSYM" - fi - fi -} - -# Copies the bcsymbolmap files of a vendored framework -install_bcsymbolmap() { - local bcsymbolmap_path="$1" - local destination="${BUILT_PRODUCTS_DIR}" - echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"" - rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}" -} - -# Signs a framework with the provided identity -code_sign_if_enabled() { - if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then - # Use the current code_sign_identity - echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}" - local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'" - - if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then - code_sign_cmd="$code_sign_cmd &" - fi - echo "$code_sign_cmd" - eval "$code_sign_cmd" - fi -} - -# Strip invalid architectures -strip_invalid_archs() { - binary="$1" - # Get architectures for current target binary - binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)" - # Intersect them with the architectures we are building for - intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)" - # If there are no archs supported by this binary then warn the user - if [[ -z "$intersected_archs" ]]; then - echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)." - STRIP_BINARY_RETVAL=0 - return - fi - stripped="" - for arch in $binary_archs; do - if ! [[ "${ARCHS}" == *"$arch"* ]]; then - # Strip non-valid architectures in-place - lipo -remove "$arch" -output "$binary" "$binary" - stripped="$stripped $arch" - fi - done - if [[ "$stripped" ]]; then - echo "Stripped $binary of architectures:$stripped" - fi - STRIP_BINARY_RETVAL=1 -} - - -if [[ "$CONFIGURATION" == "Debug" ]]; then - install_framework "${BUILT_PRODUCTS_DIR}/TestClient/TestClient.framework" -fi -if [[ "$CONFIGURATION" == "Release" ]]; then - install_framework "${BUILT_PRODUCTS_DIR}/TestClient/TestClient.framework" -fi -if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then - wait -fi diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-umbrella.h b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-umbrella.h deleted file mode 100644 index 1004f0f70412..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double Pods_TestClientAppVersionNumber; -FOUNDATION_EXPORT const unsigned char Pods_TestClientAppVersionString[]; - diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.debug.xcconfig b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.debug.xcconfig deleted file mode 100644 index e5573a7781b6..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.debug.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/TestClient" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/TestClient/TestClient.framework/Headers" -LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "TestClient" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.modulemap b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.modulemap deleted file mode 100644 index 6f2c78be7491..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Pods_TestClientApp { - umbrella header "Pods-TestClientApp-umbrella.h" - - export * - module * { export * } -} diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.release.xcconfig b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.release.xcconfig deleted file mode 100644 index e5573a7781b6..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientApp/Pods-TestClientApp.release.xcconfig +++ /dev/null @@ -1,12 +0,0 @@ -ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/TestClient" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/TestClient/TestClient.framework/Headers" -LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks' -OTHER_LDFLAGS = $(inherited) -framework "TestClient" -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-Info.plist b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-Info.plist deleted file mode 100644 index 2243fe6e27dc..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.markdown b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.markdown deleted file mode 100644 index 102af7538517..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.markdown +++ /dev/null @@ -1,3 +0,0 @@ -# Acknowledgements -This application makes use of the following third party libraries: -Generated by CocoaPods - https://cocoapods.org diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.plist b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.plist deleted file mode 100644 index 7acbad1eabbf..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-acknowledgements.plist +++ /dev/null @@ -1,29 +0,0 @@ - - - - - PreferenceSpecifiers - - - FooterText - This application makes use of the following third party libraries: - Title - Acknowledgements - Type - PSGroupSpecifier - - - FooterText - Generated by CocoaPods - https://cocoapods.org - Title - - Type - PSGroupSpecifier - - - StringsTable - Acknowledgements - Title - Acknowledgements - - diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-dummy.m b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-dummy.m deleted file mode 100644 index 391cf05865f7..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods_TestClientAppTests : NSObject -@end -@implementation PodsDummy_Pods_TestClientAppTests -@end diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-umbrella.h b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-umbrella.h deleted file mode 100644 index f3c84c4c89dc..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double Pods_TestClientAppTestsVersionNumber; -FOUNDATION_EXPORT const unsigned char Pods_TestClientAppTestsVersionString[]; - diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.debug.xcconfig b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.debug.xcconfig deleted file mode 100644 index 1e9d8f110ed9..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.debug.xcconfig +++ /dev/null @@ -1,9 +0,0 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/TestClient" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/TestClient/TestClient.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "TestClient" -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.modulemap b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.modulemap deleted file mode 100644 index a763c71493f7..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module Pods_TestClientAppTests { - umbrella header "Pods-TestClientAppTests-umbrella.h" - - export * - module * { export * } -} diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.release.xcconfig b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.release.xcconfig deleted file mode 100644 index 1e9d8f110ed9..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/Pods-TestClientAppTests/Pods-TestClientAppTests.release.xcconfig +++ /dev/null @@ -1,9 +0,0 @@ -FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/TestClient" -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/TestClient/TestClient.framework/Headers" -OTHER_LDFLAGS = $(inherited) -framework "TestClient" -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_PODFILE_DIR_PATH = ${SRCROOT}/. -PODS_ROOT = ${SRCROOT}/Pods -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-Info.plist b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-Info.plist deleted file mode 100644 index 2243fe6e27dc..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-Info.plist +++ /dev/null @@ -1,26 +0,0 @@ - - - - - CFBundleDevelopmentRegion - en - CFBundleExecutable - ${EXECUTABLE_NAME} - CFBundleIdentifier - ${PRODUCT_BUNDLE_IDENTIFIER} - CFBundleInfoDictionaryVersion - 6.0 - CFBundleName - ${PRODUCT_NAME} - CFBundlePackageType - FMWK - CFBundleShortVersionString - 1.0.0 - CFBundleSignature - ???? - CFBundleVersion - ${CURRENT_PROJECT_VERSION} - NSPrincipalClass - - - diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-dummy.m b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-dummy.m deleted file mode 100644 index e9a709a985a2..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_TestClient : NSObject -@end -@implementation PodsDummy_TestClient -@end diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-prefix.pch b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-prefix.pch deleted file mode 100644 index beb2a2441835..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-prefix.pch +++ /dev/null @@ -1,12 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-umbrella.h b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-umbrella.h deleted file mode 100644 index 57d4c595bc87..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient-umbrella.h +++ /dev/null @@ -1,16 +0,0 @@ -#ifdef __OBJC__ -#import -#else -#ifndef FOUNDATION_EXPORT -#if defined(__cplusplus) -#define FOUNDATION_EXPORT extern "C" -#else -#define FOUNDATION_EXPORT extern -#endif -#endif -#endif - - -FOUNDATION_EXPORT double TestClientVersionNumber; -FOUNDATION_EXPORT const unsigned char TestClientVersionString[]; - diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.modulemap b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.modulemap deleted file mode 100644 index 645349a23a1c..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.modulemap +++ /dev/null @@ -1,6 +0,0 @@ -framework module TestClient { - umbrella header "TestClient-umbrella.h" - - export * - module * { export * } -} diff --git a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.xcconfig b/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.xcconfig deleted file mode 100644 index 13f3de102253..000000000000 --- a/samples/client/test/swift5/default/TestClientApp/Pods/Target Support Files/TestClient/TestClient.xcconfig +++ /dev/null @@ -1,10 +0,0 @@ -CONFIGURATION_BUILD_DIR = ${PODS_CONFIGURATION_BUILD_DIR}/TestClient -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -OTHER_SWIFT_FLAGS = $(inherited) -D COCOAPODS -PODS_BUILD_DIR = ${BUILD_DIR} -PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) -PODS_ROOT = ${SRCROOT} -PODS_TARGET_SRCROOT = ${PODS_ROOT}/../.. -PRODUCT_BUNDLE_IDENTIFIER = org.cocoapods.${PRODUCT_NAME:rfc1034identifier} -SKIP_INSTALL = YES -USE_RECURSIVE_SCRIPT_INPUTS_IN_SCRIPT_PHASES = YES diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/README.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/README.md index a7fa78304046..1467a6316fc8 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/README.md +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/README.md @@ -117,9 +117,13 @@ Class | Method | HTTP request | Description - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [Animal](docs/Animal.md) - [ApiResponse](docs/ApiResponse.md) + - [Apple](docs/Apple.md) + - [AppleReq](docs/AppleReq.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [ArrayTest](docs/ArrayTest.md) + - [Banana](docs/Banana.md) + - [BananaReq](docs/BananaReq.md) - [Capitalization](docs/Capitalization.md) - [Cat](docs/Cat.md) - [CatAllOf](docs/CatAllOf.md) @@ -135,6 +139,9 @@ Class | Method | HTTP request | Description - [FileSchemaTestClass](docs/FileSchemaTestClass.md) - [Foo](docs/Foo.md) - [FormatTest](docs/FormatTest.md) + - [Fruit](docs/Fruit.md) + - [FruitReq](docs/FruitReq.md) + - [GmFruit](docs/GmFruit.md) - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - [HealthCheckResult](docs/HealthCheckResult.md) - [InlineObject](docs/InlineObject.md) @@ -145,6 +152,7 @@ Class | Method | HTTP request | Description - [InlineObject5](docs/InlineObject5.md) - [InlineResponseDefault](docs/InlineResponseDefault.md) - [List](docs/List.md) + - [Mammal](docs/Mammal.md) - [MapTest](docs/MapTest.md) - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) @@ -163,6 +171,8 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [Tag](docs/Tag.md) - [User](docs/User.md) + - [Whale](docs/Whale.md) + - [Zebra](docs/Zebra.md) ## Documentation For Authorization diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api/openapi.yaml b/samples/openapi3/client/petstore/go-experimental/go-petstore/api/openapi.yaml index b141d4d19b76..f27d7ff9c2d6 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api/openapi.yaml +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api/openapi.yaml @@ -1892,6 +1892,88 @@ components: type: object type: object type: object + fruit: + oneOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + properties: + color: + type: string + x-oneOf-name: Fruit + apple: + properties: + cultivar: + type: string + type: object + banana: + properties: + lengthCm: + type: number + type: object + mammal: + discriminator: + mapping: + whale: '#/components/schemas/whale' + zebra: '#/components/schemas/zebra' + propertyName: className + oneOf: + - $ref: '#/components/schemas/whale' + - $ref: '#/components/schemas/zebra' + x-oneOf-name: Mammal + whale: + properties: + hasBaleen: + type: boolean + hasTeeth: + type: boolean + className: + type: string + required: + - className + type: object + zebra: + properties: + type: + enum: + - plains + - mountain + - grevys + type: string + className: + type: string + required: + - className + type: object + gmFruit: + anyOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + properties: + color: + type: string + fruitReq: + oneOf: + - $ref: '#/components/schemas/appleReq' + - $ref: '#/components/schemas/bananaReq' + x-oneOf-name: FruitReq + appleReq: + properties: + cultivar: + type: string + mealy: + type: boolean + required: + - cultivar + type: object + bananaReq: + properties: + lengthCm: + type: number + sweet: + type: boolean + required: + - lengthCm + type: object inline_response_default: example: string: diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Apple.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Apple.md new file mode 100644 index 000000000000..6f0a8ad62b71 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Apple.md @@ -0,0 +1,88 @@ +# Apple + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Cultivar** | Pointer to **string** | | [optional] +**Color** | Pointer to **string** | | [optional] + +## Methods + +### NewApple + +`func NewApple() *Apple` + +NewApple instantiates a new Apple object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewAppleWithDefaults + +`func NewAppleWithDefaults() *Apple` + +NewAppleWithDefaults instantiates a new Apple object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetCultivar + +`func (o *Apple) GetCultivar() string` + +GetCultivar returns the Cultivar field if non-nil, zero value otherwise. + +### GetCultivarOk + +`func (o *Apple) GetCultivarOk() (string, bool)` + +GetCultivarOk returns a tuple with the Cultivar field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasCultivar + +`func (o *Apple) HasCultivar() bool` + +HasCultivar returns a boolean if a field has been set. + +### SetCultivar + +`func (o *Apple) SetCultivar(v string)` + +SetCultivar gets a reference to the given string and assigns it to the Cultivar field. + +### GetColor + +`func (o *Apple) GetColor() string` + +GetColor returns the Color field if non-nil, zero value otherwise. + +### GetColorOk + +`func (o *Apple) GetColorOk() (string, bool)` + +GetColorOk returns a tuple with the Color field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasColor + +`func (o *Apple) HasColor() bool` + +HasColor returns a boolean if a field has been set. + +### SetColor + +`func (o *Apple) SetColor(v string)` + +SetColor gets a reference to the given string and assigns it to the Color field. + + +### AsFruit + +`func (s *Apple) AsFruit() Fruit` + +Convenience method to wrap this instance of Apple in Fruit + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/AppleReq.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/AppleReq.md new file mode 100644 index 000000000000..53e41afbd080 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/AppleReq.md @@ -0,0 +1,88 @@ +# AppleReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Cultivar** | Pointer to **string** | | +**Mealy** | Pointer to **bool** | | [optional] + +## Methods + +### NewAppleReq + +`func NewAppleReq(cultivar string, ) *AppleReq` + +NewAppleReq instantiates a new AppleReq object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewAppleReqWithDefaults + +`func NewAppleReqWithDefaults() *AppleReq` + +NewAppleReqWithDefaults instantiates a new AppleReq object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetCultivar + +`func (o *AppleReq) GetCultivar() string` + +GetCultivar returns the Cultivar field if non-nil, zero value otherwise. + +### GetCultivarOk + +`func (o *AppleReq) GetCultivarOk() (string, bool)` + +GetCultivarOk returns a tuple with the Cultivar field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasCultivar + +`func (o *AppleReq) HasCultivar() bool` + +HasCultivar returns a boolean if a field has been set. + +### SetCultivar + +`func (o *AppleReq) SetCultivar(v string)` + +SetCultivar gets a reference to the given string and assigns it to the Cultivar field. + +### GetMealy + +`func (o *AppleReq) GetMealy() bool` + +GetMealy returns the Mealy field if non-nil, zero value otherwise. + +### GetMealyOk + +`func (o *AppleReq) GetMealyOk() (bool, bool)` + +GetMealyOk returns a tuple with the Mealy field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasMealy + +`func (o *AppleReq) HasMealy() bool` + +HasMealy returns a boolean if a field has been set. + +### SetMealy + +`func (o *AppleReq) SetMealy(v bool)` + +SetMealy gets a reference to the given bool and assigns it to the Mealy field. + + +### AsFruitReq + +`func (s *AppleReq) AsFruitReq() FruitReq` + +Convenience method to wrap this instance of AppleReq in FruitReq + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Banana.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Banana.md new file mode 100644 index 000000000000..a20d3abbfd6e --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Banana.md @@ -0,0 +1,88 @@ +# Banana + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**LengthCm** | Pointer to **float32** | | [optional] +**Color** | Pointer to **string** | | [optional] + +## Methods + +### NewBanana + +`func NewBanana() *Banana` + +NewBanana instantiates a new Banana object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewBananaWithDefaults + +`func NewBananaWithDefaults() *Banana` + +NewBananaWithDefaults instantiates a new Banana object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetLengthCm + +`func (o *Banana) GetLengthCm() float32` + +GetLengthCm returns the LengthCm field if non-nil, zero value otherwise. + +### GetLengthCmOk + +`func (o *Banana) GetLengthCmOk() (float32, bool)` + +GetLengthCmOk returns a tuple with the LengthCm field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasLengthCm + +`func (o *Banana) HasLengthCm() bool` + +HasLengthCm returns a boolean if a field has been set. + +### SetLengthCm + +`func (o *Banana) SetLengthCm(v float32)` + +SetLengthCm gets a reference to the given float32 and assigns it to the LengthCm field. + +### GetColor + +`func (o *Banana) GetColor() string` + +GetColor returns the Color field if non-nil, zero value otherwise. + +### GetColorOk + +`func (o *Banana) GetColorOk() (string, bool)` + +GetColorOk returns a tuple with the Color field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasColor + +`func (o *Banana) HasColor() bool` + +HasColor returns a boolean if a field has been set. + +### SetColor + +`func (o *Banana) SetColor(v string)` + +SetColor gets a reference to the given string and assigns it to the Color field. + + +### AsFruit + +`func (s *Banana) AsFruit() Fruit` + +Convenience method to wrap this instance of Banana in Fruit + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/BananaReq.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/BananaReq.md new file mode 100644 index 000000000000..e9ffa23a1142 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/BananaReq.md @@ -0,0 +1,88 @@ +# BananaReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**LengthCm** | Pointer to **float32** | | +**Sweet** | Pointer to **bool** | | [optional] + +## Methods + +### NewBananaReq + +`func NewBananaReq(lengthCm float32, ) *BananaReq` + +NewBananaReq instantiates a new BananaReq object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewBananaReqWithDefaults + +`func NewBananaReqWithDefaults() *BananaReq` + +NewBananaReqWithDefaults instantiates a new BananaReq object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetLengthCm + +`func (o *BananaReq) GetLengthCm() float32` + +GetLengthCm returns the LengthCm field if non-nil, zero value otherwise. + +### GetLengthCmOk + +`func (o *BananaReq) GetLengthCmOk() (float32, bool)` + +GetLengthCmOk returns a tuple with the LengthCm field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasLengthCm + +`func (o *BananaReq) HasLengthCm() bool` + +HasLengthCm returns a boolean if a field has been set. + +### SetLengthCm + +`func (o *BananaReq) SetLengthCm(v float32)` + +SetLengthCm gets a reference to the given float32 and assigns it to the LengthCm field. + +### GetSweet + +`func (o *BananaReq) GetSweet() bool` + +GetSweet returns the Sweet field if non-nil, zero value otherwise. + +### GetSweetOk + +`func (o *BananaReq) GetSweetOk() (bool, bool)` + +GetSweetOk returns a tuple with the Sweet field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasSweet + +`func (o *BananaReq) HasSweet() bool` + +HasSweet returns a boolean if a field has been set. + +### SetSweet + +`func (o *BananaReq) SetSweet(v bool)` + +SetSweet gets a reference to the given bool and assigns it to the Sweet field. + + +### AsFruitReq + +`func (s *BananaReq) AsFruitReq() FruitReq` + +Convenience method to wrap this instance of BananaReq in FruitReq + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Fruit.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Fruit.md new file mode 100644 index 000000000000..fa033d3ef6f0 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Fruit.md @@ -0,0 +1,14 @@ +# Fruit + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**FruitInterface** | **interface { }** | An interface that can hold any of the proper implementing types | + +## Methods + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/FruitReq.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/FruitReq.md new file mode 100644 index 000000000000..c22de7800645 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/FruitReq.md @@ -0,0 +1,14 @@ +# FruitReq + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**FruitReqInterface** | **interface { }** | An interface that can hold any of the proper implementing types | + +## Methods + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/GmFruit.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/GmFruit.md new file mode 100644 index 000000000000..fc71d4e30ec5 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/GmFruit.md @@ -0,0 +1,108 @@ +# GmFruit + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Color** | Pointer to **string** | | [optional] +**Cultivar** | Pointer to **string** | | [optional] +**LengthCm** | Pointer to **float32** | | [optional] + +## Methods + +### NewGmFruit + +`func NewGmFruit() *GmFruit` + +NewGmFruit instantiates a new GmFruit object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewGmFruitWithDefaults + +`func NewGmFruitWithDefaults() *GmFruit` + +NewGmFruitWithDefaults instantiates a new GmFruit object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetColor + +`func (o *GmFruit) GetColor() string` + +GetColor returns the Color field if non-nil, zero value otherwise. + +### GetColorOk + +`func (o *GmFruit) GetColorOk() (string, bool)` + +GetColorOk returns a tuple with the Color field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasColor + +`func (o *GmFruit) HasColor() bool` + +HasColor returns a boolean if a field has been set. + +### SetColor + +`func (o *GmFruit) SetColor(v string)` + +SetColor gets a reference to the given string and assigns it to the Color field. + +### GetCultivar + +`func (o *GmFruit) GetCultivar() string` + +GetCultivar returns the Cultivar field if non-nil, zero value otherwise. + +### GetCultivarOk + +`func (o *GmFruit) GetCultivarOk() (string, bool)` + +GetCultivarOk returns a tuple with the Cultivar field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasCultivar + +`func (o *GmFruit) HasCultivar() bool` + +HasCultivar returns a boolean if a field has been set. + +### SetCultivar + +`func (o *GmFruit) SetCultivar(v string)` + +SetCultivar gets a reference to the given string and assigns it to the Cultivar field. + +### GetLengthCm + +`func (o *GmFruit) GetLengthCm() float32` + +GetLengthCm returns the LengthCm field if non-nil, zero value otherwise. + +### GetLengthCmOk + +`func (o *GmFruit) GetLengthCmOk() (float32, bool)` + +GetLengthCmOk returns a tuple with the LengthCm field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasLengthCm + +`func (o *GmFruit) HasLengthCm() bool` + +HasLengthCm returns a boolean if a field has been set. + +### SetLengthCm + +`func (o *GmFruit) SetLengthCm(v float32)` + +SetLengthCm gets a reference to the given float32 and assigns it to the LengthCm field. + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Mammal.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Mammal.md new file mode 100644 index 000000000000..7d3dfe04b15f --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Mammal.md @@ -0,0 +1,14 @@ +# Mammal + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**MammalInterface** | **interface { GetClassName() string }** | An interface that can hold any of the proper implementing types | + +## Methods + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Whale.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Whale.md new file mode 100644 index 000000000000..301b91e4fd0c --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Whale.md @@ -0,0 +1,114 @@ +# Whale + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**HasBaleen** | Pointer to **bool** | | [optional] +**HasTeeth** | Pointer to **bool** | | [optional] +**ClassName** | Pointer to **string** | | + +## Methods + +### NewWhale + +`func NewWhale(className string, ) *Whale` + +NewWhale instantiates a new Whale object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewWhaleWithDefaults + +`func NewWhaleWithDefaults() *Whale` + +NewWhaleWithDefaults instantiates a new Whale object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetHasBaleen + +`func (o *Whale) GetHasBaleen() bool` + +GetHasBaleen returns the HasBaleen field if non-nil, zero value otherwise. + +### GetHasBaleenOk + +`func (o *Whale) GetHasBaleenOk() (bool, bool)` + +GetHasBaleenOk returns a tuple with the HasBaleen field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasHasBaleen + +`func (o *Whale) HasHasBaleen() bool` + +HasHasBaleen returns a boolean if a field has been set. + +### SetHasBaleen + +`func (o *Whale) SetHasBaleen(v bool)` + +SetHasBaleen gets a reference to the given bool and assigns it to the HasBaleen field. + +### GetHasTeeth + +`func (o *Whale) GetHasTeeth() bool` + +GetHasTeeth returns the HasTeeth field if non-nil, zero value otherwise. + +### GetHasTeethOk + +`func (o *Whale) GetHasTeethOk() (bool, bool)` + +GetHasTeethOk returns a tuple with the HasTeeth field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasHasTeeth + +`func (o *Whale) HasHasTeeth() bool` + +HasHasTeeth returns a boolean if a field has been set. + +### SetHasTeeth + +`func (o *Whale) SetHasTeeth(v bool)` + +SetHasTeeth gets a reference to the given bool and assigns it to the HasTeeth field. + +### GetClassName + +`func (o *Whale) GetClassName() string` + +GetClassName returns the ClassName field if non-nil, zero value otherwise. + +### GetClassNameOk + +`func (o *Whale) GetClassNameOk() (string, bool)` + +GetClassNameOk returns a tuple with the ClassName field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasClassName + +`func (o *Whale) HasClassName() bool` + +HasClassName returns a boolean if a field has been set. + +### SetClassName + +`func (o *Whale) SetClassName(v string)` + +SetClassName gets a reference to the given string and assigns it to the ClassName field. + + +### AsMammal + +`func (s *Whale) AsMammal() Mammal` + +Convenience method to wrap this instance of Whale in Mammal + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Zebra.md b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Zebra.md new file mode 100644 index 000000000000..18147cffdf26 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/docs/Zebra.md @@ -0,0 +1,88 @@ +# Zebra + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Type** | Pointer to **string** | | [optional] +**ClassName** | Pointer to **string** | | + +## Methods + +### NewZebra + +`func NewZebra(className string, ) *Zebra` + +NewZebra instantiates a new Zebra object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewZebraWithDefaults + +`func NewZebraWithDefaults() *Zebra` + +NewZebraWithDefaults instantiates a new Zebra object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetType + +`func (o *Zebra) GetType() string` + +GetType returns the Type field if non-nil, zero value otherwise. + +### GetTypeOk + +`func (o *Zebra) GetTypeOk() (string, bool)` + +GetTypeOk returns a tuple with the Type field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasType + +`func (o *Zebra) HasType() bool` + +HasType returns a boolean if a field has been set. + +### SetType + +`func (o *Zebra) SetType(v string)` + +SetType gets a reference to the given string and assigns it to the Type field. + +### GetClassName + +`func (o *Zebra) GetClassName() string` + +GetClassName returns the ClassName field if non-nil, zero value otherwise. + +### GetClassNameOk + +`func (o *Zebra) GetClassNameOk() (string, bool)` + +GetClassNameOk returns a tuple with the ClassName field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### HasClassName + +`func (o *Zebra) HasClassName() bool` + +HasClassName returns a boolean if a field has been set. + +### SetClassName + +`func (o *Zebra) SetClassName(v string)` + +SetClassName gets a reference to the given string and assigns it to the ClassName field. + + +### AsMammal + +`func (s *Zebra) AsMammal() Mammal` + +Convenience method to wrap this instance of Zebra in Mammal + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_apple.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_apple.go new file mode 100644 index 000000000000..91603b510a7c --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_apple.go @@ -0,0 +1,131 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstore + +import ( + "bytes" + "encoding/json" +) + +// Apple struct for Apple +type Apple struct { + Cultivar *string `json:"cultivar,omitempty"` + Color *string `json:"color,omitempty"` +} + +// NewApple instantiates a new Apple object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewApple() *Apple { + this := Apple{} + return &this +} + +// NewAppleWithDefaults instantiates a new Apple object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAppleWithDefaults() *Apple { + this := Apple{} + return &this +} + +// GetCultivar returns the Cultivar field value if set, zero value otherwise. +func (o *Apple) GetCultivar() string { + if o == nil || o.Cultivar == nil { + var ret string + return ret + } + return *o.Cultivar +} + +// GetCultivarOk returns a tuple with the Cultivar field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *Apple) GetCultivarOk() (string, bool) { + if o == nil || o.Cultivar == nil { + var ret string + return ret, false + } + return *o.Cultivar, true +} + +// HasCultivar returns a boolean if a field has been set. +func (o *Apple) HasCultivar() bool { + if o != nil && o.Cultivar != nil { + return true + } + + return false +} + +// SetCultivar gets a reference to the given string and assigns it to the Cultivar field. +func (o *Apple) SetCultivar(v string) { + o.Cultivar = &v +} + +// GetColor returns the Color field value if set, zero value otherwise. +func (o *Apple) GetColor() string { + if o == nil || o.Color == nil { + var ret string + return ret + } + return *o.Color +} + +// GetColorOk returns a tuple with the Color field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *Apple) GetColorOk() (string, bool) { + if o == nil || o.Color == nil { + var ret string + return ret, false + } + return *o.Color, true +} + +// HasColor returns a boolean if a field has been set. +func (o *Apple) HasColor() bool { + if o != nil && o.Color != nil { + return true + } + + return false +} + +// SetColor gets a reference to the given string and assigns it to the Color field. +func (o *Apple) SetColor(v string) { + o.Color = &v +} + +// AsFruit wraps this instance of Apple in Fruit +func (s *Apple) AsFruit() Fruit { + return Fruit{ FruitInterface: s } +} +type NullableApple struct { + Value Apple + ExplicitNull bool +} + +func (v NullableApple) MarshalJSON() ([]byte, error) { + switch { + case v.ExplicitNull: + return []byte("null"), nil + default: + return json.Marshal(v.Value) + } +} + +func (v *NullableApple) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte("null")) { + v.ExplicitNull = true + return nil + } + + return json.Unmarshal(src, &v.Value) +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_apple_req.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_apple_req.go new file mode 100644 index 000000000000..6db225a4afe4 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_apple_req.go @@ -0,0 +1,114 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstore + +import ( + "bytes" + "encoding/json" +) + +// AppleReq struct for AppleReq +type AppleReq struct { + Cultivar string `json:"cultivar"` + Mealy *bool `json:"mealy,omitempty"` +} + +// NewAppleReq instantiates a new AppleReq object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAppleReq(cultivar string, ) *AppleReq { + this := AppleReq{} + this.Cultivar = cultivar + return &this +} + +// NewAppleReqWithDefaults instantiates a new AppleReq object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAppleReqWithDefaults() *AppleReq { + this := AppleReq{} + return &this +} + +// GetCultivar returns the Cultivar field value +func (o *AppleReq) GetCultivar() string { + if o == nil { + var ret string + return ret + } + + return o.Cultivar +} + +// SetCultivar sets field value +func (o *AppleReq) SetCultivar(v string) { + o.Cultivar = v +} + +// GetMealy returns the Mealy field value if set, zero value otherwise. +func (o *AppleReq) GetMealy() bool { + if o == nil || o.Mealy == nil { + var ret bool + return ret + } + return *o.Mealy +} + +// GetMealyOk returns a tuple with the Mealy field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *AppleReq) GetMealyOk() (bool, bool) { + if o == nil || o.Mealy == nil { + var ret bool + return ret, false + } + return *o.Mealy, true +} + +// HasMealy returns a boolean if a field has been set. +func (o *AppleReq) HasMealy() bool { + if o != nil && o.Mealy != nil { + return true + } + + return false +} + +// SetMealy gets a reference to the given bool and assigns it to the Mealy field. +func (o *AppleReq) SetMealy(v bool) { + o.Mealy = &v +} + +// AsFruitReq wraps this instance of AppleReq in FruitReq +func (s *AppleReq) AsFruitReq() FruitReq { + return FruitReq{ FruitReqInterface: s } +} +type NullableAppleReq struct { + Value AppleReq + ExplicitNull bool +} + +func (v NullableAppleReq) MarshalJSON() ([]byte, error) { + switch { + case v.ExplicitNull: + return []byte("null"), nil + default: + return json.Marshal(v.Value) + } +} + +func (v *NullableAppleReq) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte("null")) { + v.ExplicitNull = true + return nil + } + + return json.Unmarshal(src, &v.Value) +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_banana.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_banana.go new file mode 100644 index 000000000000..6d923f239595 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_banana.go @@ -0,0 +1,131 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstore + +import ( + "bytes" + "encoding/json" +) + +// Banana struct for Banana +type Banana struct { + LengthCm *float32 `json:"lengthCm,omitempty"` + Color *string `json:"color,omitempty"` +} + +// NewBanana instantiates a new Banana object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewBanana() *Banana { + this := Banana{} + return &this +} + +// NewBananaWithDefaults instantiates a new Banana object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewBananaWithDefaults() *Banana { + this := Banana{} + return &this +} + +// GetLengthCm returns the LengthCm field value if set, zero value otherwise. +func (o *Banana) GetLengthCm() float32 { + if o == nil || o.LengthCm == nil { + var ret float32 + return ret + } + return *o.LengthCm +} + +// GetLengthCmOk returns a tuple with the LengthCm field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *Banana) GetLengthCmOk() (float32, bool) { + if o == nil || o.LengthCm == nil { + var ret float32 + return ret, false + } + return *o.LengthCm, true +} + +// HasLengthCm returns a boolean if a field has been set. +func (o *Banana) HasLengthCm() bool { + if o != nil && o.LengthCm != nil { + return true + } + + return false +} + +// SetLengthCm gets a reference to the given float32 and assigns it to the LengthCm field. +func (o *Banana) SetLengthCm(v float32) { + o.LengthCm = &v +} + +// GetColor returns the Color field value if set, zero value otherwise. +func (o *Banana) GetColor() string { + if o == nil || o.Color == nil { + var ret string + return ret + } + return *o.Color +} + +// GetColorOk returns a tuple with the Color field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *Banana) GetColorOk() (string, bool) { + if o == nil || o.Color == nil { + var ret string + return ret, false + } + return *o.Color, true +} + +// HasColor returns a boolean if a field has been set. +func (o *Banana) HasColor() bool { + if o != nil && o.Color != nil { + return true + } + + return false +} + +// SetColor gets a reference to the given string and assigns it to the Color field. +func (o *Banana) SetColor(v string) { + o.Color = &v +} + +// AsFruit wraps this instance of Banana in Fruit +func (s *Banana) AsFruit() Fruit { + return Fruit{ FruitInterface: s } +} +type NullableBanana struct { + Value Banana + ExplicitNull bool +} + +func (v NullableBanana) MarshalJSON() ([]byte, error) { + switch { + case v.ExplicitNull: + return []byte("null"), nil + default: + return json.Marshal(v.Value) + } +} + +func (v *NullableBanana) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte("null")) { + v.ExplicitNull = true + return nil + } + + return json.Unmarshal(src, &v.Value) +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_banana_req.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_banana_req.go new file mode 100644 index 000000000000..543d4476d688 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_banana_req.go @@ -0,0 +1,114 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstore + +import ( + "bytes" + "encoding/json" +) + +// BananaReq struct for BananaReq +type BananaReq struct { + LengthCm float32 `json:"lengthCm"` + Sweet *bool `json:"sweet,omitempty"` +} + +// NewBananaReq instantiates a new BananaReq object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewBananaReq(lengthCm float32, ) *BananaReq { + this := BananaReq{} + this.LengthCm = lengthCm + return &this +} + +// NewBananaReqWithDefaults instantiates a new BananaReq object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewBananaReqWithDefaults() *BananaReq { + this := BananaReq{} + return &this +} + +// GetLengthCm returns the LengthCm field value +func (o *BananaReq) GetLengthCm() float32 { + if o == nil { + var ret float32 + return ret + } + + return o.LengthCm +} + +// SetLengthCm sets field value +func (o *BananaReq) SetLengthCm(v float32) { + o.LengthCm = v +} + +// GetSweet returns the Sweet field value if set, zero value otherwise. +func (o *BananaReq) GetSweet() bool { + if o == nil || o.Sweet == nil { + var ret bool + return ret + } + return *o.Sweet +} + +// GetSweetOk returns a tuple with the Sweet field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *BananaReq) GetSweetOk() (bool, bool) { + if o == nil || o.Sweet == nil { + var ret bool + return ret, false + } + return *o.Sweet, true +} + +// HasSweet returns a boolean if a field has been set. +func (o *BananaReq) HasSweet() bool { + if o != nil && o.Sweet != nil { + return true + } + + return false +} + +// SetSweet gets a reference to the given bool and assigns it to the Sweet field. +func (o *BananaReq) SetSweet(v bool) { + o.Sweet = &v +} + +// AsFruitReq wraps this instance of BananaReq in FruitReq +func (s *BananaReq) AsFruitReq() FruitReq { + return FruitReq{ FruitReqInterface: s } +} +type NullableBananaReq struct { + Value BananaReq + ExplicitNull bool +} + +func (v NullableBananaReq) MarshalJSON() ([]byte, error) { + switch { + case v.ExplicitNull: + return []byte("null"), nil + default: + return json.Marshal(v.Value) + } +} + +func (v *NullableBananaReq) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte("null")) { + v.ExplicitNull = true + return nil + } + + return json.Unmarshal(src, &v.Value) +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_fruit.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_fruit.go new file mode 100644 index 000000000000..c692b3e7eea9 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_fruit.go @@ -0,0 +1,64 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstore + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// Fruit struct for Fruit +type Fruit struct { + FruitInterface interface { } +} + +func (s *Fruit) MarshalJSON() ([]byte, error) { + return json.Marshal(s.FruitInterface) +} + +func (s *Fruit) UnmarshalJSON(src []byte) error { + var err error + var unmarshaledApple *Apple = &Apple{} + err = json.Unmarshal(src, unmarshaledApple) + if err == nil { + s.FruitInterface = unmarshaledApple + return nil + } + var unmarshaledBanana *Banana = &Banana{} + err = json.Unmarshal(src, unmarshaledBanana) + if err == nil { + s.FruitInterface = unmarshaledBanana + return nil + } + return fmt.Errorf("No oneOf model could be deserialized from payload: %s", string(src)) +} +type NullableFruit struct { + Value Fruit + ExplicitNull bool +} + +func (v NullableFruit) MarshalJSON() ([]byte, error) { + switch { + case v.ExplicitNull: + return []byte("null"), nil + default: + return json.Marshal(v.Value) + } +} + +func (v *NullableFruit) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte("null")) { + v.ExplicitNull = true + return nil + } + + return json.Unmarshal(src, &v.Value) +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_fruit_req.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_fruit_req.go new file mode 100644 index 000000000000..be4dd6864b49 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_fruit_req.go @@ -0,0 +1,64 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstore + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// FruitReq struct for FruitReq +type FruitReq struct { + FruitReqInterface interface { } +} + +func (s *FruitReq) MarshalJSON() ([]byte, error) { + return json.Marshal(s.FruitReqInterface) +} + +func (s *FruitReq) UnmarshalJSON(src []byte) error { + var err error + var unmarshaledAppleReq *AppleReq = &AppleReq{} + err = json.Unmarshal(src, unmarshaledAppleReq) + if err == nil { + s.FruitReqInterface = unmarshaledAppleReq + return nil + } + var unmarshaledBananaReq *BananaReq = &BananaReq{} + err = json.Unmarshal(src, unmarshaledBananaReq) + if err == nil { + s.FruitReqInterface = unmarshaledBananaReq + return nil + } + return fmt.Errorf("No oneOf model could be deserialized from payload: %s", string(src)) +} +type NullableFruitReq struct { + Value FruitReq + ExplicitNull bool +} + +func (v NullableFruitReq) MarshalJSON() ([]byte, error) { + switch { + case v.ExplicitNull: + return []byte("null"), nil + default: + return json.Marshal(v.Value) + } +} + +func (v *NullableFruitReq) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte("null")) { + v.ExplicitNull = true + return nil + } + + return json.Unmarshal(src, &v.Value) +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_gm_fruit.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_gm_fruit.go new file mode 100644 index 000000000000..c0350d87e064 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_gm_fruit.go @@ -0,0 +1,161 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstore + +import ( + "bytes" + "encoding/json" +) + +// GmFruit struct for GmFruit +type GmFruit struct { + Color *string `json:"color,omitempty"` + Cultivar *string `json:"cultivar,omitempty"` + LengthCm *float32 `json:"lengthCm,omitempty"` +} + +// NewGmFruit instantiates a new GmFruit object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewGmFruit() *GmFruit { + this := GmFruit{} + return &this +} + +// NewGmFruitWithDefaults instantiates a new GmFruit object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewGmFruitWithDefaults() *GmFruit { + this := GmFruit{} + return &this +} + +// GetColor returns the Color field value if set, zero value otherwise. +func (o *GmFruit) GetColor() string { + if o == nil || o.Color == nil { + var ret string + return ret + } + return *o.Color +} + +// GetColorOk returns a tuple with the Color field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *GmFruit) GetColorOk() (string, bool) { + if o == nil || o.Color == nil { + var ret string + return ret, false + } + return *o.Color, true +} + +// HasColor returns a boolean if a field has been set. +func (o *GmFruit) HasColor() bool { + if o != nil && o.Color != nil { + return true + } + + return false +} + +// SetColor gets a reference to the given string and assigns it to the Color field. +func (o *GmFruit) SetColor(v string) { + o.Color = &v +} + +// GetCultivar returns the Cultivar field value if set, zero value otherwise. +func (o *GmFruit) GetCultivar() string { + if o == nil || o.Cultivar == nil { + var ret string + return ret + } + return *o.Cultivar +} + +// GetCultivarOk returns a tuple with the Cultivar field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *GmFruit) GetCultivarOk() (string, bool) { + if o == nil || o.Cultivar == nil { + var ret string + return ret, false + } + return *o.Cultivar, true +} + +// HasCultivar returns a boolean if a field has been set. +func (o *GmFruit) HasCultivar() bool { + if o != nil && o.Cultivar != nil { + return true + } + + return false +} + +// SetCultivar gets a reference to the given string and assigns it to the Cultivar field. +func (o *GmFruit) SetCultivar(v string) { + o.Cultivar = &v +} + +// GetLengthCm returns the LengthCm field value if set, zero value otherwise. +func (o *GmFruit) GetLengthCm() float32 { + if o == nil || o.LengthCm == nil { + var ret float32 + return ret + } + return *o.LengthCm +} + +// GetLengthCmOk returns a tuple with the LengthCm field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *GmFruit) GetLengthCmOk() (float32, bool) { + if o == nil || o.LengthCm == nil { + var ret float32 + return ret, false + } + return *o.LengthCm, true +} + +// HasLengthCm returns a boolean if a field has been set. +func (o *GmFruit) HasLengthCm() bool { + if o != nil && o.LengthCm != nil { + return true + } + + return false +} + +// SetLengthCm gets a reference to the given float32 and assigns it to the LengthCm field. +func (o *GmFruit) SetLengthCm(v float32) { + o.LengthCm = &v +} + +type NullableGmFruit struct { + Value GmFruit + ExplicitNull bool +} + +func (v NullableGmFruit) MarshalJSON() ([]byte, error) { + switch { + case v.ExplicitNull: + return []byte("null"), nil + default: + return json.Marshal(v.Value) + } +} + +func (v *NullableGmFruit) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte("null")) { + v.ExplicitNull = true + return nil + } + + return json.Unmarshal(src, &v.Value) +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_mammal.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_mammal.go new file mode 100644 index 000000000000..58095a07fab7 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_mammal.go @@ -0,0 +1,80 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstore + +import ( + "bytes" + "encoding/json" + "fmt" +) + +// Mammal struct for Mammal +type Mammal struct { + MammalInterface interface { GetClassName() string } +} + +func (s *Mammal) MarshalJSON() ([]byte, error) { + return json.Marshal(s.MammalInterface) +} + +func (s *Mammal) UnmarshalJSON(src []byte) error { + var err error + var unmarshaled map[string]interface{} + err = json.Unmarshal(src, &unmarshaled) + if err != nil { + return err + } + if v, ok := unmarshaled["className"]; ok { + switch v { + case "whale": + var result *Whale = &Whale{} + err = json.Unmarshal(src, result) + if err != nil { + return err + } + s.MammalInterface = result + return nil + case "zebra": + var result *Zebra = &Zebra{} + err = json.Unmarshal(src, result) + if err != nil { + return err + } + s.MammalInterface = result + return nil + default: + return fmt.Errorf("No oneOf model has 'className' equal to %s", v) + } + } else { + return fmt.Errorf("Discriminator property 'className' not found in unmarshaled payload: %+v", unmarshaled) + } +} +type NullableMammal struct { + Value Mammal + ExplicitNull bool +} + +func (v NullableMammal) MarshalJSON() ([]byte, error) { + switch { + case v.ExplicitNull: + return []byte("null"), nil + default: + return json.Marshal(v.Value) + } +} + +func (v *NullableMammal) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte("null")) { + v.ExplicitNull = true + return nil + } + + return json.Unmarshal(src, &v.Value) +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_whale.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_whale.go new file mode 100644 index 000000000000..be28dd59d354 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_whale.go @@ -0,0 +1,148 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstore + +import ( + "bytes" + "encoding/json" +) + +// Whale struct for Whale +type Whale struct { + HasBaleen *bool `json:"hasBaleen,omitempty"` + HasTeeth *bool `json:"hasTeeth,omitempty"` + ClassName string `json:"className"` +} + +// NewWhale instantiates a new Whale object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewWhale(className string, ) *Whale { + this := Whale{} + this.ClassName = className + return &this +} + +// NewWhaleWithDefaults instantiates a new Whale object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewWhaleWithDefaults() *Whale { + this := Whale{} + return &this +} + +// GetHasBaleen returns the HasBaleen field value if set, zero value otherwise. +func (o *Whale) GetHasBaleen() bool { + if o == nil || o.HasBaleen == nil { + var ret bool + return ret + } + return *o.HasBaleen +} + +// GetHasBaleenOk returns a tuple with the HasBaleen field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *Whale) GetHasBaleenOk() (bool, bool) { + if o == nil || o.HasBaleen == nil { + var ret bool + return ret, false + } + return *o.HasBaleen, true +} + +// HasHasBaleen returns a boolean if a field has been set. +func (o *Whale) HasHasBaleen() bool { + if o != nil && o.HasBaleen != nil { + return true + } + + return false +} + +// SetHasBaleen gets a reference to the given bool and assigns it to the HasBaleen field. +func (o *Whale) SetHasBaleen(v bool) { + o.HasBaleen = &v +} + +// GetHasTeeth returns the HasTeeth field value if set, zero value otherwise. +func (o *Whale) GetHasTeeth() bool { + if o == nil || o.HasTeeth == nil { + var ret bool + return ret + } + return *o.HasTeeth +} + +// GetHasTeethOk returns a tuple with the HasTeeth field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *Whale) GetHasTeethOk() (bool, bool) { + if o == nil || o.HasTeeth == nil { + var ret bool + return ret, false + } + return *o.HasTeeth, true +} + +// HasHasTeeth returns a boolean if a field has been set. +func (o *Whale) HasHasTeeth() bool { + if o != nil && o.HasTeeth != nil { + return true + } + + return false +} + +// SetHasTeeth gets a reference to the given bool and assigns it to the HasTeeth field. +func (o *Whale) SetHasTeeth(v bool) { + o.HasTeeth = &v +} + +// GetClassName returns the ClassName field value +func (o *Whale) GetClassName() string { + if o == nil { + var ret string + return ret + } + + return o.ClassName +} + +// SetClassName sets field value +func (o *Whale) SetClassName(v string) { + o.ClassName = v +} + +// AsMammal wraps this instance of Whale in Mammal +func (s *Whale) AsMammal() Mammal { + return Mammal{ MammalInterface: s } +} +type NullableWhale struct { + Value Whale + ExplicitNull bool +} + +func (v NullableWhale) MarshalJSON() ([]byte, error) { + switch { + case v.ExplicitNull: + return []byte("null"), nil + default: + return json.Marshal(v.Value) + } +} + +func (v *NullableWhale) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte("null")) { + v.ExplicitNull = true + return nil + } + + return json.Unmarshal(src, &v.Value) +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/model_zebra.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_zebra.go new file mode 100644 index 000000000000..bffa8eb7b851 --- /dev/null +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/model_zebra.go @@ -0,0 +1,114 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstore + +import ( + "bytes" + "encoding/json" +) + +// Zebra struct for Zebra +type Zebra struct { + Type *string `json:"type,omitempty"` + ClassName string `json:"className"` +} + +// NewZebra instantiates a new Zebra object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewZebra(className string, ) *Zebra { + this := Zebra{} + this.ClassName = className + return &this +} + +// NewZebraWithDefaults instantiates a new Zebra object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewZebraWithDefaults() *Zebra { + this := Zebra{} + return &this +} + +// GetType returns the Type field value if set, zero value otherwise. +func (o *Zebra) GetType() string { + if o == nil || o.Type == nil { + var ret string + return ret + } + return *o.Type +} + +// GetTypeOk returns a tuple with the Type field value if set, zero value otherwise +// and a boolean to check if the value has been set. +func (o *Zebra) GetTypeOk() (string, bool) { + if o == nil || o.Type == nil { + var ret string + return ret, false + } + return *o.Type, true +} + +// HasType returns a boolean if a field has been set. +func (o *Zebra) HasType() bool { + if o != nil && o.Type != nil { + return true + } + + return false +} + +// SetType gets a reference to the given string and assigns it to the Type field. +func (o *Zebra) SetType(v string) { + o.Type = &v +} + +// GetClassName returns the ClassName field value +func (o *Zebra) GetClassName() string { + if o == nil { + var ret string + return ret + } + + return o.ClassName +} + +// SetClassName sets field value +func (o *Zebra) SetClassName(v string) { + o.ClassName = v +} + +// AsMammal wraps this instance of Zebra in Mammal +func (s *Zebra) AsMammal() Mammal { + return Mammal{ MammalInterface: s } +} +type NullableZebra struct { + Value Zebra + ExplicitNull bool +} + +func (v NullableZebra) MarshalJSON() ([]byte, error) { + switch { + case v.ExplicitNull: + return []byte("null"), nil + default: + return json.Marshal(v.Value) + } +} + +func (v *NullableZebra) UnmarshalJSON(src []byte) error { + if bytes.Equal(src, []byte("null")) { + v.ExplicitNull = true + return nil + } + + return json.Unmarshal(src, &v.Value) +} diff --git a/samples/openapi3/client/petstore/python-experimental/README.md b/samples/openapi3/client/petstore/python-experimental/README.md index 7c1b27f95a4d..a0988878b947 100644 --- a/samples/openapi3/client/petstore/python-experimental/README.md +++ b/samples/openapi3/client/petstore/python-experimental/README.md @@ -120,9 +120,13 @@ Class | Method | HTTP request | Description - [address.Address](docs/Address.md) - [animal.Animal](docs/Animal.md) - [api_response.ApiResponse](docs/ApiResponse.md) + - [apple.Apple](docs/Apple.md) + - [apple_req.AppleReq](docs/AppleReq.md) - [array_of_array_of_number_only.ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [array_of_number_only.ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) - [array_test.ArrayTest](docs/ArrayTest.md) + - [banana.Banana](docs/Banana.md) + - [banana_req.BananaReq](docs/BananaReq.md) - [capitalization.Capitalization](docs/Capitalization.md) - [cat.Cat](docs/Cat.md) - [cat_all_of.CatAllOf](docs/CatAllOf.md) @@ -138,6 +142,9 @@ Class | Method | HTTP request | Description - [file_schema_test_class.FileSchemaTestClass](docs/FileSchemaTestClass.md) - [foo.Foo](docs/Foo.md) - [format_test.FormatTest](docs/FormatTest.md) + - [fruit.Fruit](docs/Fruit.md) + - [fruit_req.FruitReq](docs/FruitReq.md) + - [gm_fruit.GmFruit](docs/GmFruit.md) - [has_only_read_only.HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - [health_check_result.HealthCheckResult](docs/HealthCheckResult.md) - [inline_object.InlineObject](docs/InlineObject.md) @@ -148,6 +155,7 @@ Class | Method | HTTP request | Description - [inline_object5.InlineObject5](docs/InlineObject5.md) - [inline_response_default.InlineResponseDefault](docs/InlineResponseDefault.md) - [list.List](docs/List.md) + - [mammal.Mammal](docs/Mammal.md) - [map_test.MapTest](docs/MapTest.md) - [mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [model200_response.Model200Response](docs/Model200Response.md) @@ -167,6 +175,8 @@ Class | Method | HTTP request | Description - [string_boolean_map.StringBooleanMap](docs/StringBooleanMap.md) - [tag.Tag](docs/Tag.md) - [user.User](docs/User.md) + - [whale.Whale](docs/Whale.md) + - [zebra.Zebra](docs/Zebra.md) ## Documentation For Authorization diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Apple.md b/samples/openapi3/client/petstore/python-experimental/docs/Apple.md new file mode 100644 index 000000000000..0c62affcde4e --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Apple.md @@ -0,0 +1,10 @@ +# apple.Apple + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**cultivar** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-experimental/docs/AppleReq.md b/samples/openapi3/client/petstore/python-experimental/docs/AppleReq.md new file mode 100644 index 000000000000..3d6717ebd60c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/AppleReq.md @@ -0,0 +1,11 @@ +# apple_req.AppleReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**cultivar** | **str** | | +**mealy** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Banana.md b/samples/openapi3/client/petstore/python-experimental/docs/Banana.md new file mode 100644 index 000000000000..ec8b3b902cc4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Banana.md @@ -0,0 +1,10 @@ +# banana.Banana + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**length_cm** | **float** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-experimental/docs/BananaReq.md b/samples/openapi3/client/petstore/python-experimental/docs/BananaReq.md new file mode 100644 index 000000000000..5cfe53ec741f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/BananaReq.md @@ -0,0 +1,11 @@ +# banana_req.BananaReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**length_cm** | **float** | | +**sweet** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Fruit.md b/samples/openapi3/client/petstore/python-experimental/docs/Fruit.md new file mode 100644 index 000000000000..24ea69546ff8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Fruit.md @@ -0,0 +1,12 @@ +# fruit.Fruit + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**color** | **str** | | [optional] +**cultivar** | **str** | | [optional] +**length_cm** | **float** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-experimental/docs/FruitReq.md b/samples/openapi3/client/petstore/python-experimental/docs/FruitReq.md new file mode 100644 index 000000000000..22eeb37f1cc3 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/FruitReq.md @@ -0,0 +1,13 @@ +# fruit_req.FruitReq + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**cultivar** | **str** | | defaults to nulltype.Null +**length_cm** | **float** | | defaults to nulltype.Null +**mealy** | **bool** | | [optional] +**sweet** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-experimental/docs/GmFruit.md b/samples/openapi3/client/petstore/python-experimental/docs/GmFruit.md new file mode 100644 index 000000000000..4e0538c6c445 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/GmFruit.md @@ -0,0 +1,12 @@ +# gm_fruit.GmFruit + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**color** | **str** | | [optional] +**cultivar** | **str** | | [optional] +**length_cm** | **float** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Mammal.md b/samples/openapi3/client/petstore/python-experimental/docs/Mammal.md new file mode 100644 index 000000000000..b86f0b17ab99 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Mammal.md @@ -0,0 +1,13 @@ +# mammal.Mammal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **str** | | +**has_baleen** | **bool** | | [optional] +**has_teeth** | **bool** | | [optional] +**type** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Whale.md b/samples/openapi3/client/petstore/python-experimental/docs/Whale.md new file mode 100644 index 000000000000..4a19e88c5553 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Whale.md @@ -0,0 +1,12 @@ +# whale.Whale + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **str** | | +**has_baleen** | **bool** | | [optional] +**has_teeth** | **bool** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-experimental/docs/Zebra.md b/samples/openapi3/client/petstore/python-experimental/docs/Zebra.md new file mode 100644 index 000000000000..779a8db51e9f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/docs/Zebra.md @@ -0,0 +1,11 @@ +# zebra.Zebra + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**class_name** | **str** | | +**type** | **str** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/__init__.py index fbe114c91775..3aa279dd15d6 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/__init__.py @@ -44,9 +44,13 @@ from petstore_api.models.address import Address from petstore_api.models.animal import Animal from petstore_api.models.api_response import ApiResponse +from petstore_api.models.apple import Apple +from petstore_api.models.apple_req import AppleReq from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly from petstore_api.models.array_of_number_only import ArrayOfNumberOnly from petstore_api.models.array_test import ArrayTest +from petstore_api.models.banana import Banana +from petstore_api.models.banana_req import BananaReq from petstore_api.models.capitalization import Capitalization from petstore_api.models.cat import Cat from petstore_api.models.cat_all_of import CatAllOf @@ -62,6 +66,9 @@ from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.models.foo import Foo from petstore_api.models.format_test import FormatTest +from petstore_api.models.fruit import Fruit +from petstore_api.models.fruit_req import FruitReq +from petstore_api.models.gm_fruit import GmFruit from petstore_api.models.has_only_read_only import HasOnlyReadOnly from petstore_api.models.health_check_result import HealthCheckResult from petstore_api.models.inline_object import InlineObject @@ -72,6 +79,7 @@ from petstore_api.models.inline_object5 import InlineObject5 from petstore_api.models.inline_response_default import InlineResponseDefault from petstore_api.models.list import List +from petstore_api.models.mammal import Mammal from petstore_api.models.map_test import MapTest from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass from petstore_api.models.model200_response import Model200Response @@ -91,3 +99,5 @@ from petstore_api.models.string_boolean_map import StringBooleanMap from petstore_api.models.tag import Tag from petstore_api.models.user import User +from petstore_api.models.whale import Whale +from petstore_api.models.zebra import Zebra diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/model_utils.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/model_utils.py index 074e597cbd22..eed501c84502 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/model_utils.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/model_utils.py @@ -274,13 +274,20 @@ def __getattr__(self, name): if self._path_to_item: path_to_item.extend(self._path_to_item) path_to_item.append(name) + values = set() if model_instances: - values = set() for model_instance in model_instances: if name in model_instance._data_store: values.add(model_instance._data_store[name]) - if len(values) == 1: - return list(values)[0] + len_values = len(values) + if len_values == 0: + raise ApiKeyError( + "{0} has no key '{1}'".format(type(self).__name__, name), + path_to_item + ) + elif len_values == 1: + return list(values)[0] + elif len_values > 1: raise ApiValueError( "Values stored for property {0} in {1} difffer when looking " "at self and self's composed instances. All values must be " @@ -288,11 +295,6 @@ def __getattr__(self, name): path_to_item ) - raise ApiKeyError( - "{0} has no key '{1}'".format(type(self).__name__, name), - path_to_item - ) - def to_dict(self): """Returns the model properties as a dict""" return model_to_dict(self, serialize=False) @@ -1082,7 +1084,7 @@ def model_to_dict(model_instance, serialize=True): model_instances = [model_instance] if model_instance._composed_schemas() is not None: - model_instances = model_instance._composed_instances + model_instances.extend(model_instance._composed_instances) for model_instance in model_instances: for attr, value in six.iteritems(model_instance._data_store): if serialize: @@ -1205,12 +1207,12 @@ def get_oneof_instance(self, model_args, constant_args): used to make instances Returns - oneof_instance (instance) + oneof_instance (instance/None) """ - oneof_instance = None if len(self._composed_schemas()['oneOf']) == 0: - return oneof_instance + return None + oneof_instances = [] for oneof_class in self._composed_schemas()['oneOf']: # transform js keys to python keys in fixed_model_args fixed_model_args = change_keys_js_to_python( @@ -1223,20 +1225,30 @@ def get_oneof_instance(self, model_args, constant_args): if var_name in fixed_model_args: kwargs[var_name] = fixed_model_args[var_name] + # do not try to make a model with no input args + if len(kwargs) == 0: + continue + # and use it to make the instance kwargs.update(constant_args) try: oneof_instance = oneof_class(**kwargs) - break + oneof_instances.append(oneof_instance) except Exception: pass - if oneof_instance is None: + if len(oneof_instances) == 0: raise ApiValueError( "Invalid inputs given to generate an instance of %s. Unable to " "make any instances of the classes in oneOf definition." % self.__class__.__name__ ) - return oneof_instance + elif len(oneof_instances) > 1: + raise ApiValueError( + "Invalid inputs given to generate an instance of %s. Multiple " + "oneOf instances were generated when a max of one is allowed." % + self.__class__.__name__ + ) + return oneof_instances[0] def get_anyof_instances(self, model_args, constant_args): @@ -1266,6 +1278,10 @@ def get_anyof_instances(self, model_args, constant_args): if var_name in fixed_model_args: kwargs[var_name] = fixed_model_args[var_name] + # do not try to make a model with no input args + if len(kwargs) == 0: + continue + # and use it to make the instance kwargs.update(constant_args) try: diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py index 19b97e69b6af..30bc3cdce6f3 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/additional_properties_class.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -101,7 +102,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """additional_properties_class.AdditionalPropertiesClass - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/address.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/address.py index 39cec0750135..05a95d57fa99 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/address.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/address.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -97,7 +98,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """address.Address - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/animal.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/animal.py index 4971ab17ab56..45058ec7612f 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/animal.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/animal.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/api_response.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/api_response.py index 893024a80b99..f1680c87f67a 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/api_response.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/api_response.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -103,7 +104,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """api_response.ApiResponse - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/apple.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/apple.py new file mode 100644 index 000000000000..03c502690d5d --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/apple.py @@ -0,0 +1,133 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 +import nulltype # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class Apple(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def openapi_types(): + """ + This must be a class method so a model may have properties that are + of type self, this ensures that we don't create a cyclic import + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'cultivar': (str,), # noqa: E501 + } + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'cultivar': 'cultivar', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """apple.Apple - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + cultivar (str): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + for var_name, var_value in six.iteritems(kwargs): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/apple_req.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/apple_req.py new file mode 100644 index 000000000000..7aa81bf4c776 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/apple_req.py @@ -0,0 +1,139 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 +import nulltype # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class AppleReq(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def openapi_types(): + """ + This must be a class method so a model may have properties that are + of type self, this ensures that we don't create a cyclic import + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'cultivar': (str,), # noqa: E501 + 'mealy': (bool,), # noqa: E501 + } + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'cultivar': 'cultivar', # noqa: E501 + 'mealy': 'mealy', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, cultivar, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """apple_req.AppleReq - a model defined in OpenAPI + + Args: + cultivar (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + mealy (bool): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + self.cultivar = cultivar + for var_name, var_value in six.iteritems(kwargs): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py index faa9b5c44ccd..bf6419e5c089 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_of_array_of_number_only.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """array_of_array_of_number_only.ArrayOfArrayOfNumberOnly - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py index 2909708136de..f3bf89e27ba3 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_of_number_only.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """array_of_number_only.ArrayOfNumberOnly - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_test.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_test.py index 7f4f1090663a..0a01b3cad210 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_test.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/array_test.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -108,7 +109,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """array_test.ArrayTest - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/banana.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/banana.py new file mode 100644 index 000000000000..fda69a28a253 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/banana.py @@ -0,0 +1,133 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 +import nulltype # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class Banana(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def openapi_types(): + """ + This must be a class method so a model may have properties that are + of type self, this ensures that we don't create a cyclic import + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'length_cm': (float,), # noqa: E501 + } + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'length_cm': 'lengthCm', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """banana.Banana - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + length_cm (float): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + for var_name, var_value in six.iteritems(kwargs): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/banana_req.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/banana_req.py new file mode 100644 index 000000000000..bf7d461c469c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/banana_req.py @@ -0,0 +1,139 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 +import nulltype # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class BananaReq(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def openapi_types(): + """ + This must be a class method so a model may have properties that are + of type self, this ensures that we don't create a cyclic import + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'length_cm': (float,), # noqa: E501 + 'sweet': (bool,), # noqa: E501 + } + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'length_cm': 'lengthCm', # noqa: E501 + 'sweet': 'sweet', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, length_cm, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """banana_req.BananaReq - a model defined in OpenAPI + + Args: + length_cm (float): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + sweet (bool): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + self.length_cm = length_cm + for var_name, var_value in six.iteritems(kwargs): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/capitalization.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/capitalization.py index b4be4b15e71d..6011db39400c 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/capitalization.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/capitalization.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -109,7 +110,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """capitalization.Capitalization - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/cat.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/cat.py index 4106ff709bba..92076d35c068 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/cat.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/cat.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -150,9 +151,16 @@ def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_it '_from_server': _from_server, '_configuration': _configuration, } - model_args = { + required_args = { 'class_name': class_name, } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) @@ -161,7 +169,8 @@ def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_it self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] - self.class_name = class_name + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) for var_name, var_value in six.iteritems(kwargs): if var_name in unused_args and \ self._configuration is not None and \ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/cat_all_of.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/cat_all_of.py index 1c3fe2578a46..75e856dcbcde 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/cat_all_of.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/cat_all_of.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """cat_all_of.CatAllOf - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/category.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/category.py index fcdb58cb9568..5d3e21ddd7e9 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/category.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/category.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -104,7 +105,7 @@ def __init__(self, name='default-name', _check_type=True, _from_server=False, _p Args: Keyword Args: - name (str): defaults to 'default-name', must be one of ['default-name'] # noqa: E501 + name (str): defaults to 'default-name' # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/class_model.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/class_model.py index e4f1d63a264c..06c52dc8bee9 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/class_model.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/class_model.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """class_model.ClassModel - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/client.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/client.py index f3f645da3823..b7184b3f2b40 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/client.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/client.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """client.Client - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/dog.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/dog.py index 462869ffbd28..69af821b27e2 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/dog.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/dog.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -145,9 +146,16 @@ def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_it '_from_server': _from_server, '_configuration': _configuration, } - model_args = { + required_args = { 'class_name': class_name, } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) model_args.update(kwargs) composed_info = validate_get_composed_info( constant_args, model_args, self) @@ -156,7 +164,8 @@ def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_it self._additional_properties_model_instances = composed_info[2] unused_args = composed_info[3] - self.class_name = class_name + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) for var_name, var_value in six.iteritems(kwargs): if var_name in unused_args and \ self._configuration is not None and \ diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/dog_all_of.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/dog_all_of.py index ec62d18e6376..0832f4b696cc 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/dog_all_of.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/dog_all_of.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """dog_all_of.DogAllOf - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_arrays.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_arrays.py index 59f73c8f1c9e..358e9f680e76 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_arrays.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_arrays.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -109,7 +110,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """enum_arrays.EnumArrays - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_class.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_class.py index 994d7723842e..5f3f1894de47 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_class.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_class.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,7 @@ def __init__(self, value='-efg', _check_type=True, _from_server=False, _path_to_ Args: Keyword Args: - value (str): defaults to '-efg', must be one of ['-efg'] # noqa: E501 + value (str): defaults to '-efg', must be one of ["_abc", "-efg", "(xyz)", ] # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_test.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_test.py index bb39c26a8713..bcd601f04ed3 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_test.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/enum_test.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/file.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/file.py index 46f02f4436cf..f71dc07b7ca8 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/file.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/file.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """file.File - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py index 9c5cb0c63664..1260e8affda2 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/file_schema_test_class.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -106,7 +107,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """file_schema_test_class.FileSchemaTestClass - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/foo.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/foo.py index c9503266fc2e..7a71b34dc4de 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/foo.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/foo.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """foo.Foo - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/format_test.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/format_test.py index cd42a4b11ed4..2a7e08f4d737 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/format_test.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/format_test.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/fruit.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/fruit.py new file mode 100644 index 000000000000..d5e71abd700f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/fruit.py @@ -0,0 +1,193 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 +import nulltype # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) +try: + from petstore_api.models import apple +except ImportError: + apple = sys.modules[ + 'petstore_api.models.apple'] +try: + from petstore_api.models import banana +except ImportError: + banana = sys.modules[ + 'petstore_api.models.banana'] + + +class Fruit(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def openapi_types(): + """ + This must be a class method so a model may have properties that are + of type self, this ensures that we don't create a cyclic import + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'color': (str,), # noqa: E501 + 'cultivar': (str,), # noqa: E501 + 'length_cm': (float,), # noqa: E501 + } + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'color': 'color', # noqa: E501 + 'cultivar': 'cultivar', # noqa: E501 + 'length_cm': 'lengthCm', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """fruit.Fruit - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + color (str): [optional] # noqa: E501 + cultivar (str): [optional] # noqa: E501 + length_cm (float): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + required_args = { + } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + unused_args = composed_info[3] + + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) + for var_name, var_value in six.iteritems(kwargs): + if var_name in unused_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + not self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + apple.Apple, + banana.Banana, + ], + } diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/fruit_req.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/fruit_req.py new file mode 100644 index 000000000000..111326fcb4f6 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/fruit_req.py @@ -0,0 +1,200 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 +import nulltype # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) +try: + from petstore_api.models import apple_req +except ImportError: + apple_req = sys.modules[ + 'petstore_api.models.apple_req'] +try: + from petstore_api.models import banana_req +except ImportError: + banana_req = sys.modules[ + 'petstore_api.models.banana_req'] + + +class FruitReq(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def openapi_types(): + """ + This must be a class method so a model may have properties that are + of type self, this ensures that we don't create a cyclic import + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'cultivar': (str,), # noqa: E501 + 'length_cm': (float,), # noqa: E501 + 'mealy': (bool,), # noqa: E501 + 'sweet': (bool,), # noqa: E501 + } + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'cultivar': 'cultivar', # noqa: E501 + 'length_cm': 'lengthCm', # noqa: E501 + 'mealy': 'mealy', # noqa: E501 + 'sweet': 'sweet', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + def __init__(self, cultivar=nulltype.Null, length_cm=nulltype.Null, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """fruit_req.FruitReq - a model defined in OpenAPI + + Args: + + Keyword Args: + cultivar (str): defaults to nulltype.Null # noqa: E501 + length_cm (float): defaults to nulltype.Null # noqa: E501 + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + mealy (bool): [optional] # noqa: E501 + sweet (bool): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + required_args = { + 'cultivar': cultivar, + 'length_cm': length_cm, + } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + unused_args = composed_info[3] + + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) + for var_name, var_value in six.iteritems(kwargs): + if var_name in unused_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + not self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + apple_req.AppleReq, + banana_req.BananaReq, + ], + } diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/gm_fruit.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/gm_fruit.py new file mode 100644 index 000000000000..0888743b8ec8 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/gm_fruit.py @@ -0,0 +1,193 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 +import nulltype # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) +try: + from petstore_api.models import apple +except ImportError: + apple = sys.modules[ + 'petstore_api.models.apple'] +try: + from petstore_api.models import banana +except ImportError: + banana = sys.modules[ + 'petstore_api.models.banana'] + + +class GmFruit(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def openapi_types(): + """ + This must be a class method so a model may have properties that are + of type self, this ensures that we don't create a cyclic import + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'color': (str,), # noqa: E501 + 'cultivar': (str,), # noqa: E501 + 'length_cm': (float,), # noqa: E501 + } + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'color': 'color', # noqa: E501 + 'cultivar': 'cultivar', # noqa: E501 + 'length_cm': 'lengthCm', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """gm_fruit.GmFruit - a model defined in OpenAPI + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + color (str): [optional] # noqa: E501 + cultivar (str): [optional] # noqa: E501 + length_cm (float): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + required_args = { + } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + unused_args = composed_info[3] + + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) + for var_name, var_value in six.iteritems(kwargs): + if var_name in unused_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + not self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + apple.Apple, + banana.Banana, + ], + 'allOf': [ + ], + 'oneOf': [ + ], + } diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/gm_mammal.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/gm_mammal.py new file mode 100644 index 000000000000..83ef04f9707f --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/gm_mammal.py @@ -0,0 +1,212 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) +try: + from petstore_api.models import whale +except ImportError: + whale = sys.modules[ + 'petstore_api.models.whale'] +try: + from petstore_api.models import zebra +except ImportError: + zebra = sys.modules[ + 'petstore_api.models.zebra'] + + +class GmMammal(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('lungs',): { + '2': 2, + }, + ('type',): { + 'PLAINS': "plains", + 'MOUNTAIN': "mountain", + 'GREVYS': "grevys", + }, + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def openapi_types(): + """ + This must be a class method so a model may have properties that are + of type self, this ensures that we don't create a cyclic import + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'class_name': (str,), # noqa: E501 + 'lungs': (int,), # noqa: E501 + 'has_baleen': (bool,), # noqa: E501 + 'has_teeth': (bool,), # noqa: E501 + 'type': (str,), # noqa: E501 + } + + @staticmethod + def discriminator(): + return { + 'class_name': { + 'whale': whale.Whale, + 'zebra': zebra.Zebra, + }, + } + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'lungs': 'lungs', # noqa: E501 + 'has_baleen': 'hasBaleen', # noqa: E501 + 'has_teeth': 'hasTeeth', # noqa: E501 + 'type': 'type', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """gm_mammal.GmMammal - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + lungs (int): [optional] if omitted the server will use the default value of 2 # noqa: E501 + has_baleen (bool): [optional] # noqa: E501 + has_teeth (bool): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + model_args = { + 'class_name': class_name, + } + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + + self.class_name = class_name + for var_name, var_value in six.iteritems(kwargs): + setattr(self, var_name, var_value) + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + whale.Whale, + zebra.Zebra, + ], + 'allOf': [ + ], + 'oneOf': [ + ], + } + + @classmethod + def get_discriminator_class(cls, from_server, data): + """Returns the child class specified by the discriminator""" + discriminator = cls.discriminator() + discr_propertyname_py = list(discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if from_server: + class_name = data[discr_propertyname_js] + else: + class_name = data[discr_propertyname_py] + class_name_to_discr_class = discriminator[discr_propertyname_py] + return class_name_to_discr_class.get(class_name) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py index cf66f3fc02e8..c84cf0be3f2b 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/has_only_read_only.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -101,7 +102,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """has_only_read_only.HasOnlyReadOnly - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/health_check_result.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/health_check_result.py index 84e6ba56231a..873bad5451fe 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/health_check_result.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/health_check_result.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """health_check_result.HealthCheckResult - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object.py index 0879d7cf296e..bba44a11c13d 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -101,7 +102,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """inline_object.InlineObject - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object1.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object1.py index bbdd1f9d3c02..4262d4165fdc 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object1.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object1.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -101,7 +102,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """inline_object1.InlineObject1 - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object2.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object2.py index 1e97636581dc..2fd4792709f5 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object2.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object2.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -110,7 +111,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """inline_object2.InlineObject2 - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object3.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object3.py index 210fe669dc7f..209e97de6e18 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object3.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object3.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object4.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object4.py index cb4720589438..67b14d2c64e5 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object4.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object4.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object5.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object5.py index feaa8525c6d8..ce5fc59a4aee 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object5.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_object5.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_response_default.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_response_default.py index f1649f46890e..ad0f356ab50b 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_response_default.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/inline_response_default.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -104,7 +105,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """inline_response_default.InlineResponseDefault - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/list.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/list.py index d4cd4c4eb466..c7c80e8bd28b 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/list.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/list.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """list.List - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/mammal.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/mammal.py new file mode 100644 index 000000000000..303838fd7d4b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/mammal.py @@ -0,0 +1,222 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 +import nulltype # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) +try: + from petstore_api.models import whale +except ImportError: + whale = sys.modules[ + 'petstore_api.models.whale'] +try: + from petstore_api.models import zebra +except ImportError: + zebra = sys.modules[ + 'petstore_api.models.zebra'] + + +class Mammal(ModelComposed): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('type',): { + 'PLAINS': "plains", + 'MOUNTAIN': "mountain", + 'GREVYS': "grevys", + }, + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def openapi_types(): + """ + This must be a class method so a model may have properties that are + of type self, this ensures that we don't create a cyclic import + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'class_name': (str,), # noqa: E501 + 'has_baleen': (bool,), # noqa: E501 + 'has_teeth': (bool,), # noqa: E501 + 'type': (str,), # noqa: E501 + } + + @staticmethod + def discriminator(): + return { + 'class_name': { + 'whale': whale.Whale, + 'zebra': zebra.Zebra, + }, + } + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'has_baleen': 'hasBaleen', # noqa: E501 + 'has_teeth': 'hasTeeth', # noqa: E501 + 'type': 'type', # noqa: E501 + } + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + '_composed_instances', + '_var_name_to_model_instances', + '_additional_properties_model_instances', + ]) + + def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """mammal.Mammal - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + has_baleen (bool): [optional] # noqa: E501 + has_teeth (bool): [optional] # noqa: E501 + type (str): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + constant_args = { + '_check_type': _check_type, + '_path_to_item': _path_to_item, + '_from_server': _from_server, + '_configuration': _configuration, + } + required_args = { + 'class_name': class_name, + } + # remove args whose value is Null because they are unset + required_arg_names = list(required_args.keys()) + for required_arg_name in required_arg_names: + if required_args[required_arg_name] is nulltype.Null: + del required_args[required_arg_name] + model_args = {} + model_args.update(required_args) + model_args.update(kwargs) + composed_info = validate_get_composed_info( + constant_args, model_args, self) + self._composed_instances = composed_info[0] + self._var_name_to_model_instances = composed_info[1] + self._additional_properties_model_instances = composed_info[2] + unused_args = composed_info[3] + + for var_name, var_value in required_args.items(): + setattr(self, var_name, var_value) + for var_name, var_value in six.iteritems(kwargs): + if var_name in unused_args and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + not self._additional_properties_model_instances: + # discard variable. + continue + setattr(self, var_name, var_value) + + @staticmethod + def _composed_schemas(): + # we need this here to make our import statements work + # we must store _composed_schemas in here so the code is only run + # when we invoke this method. If we kept this at the class + # level we would get an error beause the class level + # code would be run when this module is imported, and these composed + # classes don't exist yet because their module has not finished + # loading + return { + 'anyOf': [ + ], + 'allOf': [ + ], + 'oneOf': [ + whale.Whale, + zebra.Zebra, + ], + } + + @classmethod + def get_discriminator_class(cls, from_server, data): + """Returns the child class specified by the discriminator""" + discriminator = cls.discriminator() + discr_propertyname_py = list(discriminator.keys())[0] + discr_propertyname_js = cls.attribute_map[discr_propertyname_py] + if from_server: + class_name = data[discr_propertyname_js] + else: + class_name = data[discr_propertyname_py] + class_name_to_discr_class = discriminator[discr_propertyname_py] + return class_name_to_discr_class.get(class_name) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/map_test.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/map_test.py index 95d680e9ebdf..8cc47c0a6922 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/map_test.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/map_test.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -114,7 +115,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """map_test.MapTest - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py index 7eb5df3cc68f..143a79bfa266 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -108,7 +109,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """mixed_properties_and_additional_properties_class.MixedPropertiesAndAdditionalPropertiesClass - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/model200_response.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/model200_response.py index 4eb1672966ae..0c3885120210 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/model200_response.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/model200_response.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -101,7 +102,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """model200_response.Model200Response - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/model_return.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/model_return.py index 740c8e140563..75c3cea6318b 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/model_return.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/model_return.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """model_return.ModelReturn - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/name.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/name.py index c85f89a118c6..db81ae16916d 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/name.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/name.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/nullable_class.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/nullable_class.py index 1fad5bd94e72..c97b8227cde6 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/nullable_class.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/nullable_class.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -121,7 +122,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """nullable_class.NullableClass - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/number_only.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/number_only.py index a3f20cd4b4b3..0c91e2ae62d0 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/number_only.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/number_only.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """number_only.NumberOnly - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/order.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/order.py index 15c23366e433..673295a8610c 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/order.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/order.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -114,7 +115,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """order.Order - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_composite.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_composite.py index 382e84df2527..d797e2f7d07a 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_composite.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_composite.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -103,7 +104,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """outer_composite.OuterComposite - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum.py index 39e533a3ecf4..ad948db05274 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_default_value.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_default_value.py index 5a05e121f521..789bf4ae86fa 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_default_value.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_default_value.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,7 @@ def __init__(self, value='placed', _check_type=True, _from_server=False, _path_t Args: Keyword Args: - value (str): defaults to 'placed', must be one of ['placed'] # noqa: E501 + value (str): defaults to 'placed', must be one of ["placed", "approved", "delivered", ] # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_integer.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_integer.py index b2d55e484b9c..a6323a7fc0ea 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_integer.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_integer.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_integer_default_value.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_integer_default_value.py index 7a3b77cb8240..1098c6494504 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_integer_default_value.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/outer_enum_integer_default_value.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,7 @@ def __init__(self, value=0, _check_type=True, _from_server=False, _path_to_item= Args: Keyword Args: - value (int): defaults to 0, must be one of [0] # noqa: E501 + value (int): defaults to 0, must be one of [0, 1, 2, ] # noqa: E501 _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be raised if the wrong type is input. diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/pet.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/pet.py index 1682c3cb51b2..74cd8afef1af 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/pet.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/pet.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/read_only_first.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/read_only_first.py index 6a18e6331f61..329ec017d435 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/read_only_first.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/read_only_first.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -101,7 +102,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """read_only_first.ReadOnlyFirst - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/special_model_name.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/special_model_name.py index 006f9454b854..d4ffc608a579 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/special_model_name.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/special_model_name.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -99,7 +100,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """special_model_name.SpecialModelName - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py index d7b0b0a94501..7f797f5f1b5d 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/string_boolean_map.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -97,7 +98,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """string_boolean_map.StringBooleanMap - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/tag.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/tag.py index 8585d19c710b..8ffba1b13071 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/tag.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/tag.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -101,7 +102,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """tag.Tag - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/user.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/user.py index 3776e7e7f3f8..3b2eeb54b3d9 100644 --- a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/user.py +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/user.py @@ -15,6 +15,7 @@ import sys # noqa: F401 import six # noqa: F401 +import nulltype # noqa: F401 from petstore_api.model_utils import ( # noqa: F401 ModelComposed, @@ -113,7 +114,6 @@ def _composed_schemas(): def __init__(self, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 """user.User - a model defined in OpenAPI - Keyword Args: _check_type (bool): if True, values for parameters in openapi_types will be type checked and a TypeError will be diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/whale.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/whale.py new file mode 100644 index 000000000000..0c166e663015 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/whale.py @@ -0,0 +1,142 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 +import nulltype # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class Whale(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def openapi_types(): + """ + This must be a class method so a model may have properties that are + of type self, this ensures that we don't create a cyclic import + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'class_name': (str,), # noqa: E501 + 'has_baleen': (bool,), # noqa: E501 + 'has_teeth': (bool,), # noqa: E501 + } + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'has_baleen': 'hasBaleen', # noqa: E501 + 'has_teeth': 'hasTeeth', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """whale.Whale - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + has_baleen (bool): [optional] # noqa: E501 + has_teeth (bool): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + self.class_name = class_name + for var_name, var_value in six.iteritems(kwargs): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) diff --git a/samples/openapi3/client/petstore/python-experimental/petstore_api/models/zebra.py b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/zebra.py new file mode 100644 index 000000000000..56c0b34c2672 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/petstore_api/models/zebra.py @@ -0,0 +1,144 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import +import re # noqa: F401 +import sys # noqa: F401 + +import six # noqa: F401 +import nulltype # noqa: F401 + +from petstore_api.model_utils import ( # noqa: F401 + ModelComposed, + ModelNormal, + ModelSimple, + date, + datetime, + file_type, + int, + none_type, + str, + validate_get_composed_info, +) + + +class Zebra(ModelNormal): + """NOTE: This class is auto generated by OpenAPI Generator. + Ref: https://openapi-generator.tech + + Do not edit the class manually. + + Attributes: + allowed_values (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + with a capitalized key describing the allowed value and an allowed + value. These dicts store the allowed enum values. + attribute_map (dict): The key is attribute name + and the value is json key in definition. + discriminator_value_class_map (dict): A dict to go from the discriminator + variable value to the discriminator class name. + validations (dict): The key is the tuple path to the attribute + and the for var_name this is (var_name,). The value is a dict + that stores validations for max_length, min_length, max_items, + min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, + inclusive_minimum, and regex. + additional_properties_type (tuple): A tuple of classes accepted + as additional properties values. + """ + + allowed_values = { + ('type',): { + 'PLAINS': "plains", + 'MOUNTAIN': "mountain", + 'GREVYS': "grevys", + }, + } + + validations = { + } + + additional_properties_type = None + + @staticmethod + def openapi_types(): + """ + This must be a class method so a model may have properties that are + of type self, this ensures that we don't create a cyclic import + + Returns + openapi_types (dict): The key is attribute name + and the value is attribute type. + """ + return { + 'class_name': (str,), # noqa: E501 + 'type': (str,), # noqa: E501 + } + + @staticmethod + def discriminator(): + return None + + attribute_map = { + 'class_name': 'className', # noqa: E501 + 'type': 'type', # noqa: E501 + } + + @staticmethod + def _composed_schemas(): + return None + + required_properties = set([ + '_data_store', + '_check_type', + '_from_server', + '_path_to_item', + '_configuration', + ]) + + def __init__(self, class_name, _check_type=True, _from_server=False, _path_to_item=(), _configuration=None, **kwargs): # noqa: E501 + """zebra.Zebra - a model defined in OpenAPI + + Args: + class_name (str): + + Keyword Args: + _check_type (bool): if True, values for parameters in openapi_types + will be type checked and a TypeError will be + raised if the wrong type is input. + Defaults to True + _path_to_item (tuple/list): This is a list of keys or values to + drill down to the model in received_data + when deserializing a response + _from_server (bool): True if the data is from the server + False if the data is from the client (default) + _configuration (Configuration): the instance to use when + deserializing a file_type parameter. + If passed, type conversion is attempted + If omitted no type conversion is done. + type (str): [optional] # noqa: E501 + """ + + self._data_store = {} + self._check_type = _check_type + self._from_server = _from_server + self._path_to_item = _path_to_item + self._configuration = _configuration + + self.class_name = class_name + for var_name, var_value in six.iteritems(kwargs): + if var_name not in self.attribute_map and \ + self._configuration is not None and \ + self._configuration.discard_unknown_keys and \ + self.additional_properties_type is None: + # discard variable. + continue + setattr(self, var_name, var_value) diff --git a/samples/openapi3/client/petstore/python-experimental/requirements.txt b/samples/openapi3/client/petstore/python-experimental/requirements.txt index eb358efd5bd3..a56bedffbf57 100644 --- a/samples/openapi3/client/petstore/python-experimental/requirements.txt +++ b/samples/openapi3/client/petstore/python-experimental/requirements.txt @@ -1,3 +1,4 @@ +nulltype certifi >= 14.05.14 future; python_version<="2.7" six >= 1.10 diff --git a/samples/openapi3/client/petstore/python-experimental/setup.py b/samples/openapi3/client/petstore/python-experimental/setup.py index 47c8b2787925..261bc12d34ba 100644 --- a/samples/openapi3/client/petstore/python-experimental/setup.py +++ b/samples/openapi3/client/petstore/python-experimental/setup.py @@ -26,6 +26,7 @@ "six >= 1.10", "certifi", "python-dateutil", + "nulltype", "pem>=19.3.0", "pycryptodome>=3.9.0", ] diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_apple.py b/samples/openapi3/client/petstore/python-experimental/test/test_apple.py new file mode 100644 index 000000000000..100866918919 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_apple.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestApple(unittest.TestCase): + """Apple unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testApple(self): + """Test Apple""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.Apple() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_apple_req.py b/samples/openapi3/client/petstore/python-experimental/test/test_apple_req.py new file mode 100644 index 000000000000..4cb5abcdede4 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_apple_req.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestAppleReq(unittest.TestCase): + """AppleReq unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testAppleReq(self): + """Test AppleReq""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.AppleReq() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_banana.py b/samples/openapi3/client/petstore/python-experimental/test/test_banana.py new file mode 100644 index 000000000000..6efdcd07da1c --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_banana.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestBanana(unittest.TestCase): + """Banana unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testBanana(self): + """Test Banana""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.Banana() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_banana_req.py b/samples/openapi3/client/petstore/python-experimental/test/test_banana_req.py new file mode 100644 index 000000000000..5eeb0bc57c21 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_banana_req.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestBananaReq(unittest.TestCase): + """BananaReq unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testBananaReq(self): + """Test BananaReq""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.BananaReq() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_fruit.py b/samples/openapi3/client/petstore/python-experimental/test/test_fruit.py new file mode 100644 index 000000000000..ee32229a8bbd --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_fruit.py @@ -0,0 +1,175 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestFruit(unittest.TestCase): + """Fruit unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testFruit(self): + """Test Fruit""" + + # make an instance of Fruit, a composed schema oneOf model + # banana test + length_cm = 20.3 + color = 'yellow' + fruit = petstore_api.Fruit(length_cm=length_cm, color=color) + # check its properties + self.assertEqual(fruit.length_cm, length_cm) + self.assertEqual(fruit['length_cm'], length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), length_cm) + self.assertEqual(fruit.color, color) + self.assertEqual(fruit['color'], color) + self.assertEqual(getattr(fruit, 'color'), color) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'length_cm': length_cm, + 'color': color + } + ) + # setting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(petstore_api.ApiKeyError): + fruit['invalid_variable'] = 'some value' + # with setattr + with self.assertRaises(petstore_api.ApiKeyError): + setattr(fruit, 'invalid_variable', 'some value') + + # getting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(petstore_api.ApiKeyError): + invalid_variable = fruit['cultivar'] + # with getattr + with self.assertRaises(petstore_api.ApiKeyError): + invalid_variable = getattr(fruit, 'cultivar', 'some value') + + # make sure that the ModelComposed class properties are correct + # model.composed_schemas() stores the anyOf/allOf/oneOf info + self.assertEqual( + fruit._composed_schemas(), + { + 'anyOf': [], + 'allOf': [], + 'oneOf': [ + petstore_api.Apple, + petstore_api.Banana, + ], + } + ) + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas() + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == petstore_api.Banana: + banana_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [banana_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'color': [fruit], + 'length_cm': [fruit, banana_instance], + 'cultivar': [fruit], + } + ) + # model._additional_properties_model_instances stores a list of + # models which have the property additional_properties_type != None + self.assertEqual( + fruit._additional_properties_model_instances, [] + ) + + # if we modify one of the properties owned by multiple + # model_instances we get an exception when we try to access that + # property because the retrieved values are not all the same + banana_instance.length_cm = 4.56 + with self.assertRaises(petstore_api.ApiValueError): + some_length_cm = fruit.length_cm + + # including extra parameters raises an exception + with self.assertRaises(petstore_api.ApiValueError): + fruit = petstore_api.Fruit( + color=color, + length_cm=length_cm, + unknown_property='some value' + ) + + # including input parameters for two oneOf instances raise an exception + with self.assertRaises(petstore_api.ApiValueError): + fruit = petstore_api.Fruit( + length_cm=length_cm, + cultivar='granny smith' + ) + + # make an instance of Fruit, a composed schema oneOf model + # apple test + color = 'red' + cultivar = 'golden delicious' + fruit = petstore_api.Fruit(color=color, cultivar=cultivar) + # check its properties + self.assertEqual(fruit.color, color) + self.assertEqual(fruit['color'], color) + self.assertEqual(getattr(fruit, 'color'), color) + self.assertEqual(fruit.cultivar, cultivar) + self.assertEqual(fruit['cultivar'], cultivar) + self.assertEqual(getattr(fruit, 'cultivar'), cultivar) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'color': color, + 'cultivar': cultivar + } + ) + + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas() + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == petstore_api.Apple: + apple_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [apple_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'color': [fruit], + 'length_cm': [fruit], + 'cultivar': [fruit, apple_instance], + } + ) + # model._additional_properties_model_instances stores a list of + # models which have the property additional_properties_type != None + self.assertEqual( + fruit._additional_properties_model_instances, [] + ) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_fruit_req.py b/samples/openapi3/client/petstore/python-experimental/test/test_fruit_req.py new file mode 100644 index 000000000000..2fa26fac0aa5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_fruit_req.py @@ -0,0 +1,166 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestFruitReq(unittest.TestCase): + """FruitReq unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testFruitReq(self): + """Test FruitReq""" + + # make an instance of Fruit, a composed schema oneOf model + # banana test + length_cm = 20.3 + fruit = petstore_api.FruitReq(length_cm=length_cm) + # check its properties + self.assertEqual(fruit.length_cm, length_cm) + self.assertEqual(fruit['length_cm'], length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), length_cm) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'length_cm': length_cm, + } + ) + # setting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(petstore_api.ApiKeyError): + fruit['invalid_variable'] = 'some value' + # with setattr + with self.assertRaises(petstore_api.ApiKeyError): + setattr(fruit, 'invalid_variable', 'some value') + + # getting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(petstore_api.ApiKeyError): + invalid_variable = fruit['cultivar'] + # with getattr + with self.assertRaises(petstore_api.ApiKeyError): + invalid_variable = getattr(fruit, 'cultivar', 'some value') + + # make sure that the ModelComposed class properties are correct + # model.composed_schemas() stores the anyOf/allOf/oneOf info + self.assertEqual( + fruit._composed_schemas(), + { + 'anyOf': [], + 'allOf': [], + 'oneOf': [ + petstore_api.AppleReq, + petstore_api.BananaReq, + ], + } + ) + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas() + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == petstore_api.BananaReq: + banana_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [banana_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'length_cm': [fruit, banana_instance], + 'cultivar': [fruit], + 'mealy': [fruit], + 'sweet': [fruit, banana_instance], + } + ) + # model._additional_properties_model_instances stores a list of + # models which have the property additional_properties_type != None + self.assertEqual( + fruit._additional_properties_model_instances, [] + ) + + # if we modify one of the properties owned by multiple + # model_instances we get an exception when we try to access that + # property because the retrieved values are not all the same + banana_instance.length_cm = 4.56 + with self.assertRaises(petstore_api.ApiValueError): + some_length_cm = fruit.length_cm + + # including extra parameters raises an exception + with self.assertRaises(petstore_api.ApiValueError): + fruit = petstore_api.FruitReq( + length_cm=length_cm, + unknown_property='some value' + ) + + # including input parameters for two oneOf instances raise an exception + with self.assertRaises(petstore_api.ApiValueError): + fruit = petstore_api.FruitReq( + length_cm=length_cm, + cultivar='granny smith' + ) + + # make an instance of Fruit, a composed schema oneOf model + # apple test + cultivar = 'golden delicious' + fruit = petstore_api.FruitReq(cultivar=cultivar) + # check its properties + self.assertEqual(fruit.cultivar, cultivar) + self.assertEqual(fruit['cultivar'], cultivar) + self.assertEqual(getattr(fruit, 'cultivar'), cultivar) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'cultivar': cultivar + } + ) + + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas() + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == petstore_api.AppleReq: + apple_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [apple_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'length_cm': [fruit], + 'cultivar': [fruit, apple_instance], + 'mealy': [fruit, apple_instance], + 'sweet': [fruit], + } + ) + # model._additional_properties_model_instances stores a list of + # models which have the property additional_properties_type != None + self.assertEqual( + fruit._additional_properties_model_instances, [] + ) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_gm_fruit.py b/samples/openapi3/client/petstore/python-experimental/test/test_gm_fruit.py new file mode 100644 index 000000000000..dd9605bd8a1b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_gm_fruit.py @@ -0,0 +1,208 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestGmFruit(unittest.TestCase): + """GmFruit unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testGmFruit(self): + """Test GmFruit""" + + # make an instance of GmFruit, a composed schema anyOf model + # banana test + length_cm = 20.3 + color = 'yellow' + fruit = petstore_api.GmFruit(length_cm=length_cm, color=color) + # check its properties + self.assertEqual(fruit.length_cm, length_cm) + self.assertEqual(fruit['length_cm'], length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), length_cm) + self.assertEqual(fruit.color, color) + self.assertEqual(fruit['color'], color) + self.assertEqual(getattr(fruit, 'color'), color) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'length_cm': length_cm, + 'color': color + } + ) + # setting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(petstore_api.ApiKeyError): + fruit['invalid_variable'] = 'some value' + # with setattr + with self.assertRaises(petstore_api.ApiKeyError): + setattr(fruit, 'invalid_variable', 'some value') + + # getting a value that doesn't exist raises an exception + # with a key + with self.assertRaises(petstore_api.ApiKeyError): + invalid_variable = fruit['cultivar'] + # with getattr + with self.assertRaises(petstore_api.ApiKeyError): + invalid_variable = getattr(fruit, 'cultivar', 'some value') + + # make sure that the ModelComposed class properties are correct + # model.composed_schemas() stores the anyOf/allOf/oneOf info + self.assertEqual( + fruit._composed_schemas(), + { + 'anyOf': [ + petstore_api.Apple, + petstore_api.Banana, + ], + 'allOf': [], + 'oneOf': [], + } + ) + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas() + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == petstore_api.Banana: + banana_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [banana_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'color': [fruit], + 'length_cm': [fruit, banana_instance], + 'cultivar': [fruit], + } + ) + # model._additional_properties_model_instances stores a list of + # models which have the property additional_properties_type != None + self.assertEqual( + fruit._additional_properties_model_instances, [] + ) + + # if we modify one of the properties owned by multiple + # model_instances we get an exception when we try to access that + # property because the retrieved values are not all the same + banana_instance.length_cm = 4.56 + with self.assertRaises(petstore_api.ApiValueError): + some_length_cm = fruit.length_cm + + # including extra parameters raises an exception + with self.assertRaises(petstore_api.ApiValueError): + fruit = petstore_api.GmFruit( + color=color, + length_cm=length_cm, + unknown_property='some value' + ) + + # including input parameters for both anyOf instances works + cultivar = 'banaple' + color = 'orange' + fruit = petstore_api.GmFruit( + color=color, + cultivar=cultivar, + length_cm=length_cm + ) + self.assertEqual(fruit.color, color) + self.assertEqual(fruit['color'], color) + self.assertEqual(getattr(fruit, 'color'), color) + self.assertEqual(fruit.cultivar, cultivar) + self.assertEqual(fruit['cultivar'], cultivar) + self.assertEqual(getattr(fruit, 'cultivar'), cultivar) + self.assertEqual(fruit.length_cm, length_cm) + self.assertEqual(fruit['length_cm'], length_cm) + self.assertEqual(getattr(fruit, 'length_cm'), length_cm) + + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas() + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == petstore_api.Apple: + apple_instance = composed_instance + elif composed_instance.__class__ == petstore_api.Banana: + banana_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [apple_instance, banana_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'color': [fruit], + 'length_cm': [fruit, banana_instance], + 'cultivar': [fruit, apple_instance], + } + ) + + # make an instance of GmFruit, a composed schema anyOf model + # apple test + color = 'red' + cultivar = 'golden delicious' + fruit = petstore_api.GmFruit(color=color, cultivar=cultivar) + # check its properties + self.assertEqual(fruit.color, color) + self.assertEqual(fruit['color'], color) + self.assertEqual(getattr(fruit, 'color'), color) + self.assertEqual(fruit.cultivar, cultivar) + self.assertEqual(fruit['cultivar'], cultivar) + self.assertEqual(getattr(fruit, 'cultivar'), cultivar) + # check the dict representation + self.assertEqual( + fruit.to_dict(), + { + 'color': color, + 'cultivar': cultivar + } + ) + + # model._composed_instances is a list of the instances that were + # made from the anyOf/allOf/OneOf classes in model._composed_schemas() + for composed_instance in fruit._composed_instances: + if composed_instance.__class__ == petstore_api.Apple: + apple_instance = composed_instance + self.assertEqual( + fruit._composed_instances, + [apple_instance] + ) + # model._var_name_to_model_instances maps the variable name to the + # model instances which store that variable + self.assertEqual( + fruit._var_name_to_model_instances, + { + 'color': [fruit], + 'length_cm': [fruit], + 'cultivar': [fruit, apple_instance], + } + ) + # model._additional_properties_model_instances stores a list of + # models which have the property additional_properties_type != None + self.assertEqual( + fruit._additional_properties_model_instances, [] + ) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_mammal.py b/samples/openapi3/client/petstore/python-experimental/test/test_mammal.py new file mode 100644 index 000000000000..1b4f161196e7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_mammal.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestMammal(unittest.TestCase): + """Mammal unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testMammal(self): + """Test Mammal""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.Mammal() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_whale.py b/samples/openapi3/client/petstore/python-experimental/test/test_whale.py new file mode 100644 index 000000000000..35d68f0cda02 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_whale.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestWhale(unittest.TestCase): + """Whale unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testWhale(self): + """Test Whale""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.Whale() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/test/test_zebra.py b/samples/openapi3/client/petstore/python-experimental/test/test_zebra.py new file mode 100644 index 000000000000..6013bd9a9a20 --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/test/test_zebra.py @@ -0,0 +1,37 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + + The version of the OpenAPI document: 1.0.0 + Generated by: https://openapi-generator.tech +""" + + +from __future__ import absolute_import + +import unittest + +import petstore_api + + +class TestZebra(unittest.TestCase): + """Zebra unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def testZebra(self): + """Test Zebra""" + # FIXME: construct object with mandatory attributes with example values + # model = petstore_api.Zebra() # noqa: E501 + pass + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-experimental/tests/test_deserialization.py b/samples/openapi3/client/petstore/python-experimental/tests/test_deserialization.py new file mode 100644 index 000000000000..f1a71a67378b --- /dev/null +++ b/samples/openapi3/client/petstore/python-experimental/tests/test_deserialization.py @@ -0,0 +1,86 @@ +# coding: utf-8 + +# flake8: noqa + +""" +Run the tests. +$ pip install nose (optional) +$ cd OpenAPIPetstore-python +$ nosetests -v +""" +from collections import namedtuple +import json +import os +import time +import unittest +import datetime + +import petstore_api + + +MockResponse = namedtuple('MockResponse', 'data') + + +class DeserializationTests(unittest.TestCase): + + def setUp(self): + self.api_client = petstore_api.ApiClient() + self.deserialize = self.api_client.deserialize + + def test_deserialize_animal(self): + """ + deserialize Animal to a Dog instance + Animal uses a discriminator which has a map built of child classes + that inherrit from Animal + This is the swagger (v2) way of doing something like oneOf composition + """ + class_name = 'Dog' + color = 'white' + breed = 'Jack Russel Terrier' + data = { + 'className': class_name, + 'color': color, + 'breed': breed + } + response = MockResponse(data=json.dumps(data)) + + deserialized = self.deserialize(response, (petstore_api.Animal,), True) + self.assertTrue(isinstance(deserialized, petstore_api.Dog)) + self.assertEqual(deserialized.class_name, class_name) + self.assertEqual(deserialized.color, color) + self.assertEqual(deserialized.breed, breed) + + def test_deserialize_mammal(self): + """ + deserialize mammal + mammal is a oneOf composed schema model with discriminator + """ + + # whale test + has_baleen = True + has_teeth = False + class_name = 'whale' + data = { + 'hasBaleen': has_baleen, + 'hasTeeth': has_teeth, + 'className': class_name + } + response = MockResponse(data=json.dumps(data)) + deserialized = self.deserialize(response, (petstore_api.Mammal,), True) + self.assertTrue(isinstance(deserialized, petstore_api.Whale)) + self.assertEqual(deserialized.has_baleen, has_baleen) + self.assertEqual(deserialized.has_teeth, has_teeth) + self.assertEqual(deserialized.class_name, class_name) + + # zebra test + zebra_type = 'plains' + class_name = 'zebra' + data = { + 'type': zebra_type, + 'className': class_name + } + response = MockResponse(data=json.dumps(data)) + deserialized = self.deserialize(response, (petstore_api.Mammal,), True) + self.assertTrue(isinstance(deserialized, petstore_api.Zebra)) + self.assertEqual(deserialized.type, zebra_type) + self.assertEqual(deserialized.class_name, class_name) \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python-experimental/tests/test_http_signature.py b/samples/openapi3/client/petstore/python-experimental/tests/test_http_signature.py index c6c7c5e9bc11..0ef089cfff51 100644 --- a/samples/openapi3/client/petstore/python-experimental/tests/test_http_signature.py +++ b/samples/openapi3/client/petstore/python-experimental/tests/test_http_signature.py @@ -192,57 +192,73 @@ def _validate_authorization_header(self, request_target, actual_headers, authori class PetApiTests(unittest.TestCase): - def setUp(self): - self.setUpModels() - self.setUpFiles() - - - def setUpModels(self): - self.category = petstore_api.Category() - self.category.id = id_gen() - self.category.name = "dog" - self.tag = petstore_api.Tag() - self.tag.id = id_gen() - self.tag.name = "python-pet-tag" - self.pet = petstore_api.Pet(name="hello kity", photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"]) - self.pet.id = id_gen() - self.pet.status = "sold" - self.pet.category = self.category - self.pet.tags = [self.tag] - - def setUpFiles(self): - self.test_file_dir = os.path.join(os.path.dirname(__file__), "..", "testfiles") - self.test_file_dir = os.path.realpath(self.test_file_dir) - if not os.path.exists(self.test_file_dir): - os.mkdir(self.test_file_dir) - - self.private_key_passphrase = 'test-passphrase' - self.rsa_key_path = os.path.join(self.test_file_dir, 'rsa.pem') - self.rsa4096_key_path = os.path.join(self.test_file_dir, 'rsa4096.pem') - self.ec_p521_key_path = os.path.join(self.test_file_dir, 'ecP521.pem') - - if not os.path.exists(self.rsa_key_path): - with open(self.rsa_key_path, 'w') as f: + @classmethod + def setUpClass(cls): + cls.setUpModels() + cls.setUpFiles() + + @classmethod + def tearDownClass(cls): + file_paths = [ + cls.rsa_key_path, + cls.rsa4096_key_path, + cls.ec_p521_key_path, + ] + for file_path in file_paths: + os.unlink(file_path) + + @classmethod + def setUpModels(cls): + cls.category = petstore_api.Category() + cls.category.id = id_gen() + cls.category.name = "dog" + cls.tag = petstore_api.Tag() + cls.tag.id = id_gen() + cls.tag.name = "python-pet-tag" + cls.pet = petstore_api.Pet( + name="hello kity", + photo_urls=["http://foo.bar.com/1", "http://foo.bar.com/2"] + ) + cls.pet.id = id_gen() + cls.pet.status = "sold" + cls.pet.category = cls.category + cls.pet.tags = [cls.tag] + + @classmethod + def setUpFiles(cls): + cls.test_file_dir = os.path.join( + os.path.dirname(__file__), "..", "testfiles") + cls.test_file_dir = os.path.realpath(cls.test_file_dir) + if not os.path.exists(cls.test_file_dir): + os.mkdir(cls.test_file_dir) + + cls.private_key_passphrase = 'test-passphrase' + cls.rsa_key_path = os.path.join(cls.test_file_dir, 'rsa.pem') + cls.rsa4096_key_path = os.path.join(cls.test_file_dir, 'rsa4096.pem') + cls.ec_p521_key_path = os.path.join(cls.test_file_dir, 'ecP521.pem') + + if not os.path.exists(cls.rsa_key_path): + with open(cls.rsa_key_path, 'w') as f: f.write(RSA_TEST_PRIVATE_KEY) - if not os.path.exists(self.rsa4096_key_path): + if not os.path.exists(cls.rsa4096_key_path): key = RSA.generate(4096) private_key = key.export_key( - passphrase=self.private_key_passphrase, + passphrase=cls.private_key_passphrase, protection='PEM' ) - with open(self.rsa4096_key_path, "wb") as f: + with open(cls.rsa4096_key_path, "wb") as f: f.write(private_key) - if not os.path.exists(self.ec_p521_key_path): + if not os.path.exists(cls.ec_p521_key_path): key = ECC.generate(curve='P-521') private_key = key.export_key( format='PEM', - passphrase=self.private_key_passphrase, + passphrase=cls.private_key_passphrase, use_pkcs8=True, protection='PBKDF2WithHMAC-SHA1AndAES128-CBC' ) - with open(self.ec_p521_key_path, "wt") as f: + with open(cls.ec_p521_key_path, "wt") as f: f.write(private_key) def test_valid_http_signature(self): diff --git a/samples/openapi3/client/petstore/ruby-faraday/.rubocop.yml b/samples/openapi3/client/petstore/ruby-faraday/.rubocop.yml index 0ef33ce5e322..df46058490d0 100644 --- a/samples/openapi3/client/petstore/ruby-faraday/.rubocop.yml +++ b/samples/openapi3/client/petstore/ruby-faraday/.rubocop.yml @@ -14,12 +14,6 @@ AllCops: Style/AndOr: Enabled: true -# Do not use braces for hash literals when they are the last argument of a -# method call. -Style/BracesAroundHashParameters: - Enabled: true - EnforcedStyle: context_dependent - # Align `when` with `case`. Layout/CaseIndentation: Enabled: true @@ -46,7 +40,7 @@ Layout/EmptyLinesAroundMethodBody: Layout/EmptyLinesAroundModuleBody: Enabled: true -Layout/IndentFirstArgument: +Layout/FirstArgumentIndentation: Enabled: true # Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. @@ -57,7 +51,7 @@ Style/HashSyntax: # extra level of indentation. Layout/IndentationConsistency: Enabled: true - EnforcedStyle: rails + EnforcedStyle: indented_internal_methods # Two spaces, no tabs (for indentation). Layout/IndentationWidth: @@ -123,7 +117,7 @@ Layout/Tab: Enabled: true # Blank lines should not have any spaces. -Layout/TrailingBlankLines: +Layout/TrailingEmptyLines: Enabled: true # No trailing whitespace. @@ -131,7 +125,7 @@ Layout/TrailingWhitespace: Enabled: false # Use quotes for string literals when they are enough. -Style/UnneededPercentQ: +Style/RedundantPercentQ: Enabled: true # Align `end` with the matching keyword or starting expression except for diff --git a/samples/openapi3/client/petstore/ruby-faraday/Gemfile b/samples/openapi3/client/petstore/ruby-faraday/Gemfile index 69255e559f7c..c2e3127cdcfe 100644 --- a/samples/openapi3/client/petstore/ruby-faraday/Gemfile +++ b/samples/openapi3/client/petstore/ruby-faraday/Gemfile @@ -3,7 +3,7 @@ source 'https://rubygems.org' gemspec group :development, :test do - gem 'rake', '~> 12.0.0' + gem 'rake', '~> 13.0.1' gem 'pry-byebug' gem 'rubocop', '~> 0.66.0' end diff --git a/samples/openapi3/client/petstore/ruby-faraday/spec/api_client_spec.rb b/samples/openapi3/client/petstore/ruby-faraday/spec/api_client_spec.rb index bd7d495672bf..958e570057e6 100644 --- a/samples/openapi3/client/petstore/ruby-faraday/spec/api_client_spec.rb +++ b/samples/openapi3/client/petstore/ruby-faraday/spec/api_client_spec.rb @@ -118,7 +118,7 @@ end it 'fails for invalid collection format' do - expect{api_client.build_collection_param(param, :INVALID)}.to raise_error(RuntimeError, 'unknown collection format: :INVALID') + expect { api_client.build_collection_param(param, :INVALID) }.to raise_error(RuntimeError, 'unknown collection format: :INVALID') end end diff --git a/samples/openapi3/client/petstore/ruby/.rubocop.yml b/samples/openapi3/client/petstore/ruby/.rubocop.yml index 0ef33ce5e322..df46058490d0 100644 --- a/samples/openapi3/client/petstore/ruby/.rubocop.yml +++ b/samples/openapi3/client/petstore/ruby/.rubocop.yml @@ -14,12 +14,6 @@ AllCops: Style/AndOr: Enabled: true -# Do not use braces for hash literals when they are the last argument of a -# method call. -Style/BracesAroundHashParameters: - Enabled: true - EnforcedStyle: context_dependent - # Align `when` with `case`. Layout/CaseIndentation: Enabled: true @@ -46,7 +40,7 @@ Layout/EmptyLinesAroundMethodBody: Layout/EmptyLinesAroundModuleBody: Enabled: true -Layout/IndentFirstArgument: +Layout/FirstArgumentIndentation: Enabled: true # Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. @@ -57,7 +51,7 @@ Style/HashSyntax: # extra level of indentation. Layout/IndentationConsistency: Enabled: true - EnforcedStyle: rails + EnforcedStyle: indented_internal_methods # Two spaces, no tabs (for indentation). Layout/IndentationWidth: @@ -123,7 +117,7 @@ Layout/Tab: Enabled: true # Blank lines should not have any spaces. -Layout/TrailingBlankLines: +Layout/TrailingEmptyLines: Enabled: true # No trailing whitespace. @@ -131,7 +125,7 @@ Layout/TrailingWhitespace: Enabled: false # Use quotes for string literals when they are enough. -Style/UnneededPercentQ: +Style/RedundantPercentQ: Enabled: true # Align `end` with the matching keyword or starting expression except for diff --git a/samples/openapi3/client/petstore/ruby/Gemfile b/samples/openapi3/client/petstore/ruby/Gemfile index 69255e559f7c..c2e3127cdcfe 100644 --- a/samples/openapi3/client/petstore/ruby/Gemfile +++ b/samples/openapi3/client/petstore/ruby/Gemfile @@ -3,7 +3,7 @@ source 'https://rubygems.org' gemspec group :development, :test do - gem 'rake', '~> 12.0.0' + gem 'rake', '~> 13.0.1' gem 'pry-byebug' gem 'rubocop', '~> 0.66.0' end diff --git a/samples/openapi3/client/petstore/ruby/spec/api_client_spec.rb b/samples/openapi3/client/petstore/ruby/spec/api_client_spec.rb index bef4a88a2e3b..4e2d9c5b69bc 100644 --- a/samples/openapi3/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/openapi3/client/petstore/ruby/spec/api_client_spec.rb @@ -156,7 +156,7 @@ end it 'fails for invalid collection format' do - expect{api_client.build_collection_param(param, :INVALID)}.to raise_error(RuntimeError, 'unknown collection format: :INVALID') + expect { api_client.build_collection_param(param, :INVALID) }.to raise_error(RuntimeError, 'unknown collection format: :INVALID') end end diff --git a/samples/openapi3/client/petstore/scala-sttp/.openapi-generator-ignore b/samples/openapi3/client/petstore/scala-sttp/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/openapi3/client/petstore/scala-sttp/.openapi-generator/VERSION b/samples/openapi3/client/petstore/scala-sttp/.openapi-generator/VERSION new file mode 100644 index 000000000000..bfbf77eb7fad --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/scala-sttp/README.md b/samples/openapi3/client/petstore/scala-sttp/README.md new file mode 100644 index 000000000000..c745a7ecee88 --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/README.md @@ -0,0 +1,121 @@ +# 'scala-sttp-petstore' + +OpenAPI Petstore +- API version: 1.0.0 + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: +1. Java 1.7+ +2. Maven/Gradle/SBT + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + 'scala-sttp-petstore' + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "org.openapitools:'scala-sttp-petstore':1.0.0" +``` + +### SBT users + +```scala +libraryDependencies += "org.openapitools" % "'scala-sttp-petstore'" % "1.0.0" +``` + +## Getting Started + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | **addPet** | **POST** /pet | Add a new pet to the store +*PetApi* | **deletePet** | **DELETE** /pet/${petId} | Deletes a pet +*PetApi* | **findPetsByStatus** | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | **findPetsByTags** | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | **getPetById** | **GET** /pet/${petId} | Find pet by ID +*PetApi* | **updatePet** | **PUT** /pet | Update an existing pet +*PetApi* | **updatePetWithForm** | **POST** /pet/${petId} | Updates a pet in the store with form data +*PetApi* | **uploadFile** | **POST** /pet/${petId}/uploadImage | uploads an image +*StoreApi* | **deleteOrder** | **DELETE** /store/order/${orderId} | Delete purchase order by ID +*StoreApi* | **getInventory** | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | **getOrderById** | **GET** /store/order/${orderId} | Find purchase order by ID +*StoreApi* | **placeOrder** | **POST** /store/order | Place an order for a pet +*UserApi* | **createUser** | **POST** /user | Create user +*UserApi* | **createUsersWithArrayInput** | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | **createUsersWithListInput** | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | **deleteUser** | **DELETE** /user/${username} | Delete user +*UserApi* | **getUserByName** | **GET** /user/${username} | Get user by user name +*UserApi* | **loginUser** | **GET** /user/login | Logs user into the system +*UserApi* | **logoutUser** | **GET** /user/logout | Logs out current logged in user session +*UserApi* | **updateUser** | **PUT** /user/${username} | Updated user + + +## Documentation for Models + + - [ApiResponse](ApiResponse.md) + - [Category](Category.md) + - [InlineObject](InlineObject.md) + - [InlineObject1](InlineObject1.md) + - [Order](Order.md) + - [Pet](Pet.md) + - [Tag](Tag.md) + - [User](User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### auth_cookie + +- **Type**: API key +- **API key parameter name**: AUTH_KEY +- **Location**: + + +## Author + + + diff --git a/samples/openapi3/client/petstore/scala-sttp/build.sbt b/samples/openapi3/client/petstore/scala-sttp/build.sbt new file mode 100644 index 000000000000..610244cee605 --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/build.sbt @@ -0,0 +1,25 @@ +version := "1.0.0" +name := "'scala-sttp-petstore'" +organization := "org.openapitools" + +scalaVersion := "2.13.0" + +crossScalaVersions := Seq(scalaVersion.value, "2.12.10", "2.11.12") + +libraryDependencies ++= Seq( + "com.softwaremill.sttp.client" %% "core" % "2.0.0", + "com.softwaremill.sttp.client" %% "json4s" % "2.0.0", + "joda-time" % "joda-time" % "2.10.1", + "org.json4s" %% "json4s-jackson" % "3.6.7", + // test dependencies + "org.scalatest" %% "scalatest" % "3.0.8" % Test, + "junit" % "junit" % "4.13" % "test" +) + +scalacOptions := Seq( + "-unchecked", + "-deprecation", + "-feature" +) + +publishArtifact in (Compile, packageDoc) := false \ No newline at end of file diff --git a/samples/openapi3/client/petstore/scala-sttp/pom.xml b/samples/openapi3/client/petstore/scala-sttp/pom.xml new file mode 100644 index 000000000000..6b6a83b21e2d --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + org.openapitools + scalaz-sttp-petstore-client + pom + 1.0-SNAPSHOT + scala-sttp-petstore-client + + + + org.codehaus.mojo + exec-maven-plugin + 1.5.0 + + + sbt-test + integration-test + + exec + + + sbt + + test + + + + + + + + diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/EnumsSerializers.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/EnumsSerializers.scala new file mode 100644 index 000000000000..71ad618e31fb --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/EnumsSerializers.scala @@ -0,0 +1,51 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.api + +import org.openapitools.client.model._ +import org.json4s._ +import scala.reflect.ClassTag + +object EnumsSerializers { + + def all: Seq[Serializer[_]] = Seq[Serializer[_]]() :+ + new EnumNameSerializer(OrderEnums.Status) :+ + new EnumNameSerializer(PetEnums.Status) + + private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E) + extends Serializer[E#Value] { + import JsonDSL._ + + val EnumerationClass: Class[E#Value] = classOf[E#Value] + + def deserialize(implicit format: Formats): + PartialFunction[(TypeInfo, JValue), E#Value] = { + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => + json match { + case JString(value) => + enum.withName(value) + case value => + throw new MappingException(s"Can't convert $value to $EnumerationClass") + } + } + + private[this] def isValid(json: JValue) = json match { + case JString(value) if enum.values.exists(_.toString == value) => true + case _ => false + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case i: E#Value => i.toString + } + } + +} diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala new file mode 100644 index 000000000000..5211d09c9c5c --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/PetApi.scala @@ -0,0 +1,163 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.api + +import org.openapitools.client.model.ApiResponse +import java.io.File +import org.openapitools.client.model.Pet +import org.openapitools.client.core._ +import alias._ +import sttp.client._ +import sttp.model.Method + +object PetApi { + + def apply(baseUrl: String = "http://petstore.swagger.io/v2")(implicit serializer: SttpSerializer) = new PetApi(baseUrl) +} + +class PetApi(baseUrl: String)(implicit serializer: SttpSerializer) { + + import Helpers._ + import serializer._ + + /** + * Expected answers: + * code 200 : Pet (successful operation) + * code 405 : (Invalid input) + * + * @param pet Pet object that needs to be added to the store + */ + def addPet(pet: Pet): ApiRequestT[Pet] = + basicRequest + .method(Method.POST, uri"$baseUrl/pet") + .contentType("application/json") + .body(pet) + .response(asJson[Pet]) + + /** + * Expected answers: + * code 400 : (Invalid pet value) + * + * @param petId Pet id to delete + * @param apiKey + */ + def deletePet(petId: Long, apiKey: Option[String] = None): ApiRequestT[Unit] = + basicRequest + .method(Method.DELETE, uri"$baseUrl/pet/${petId}") + .contentType("application/json") + .header("api_key", apiKey) + .response(asJson[Unit]) + + /** + * Multiple status values can be provided with comma separated strings + * + * Expected answers: + * code 200 : Seq[Pet] (successful operation) + * code 400 : (Invalid status value) + * + * @param status Status values that need to be considered for filter + */ + def findPetsByStatus(status: Seq[String]): ApiRequestT[Seq[Pet]] = + basicRequest + .method(Method.GET, uri"$baseUrl/pet/findByStatus?status=$status") + .contentType("application/json") + .response(asJson[Seq[Pet]]) + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * Expected answers: + * code 200 : Seq[Pet] (successful operation) + * code 400 : (Invalid tag value) + * + * @param tags Tags to filter by + */ + def findPetsByTags(tags: Seq[String]): ApiRequestT[Seq[Pet]] = + basicRequest + .method(Method.GET, uri"$baseUrl/pet/findByTags?tags=$tags") + .contentType("application/json") + .response(asJson[Seq[Pet]]) + + /** + * Returns a single pet + * + * Expected answers: + * code 200 : Pet (successful operation) + * code 400 : (Invalid ID supplied) + * code 404 : (Pet not found) + * + * Available security schemes: + * api_key (apiKey) + * + * @param petId ID of pet to return + */ + def getPetById(petId: Long)(implicit apiKey: ApiKeyValue): ApiRequestT[Pet] = + basicRequest + .method(Method.GET, uri"$baseUrl/pet/${petId}") + .contentType("application/json") + .header("api_key", apiKey.value) + .response(asJson[Pet]) + + /** + * Expected answers: + * code 200 : Pet (successful operation) + * code 400 : (Invalid ID supplied) + * code 404 : (Pet not found) + * code 405 : (Validation exception) + * + * @param pet Pet object that needs to be added to the store + */ + def updatePet(pet: Pet): ApiRequestT[Pet] = + basicRequest + .method(Method.PUT, uri"$baseUrl/pet") + .contentType("application/json") + .body(pet) + .response(asJson[Pet]) + + /** + * Expected answers: + * code 405 : (Invalid input) + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + def updatePetWithForm(petId: Long, name: Option[String] = None, status: Option[String] = None): ApiRequestT[Unit] = + basicRequest + .method(Method.POST, uri"$baseUrl/pet/${petId}") + .contentType("application/x-www-form-urlencoded") + .body(Map( + "name" -> name, + "status" -> status, + )) + .response(asJson[Unit]) + + /** + * Expected answers: + * code 200 : ApiResponse (successful operation) + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): ApiRequestT[ApiResponse] = + basicRequest + .method(Method.POST, uri"$baseUrl/pet/${petId}/uploadImage") + .contentType("multipart/form-data") + .body(Map( + "additionalMetadata" -> additionalMetadata, + "file" -> file, + )) + .response(asJson[ApiResponse]) + +} + diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/StoreApi.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/StoreApi.scala new file mode 100644 index 000000000000..907cc9f42f0f --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/StoreApi.scala @@ -0,0 +1,92 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.api + +import org.openapitools.client.model.Order +import org.openapitools.client.core._ +import alias._ +import sttp.client._ +import sttp.model.Method + +object StoreApi { + + def apply(baseUrl: String = "http://petstore.swagger.io/v2")(implicit serializer: SttpSerializer) = new StoreApi(baseUrl) +} + +class StoreApi(baseUrl: String)(implicit serializer: SttpSerializer) { + + import Helpers._ + import serializer._ + + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * Expected answers: + * code 400 : (Invalid ID supplied) + * code 404 : (Order not found) + * + * @param orderId ID of the order that needs to be deleted + */ + def deleteOrder(orderId: String): ApiRequestT[Unit] = + basicRequest + .method(Method.DELETE, uri"$baseUrl/store/order/${orderId}") + .contentType("application/json") + .response(asJson[Unit]) + + /** + * Returns a map of status codes to quantities + * + * Expected answers: + * code 200 : Map[String, Int] (successful operation) + * + * Available security schemes: + * api_key (apiKey) + */ + def getInventory()(implicit apiKey: ApiKeyValue): ApiRequestT[Map[String, Int]] = + basicRequest + .method(Method.GET, uri"$baseUrl/store/inventory") + .contentType("application/json") + .header("api_key", apiKey.value) + .response(asJson[Map[String, Int]]) + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * Expected answers: + * code 200 : Order (successful operation) + * code 400 : (Invalid ID supplied) + * code 404 : (Order not found) + * + * @param orderId ID of pet that needs to be fetched + */ + def getOrderById(orderId: Long): ApiRequestT[Order] = + basicRequest + .method(Method.GET, uri"$baseUrl/store/order/${orderId}") + .contentType("application/json") + .response(asJson[Order]) + + /** + * Expected answers: + * code 200 : Order (successful operation) + * code 400 : (Invalid Order) + * + * @param order order placed for purchasing the pet + */ + def placeOrder(order: Order): ApiRequestT[Order] = + basicRequest + .method(Method.POST, uri"$baseUrl/store/order") + .contentType("application/json") + .body(order) + .response(asJson[Order]) + +} + diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/UserApi.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/UserApi.scala new file mode 100644 index 000000000000..7b7df3b8e149 --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/api/UserApi.scala @@ -0,0 +1,170 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.api + +import org.openapitools.client.model.User +import org.openapitools.client.core._ +import alias._ +import sttp.client._ +import sttp.model.Method + +object UserApi { + + def apply(baseUrl: String = "http://petstore.swagger.io/v2")(implicit serializer: SttpSerializer) = new UserApi(baseUrl) +} + +class UserApi(baseUrl: String)(implicit serializer: SttpSerializer) { + + import Helpers._ + import serializer._ + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 0 : (successful operation) + * + * Available security schemes: + * auth_cookie (apiKey) + * + * @param user Created user object + */ + def createUser(user: User)(implicit apiKey: ApiKeyValue): ApiRequestT[Unit] = + basicRequest + .method(Method.POST, uri"$baseUrl/user") + .contentType("application/json") + .cookie("AUTH_KEY", apiKey.value) + .body(user) + .response(asJson[Unit]) + + /** + * Expected answers: + * code 0 : (successful operation) + * + * Available security schemes: + * auth_cookie (apiKey) + * + * @param user List of user object + */ + def createUsersWithArrayInput(user: Seq[User])(implicit apiKey: ApiKeyValue): ApiRequestT[Unit] = + basicRequest + .method(Method.POST, uri"$baseUrl/user/createWithArray") + .contentType("application/json") + .cookie("AUTH_KEY", apiKey.value) + .body(user) + .response(asJson[Unit]) + + /** + * Expected answers: + * code 0 : (successful operation) + * + * Available security schemes: + * auth_cookie (apiKey) + * + * @param user List of user object + */ + def createUsersWithListInput(user: Seq[User])(implicit apiKey: ApiKeyValue): ApiRequestT[Unit] = + basicRequest + .method(Method.POST, uri"$baseUrl/user/createWithList") + .contentType("application/json") + .cookie("AUTH_KEY", apiKey.value) + .body(user) + .response(asJson[Unit]) + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 400 : (Invalid username supplied) + * code 404 : (User not found) + * + * Available security schemes: + * auth_cookie (apiKey) + * + * @param username The name that needs to be deleted + */ + def deleteUser(username: String)(implicit apiKey: ApiKeyValue): ApiRequestT[Unit] = + basicRequest + .method(Method.DELETE, uri"$baseUrl/user/${username}") + .contentType("application/json") + .cookie("AUTH_KEY", apiKey.value) + .response(asJson[Unit]) + + /** + * Expected answers: + * code 200 : User (successful operation) + * code 400 : (Invalid username supplied) + * code 404 : (User not found) + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + def getUserByName(username: String): ApiRequestT[User] = + basicRequest + .method(Method.GET, uri"$baseUrl/user/${username}") + .contentType("application/json") + .response(asJson[User]) + + /** + * Expected answers: + * code 200 : String (successful operation) + * Headers : + * Set-Cookie - Cookie authentication key for use with the `auth_cookie` apiKey authentication. + * X-Rate-Limit - calls per hour allowed by the user + * X-Expires-After - date in UTC when toekn expires + * code 400 : (Invalid username/password supplied) + * + * @param username The user name for login + * @param password The password for login in clear text + */ + def loginUser(username: String, password: String): ApiRequestT[String] = + basicRequest + .method(Method.GET, uri"$baseUrl/user/login?username=$username&password=$password") + .contentType("application/json") + .response(asJson[String]) + + /** + * Expected answers: + * code 0 : (successful operation) + * + * Available security schemes: + * auth_cookie (apiKey) + */ + def logoutUser()(implicit apiKey: ApiKeyValue): ApiRequestT[Unit] = + basicRequest + .method(Method.GET, uri"$baseUrl/user/logout") + .contentType("application/json") + .cookie("AUTH_KEY", apiKey.value) + .response(asJson[Unit]) + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 400 : (Invalid user supplied) + * code 404 : (User not found) + * + * Available security schemes: + * auth_cookie (apiKey) + * + * @param username name that need to be deleted + * @param user Updated user object + */ + def updateUser(username: String, user: User)(implicit apiKey: ApiKeyValue): ApiRequestT[Unit] = + basicRequest + .method(Method.PUT, uri"$baseUrl/user/${username}") + .contentType("application/json") + .cookie("AUTH_KEY", apiKey.value) + .body(user) + .response(asJson[Unit]) + +} + diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/ApiInvoker.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/ApiInvoker.scala new file mode 100644 index 000000000000..dc98ff4d1365 --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/ApiInvoker.scala @@ -0,0 +1,60 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.core + +import org.json4s._ +import sttp.client._ +import sttp.model.StatusCode +import org.openapitools.client.api.EnumsSerializers +import sttp.client.json4s.SttpJson4sApi +import sttp.client.monad.MonadError + +class SttpSerializer(implicit val format: Formats = DefaultFormats ++ EnumsSerializers.all ++ Serializers.all, + implicit val serialization: org.json4s.Serialization = org.json4s.jackson.Serialization) extends SttpJson4sApi + +class HttpException(val statusCode: StatusCode, val statusText: String, val message: String) extends Exception(s"[$statusCode] $statusText: $message") + +object Helpers { + + // Helper to handle Optional header parameters + implicit class optionalParams(val request: RequestT[Identity, Either[String, String], Nothing]) extends AnyVal { + def header( header: String, optValue: Option[Any]): RequestT[Identity, Either[String, String], Nothing] = { + optValue.map( value => request.header(header, value.toString)).getOrElse(request) + } + } + +} + +object ApiInvoker { + + /** + * Allows request execution without calling apiInvoker.execute(request) + * request.result can be used to get a monad wrapped content. + * + * @param request the apiRequest to be executed + */ + implicit class ApiRequestImprovements[R[_], T](request: RequestT[Identity, Either[ResponseError[Exception], T], Nothing]) { + + def result(implicit backend: SttpBackend[R, Nothing, Nothing]): R[T] = { + val responseT = request.send() + val ME: MonadError[R] = backend.responseMonad + ME.flatMap(responseT) { + response => + response.body match { + case Left(ex) => ME.error[T](new HttpException(response.code, response.statusText, ex.body)) + case Right(value) => ME.unit(value) + } + } + } + } + +} diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/Serializers.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/Serializers.scala new file mode 100644 index 000000000000..80188ba5e6a1 --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/Serializers.scala @@ -0,0 +1,29 @@ +package org.openapitools.client.core + +import org.joda.time.DateTime +import org.joda.time.format.ISODateTimeFormat +import org.json4s.{Serializer, CustomSerializer, JNull} +import org.json4s.JsonAST.JString + +object Serializers { + + case object DateTimeSerializer extends CustomSerializer[DateTime](_ => ( { + case JString(s) => + ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(s) + case JNull => null + }, { + case d: org.joda.time.DateTime => + JString(ISODateTimeFormat.dateTime().print(d)) + }) + ) + + case object LocalDateSerializer extends CustomSerializer[org.joda.time.LocalDate](_ => ( { + case JString(s) => org.joda.time.format.DateTimeFormat.forPattern("yyyy-MM-dd").parseLocalDate(s) + case JNull => null + }, { + case d: org.joda.time.LocalDate => JString(d.toString("yyyy-MM-dd")) + })) + + def all: Seq[Serializer[_]] = Seq[Serializer[_]]() :+ LocalDateSerializer :+ DateTimeSerializer + +} diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/requests.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/requests.scala new file mode 100644 index 000000000000..1f45be8103e1 --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/core/requests.scala @@ -0,0 +1,58 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.core + +import sttp.client.{Identity, RequestT, ResponseError} + +/** + * This trait needs to be added to any model defined by the api. + */ +trait ApiModel + +/** + * Sttp type aliases + */ +object alias { + type ApiRequestT[T] = RequestT[Identity, Either[ResponseError[Exception], T], Nothing] +} + +/** + * Single trait defining a credential that can be transformed to a paramName / paramValue tupple + */ +sealed trait Credentials { + def asQueryParam: Option[(String, String)] = None +} + +sealed case class BasicCredentials(user: String, password: String) extends Credentials + +sealed case class BearerToken(token: String) extends Credentials + +sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { + override def asQueryParam: Option[(String, String)] = location match { + case ApiKeyLocations.QUERY => Some((keyName, key.value)) + case _ => None + } +} + +sealed case class ApiKeyValue(value: String) + +sealed trait ApiKeyLocation + +object ApiKeyLocations { + + case object QUERY extends ApiKeyLocation + + case object HEADER extends ApiKeyLocation + + case object COOKIE extends ApiKeyLocation + +} diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/ApiResponse.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/ApiResponse.scala new file mode 100644 index 000000000000..3a3b6d6f499a --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/ApiResponse.scala @@ -0,0 +1,26 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.openapitools.client.core.ApiModel + + /** + * An uploaded response + * Describes the result of uploading an image resource + */ +case class ApiResponse( + code: Option[Int] = None, + `type`: Option[String] = None, + message: Option[String] = None +) extends ApiModel + + diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Category.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Category.scala new file mode 100644 index 000000000000..011164617cfb --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Category.scala @@ -0,0 +1,25 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.openapitools.client.core.ApiModel + + /** + * Pet category + * A category for a pet + */ +case class Category( + id: Option[Long] = None, + name: Option[String] = None +) extends ApiModel + + diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/InlineObject.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/InlineObject.scala new file mode 100644 index 000000000000..a8c5493161a1 --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/InlineObject.scala @@ -0,0 +1,23 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.openapitools.client.core.ApiModel + +case class InlineObject( + /* Updated name of the pet */ + name: Option[String] = None, + /* Updated status of the pet */ + status: Option[String] = None +) extends ApiModel + + diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/InlineObject1.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/InlineObject1.scala new file mode 100644 index 000000000000..480cf8c2e10a --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/InlineObject1.scala @@ -0,0 +1,24 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import java.io.File +import org.openapitools.client.core.ApiModel + +case class InlineObject1( + /* Additional data to pass to server */ + additionalMetadata: Option[String] = None, + /* file to upload */ + file: Option[File] = None +) extends ApiModel + + diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Order.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Order.scala new file mode 100644 index 000000000000..b8f11b0b3c38 --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Order.scala @@ -0,0 +1,41 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.joda.time.DateTime +import org.openapitools.client.core.ApiModel + + /** + * Pet Order + * An order for a pets from the pet store + */ +case class Order( + id: Option[Long] = None, + petId: Option[Long] = None, + quantity: Option[Int] = None, + shipDate: Option[DateTime] = None, + /* Order Status */ + status: Option[OrderEnums.Status] = None, + complete: Option[Boolean] = None +) extends ApiModel + +object OrderEnums { + + type Status = Status.Value + object Status extends Enumeration { + val Placed = Value("placed") + val Approved = Value("approved") + val Delivered = Value("delivered") + } + +} + diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Pet.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Pet.scala new file mode 100644 index 000000000000..75b528c3c0a1 --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Pet.scala @@ -0,0 +1,40 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.openapitools.client.core.ApiModel + + /** + * a Pet + * A pet for sale in the pet store + */ +case class Pet( + id: Option[Long] = None, + category: Option[Category] = None, + name: String, + photoUrls: Seq[String], + tags: Option[Seq[Tag]] = None, + /* pet status in the store */ + status: Option[PetEnums.Status] = None +) extends ApiModel + +object PetEnums { + + type Status = Status.Value + object Status extends Enumeration { + val Available = Value("available") + val Pending = Value("pending") + val Sold = Value("sold") + } + +} + diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Tag.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Tag.scala new file mode 100644 index 000000000000..299ee5161a8b --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/Tag.scala @@ -0,0 +1,25 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.openapitools.client.core.ApiModel + + /** + * Pet Tag + * A tag for a pet + */ +case class Tag( + id: Option[Long] = None, + name: Option[String] = None +) extends ApiModel + + diff --git a/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/User.scala b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/User.scala new file mode 100644 index 000000000000..bd2e6c3ba2a7 --- /dev/null +++ b/samples/openapi3/client/petstore/scala-sttp/src/main/scala/org/openapitools/client/model/User.scala @@ -0,0 +1,32 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.openapitools.client.core.ApiModel + + /** + * a User + * A User who is purchasing from the pet store + */ +case class User( + id: Option[Long] = None, + username: Option[String] = None, + firstName: Option[String] = None, + lastName: Option[String] = None, + email: Option[String] = None, + password: Option[String] = None, + phone: Option[String] = None, + /* User Status */ + userStatus: Option[Int] = None +) extends ApiModel + + diff --git a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/controllers/pet_controller.py b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/controllers/pet_controller.py index 9376ab94244c..20b15fabbd98 100644 --- a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/controllers/pet_controller.py +++ b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/controllers/pet_controller.py @@ -3,6 +3,9 @@ from openapi_server.models.api_response import ApiResponse # noqa: E501 from openapi_server.models.pet import Pet # noqa: E501 +from openapi_server.models.pet_form import PetForm # noqa: E501 +from openapi_server.models.status_enum import StatusEnum # noqa: E501 +from openapi_server.models.upload_form import UploadForm # noqa: E501 from openapi_server import util @@ -90,35 +93,52 @@ def update_pet(pet): # noqa: E501 return 'do some magic!' -def update_pet_with_form(pet_id, name=None, status=None): # noqa: E501 +def update_pet_status_with_enum(pet_id, status): # noqa: E501 + """Set the status of a pet in the store using an enum + + # noqa: E501 + + :param pet_id: ID of pet to return + :type pet_id: int + :param status: The required status + :type status: dict | bytes + + :rtype: Pet + """ + if connexion.request.is_json: + status = StatusEnum.from_dict(connexion.request.get_json()) # noqa: E501 + return 'do some magic!' + + +def update_pet_with_form(pet_id, pet_form=None): # noqa: E501 """Updates a pet in the store with form data # noqa: E501 :param pet_id: ID of pet that needs to be updated :type pet_id: int - :param name: Updated name of the pet - :type name: str - :param status: Updated status of the pet - :type status: str + :param pet_form: + :type pet_form: dict | bytes :rtype: None """ + if connexion.request.is_json: + pet_form = PetForm.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' -def upload_file(pet_id, additional_metadata=None, file=None): # noqa: E501 +def upload_file(pet_id, upload_form=None): # noqa: E501 """uploads an image # noqa: E501 :param pet_id: ID of pet to update :type pet_id: int - :param additional_metadata: Additional data to pass to server - :type additional_metadata: str - :param file: file to upload - :type file: str + :param upload_form: + :type upload_form: dict | bytes :rtype: ApiResponse """ + if connexion.request.is_json: + upload_form = UploadForm.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' diff --git a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/controllers/user_controller.py b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/controllers/user_controller.py index 9b9706262121..e897814d4b0d 100644 --- a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/controllers/user_controller.py +++ b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/controllers/user_controller.py @@ -25,7 +25,7 @@ def create_users_with_array_input(user): # noqa: E501 # noqa: E501 - :param user: List of user object + :param user: List of user objects :type user: list | bytes :rtype: None @@ -40,7 +40,7 @@ def create_users_with_list_input(user): # noqa: E501 # noqa: E501 - :param user: List of user object + :param user: List of user objects :type user: list | bytes :rtype: None diff --git a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/__init__.py b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/__init__.py index 689233630d14..bb6f70f1569b 100644 --- a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/__init__.py +++ b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/__init__.py @@ -5,9 +5,10 @@ # import models into model package from openapi_server.models.api_response import ApiResponse from openapi_server.models.category import Category -from openapi_server.models.inline_object import InlineObject -from openapi_server.models.inline_object1 import InlineObject1 from openapi_server.models.order import Order from openapi_server.models.pet import Pet +from openapi_server.models.pet_form import PetForm +from openapi_server.models.status_enum import StatusEnum from openapi_server.models.tag import Tag +from openapi_server.models.upload_form import UploadForm from openapi_server.models.user import User diff --git a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/inline_object.py b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/pet_form.py similarity index 64% rename from samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/inline_object.py rename to samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/pet_form.py index f8fe9cb4af8f..0eac9c1c2696 100644 --- a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/inline_object.py +++ b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/pet_form.py @@ -9,18 +9,18 @@ from openapi_server import util -class InlineObject(Model): +class PetForm(Model): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(self, name=None, status=None): # noqa: E501 - """InlineObject - a model defined in OpenAPI + """PetForm - a model defined in OpenAPI - :param name: The name of this InlineObject. # noqa: E501 + :param name: The name of this PetForm. # noqa: E501 :type name: str - :param status: The status of this InlineObject. # noqa: E501 + :param status: The status of this PetForm. # noqa: E501 :type status: str """ self.openapi_types = { @@ -42,53 +42,57 @@ def from_dict(cls, dikt): :param dikt: A dict. :type: dict - :return: The inline_object of this InlineObject. # noqa: E501 - :rtype: InlineObject + :return: The PetForm of this PetForm. # noqa: E501 + :rtype: PetForm """ return util.deserialize_model(dikt, cls) @property def name(self): - """Gets the name of this InlineObject. + """Gets the name of this PetForm. Updated name of the pet # noqa: E501 - :return: The name of this InlineObject. + :return: The name of this PetForm. :rtype: str """ return self._name @name.setter def name(self, name): - """Sets the name of this InlineObject. + """Sets the name of this PetForm. Updated name of the pet # noqa: E501 - :param name: The name of this InlineObject. + :param name: The name of this PetForm. :type name: str """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def status(self): - """Gets the status of this InlineObject. + """Gets the status of this PetForm. Updated status of the pet # noqa: E501 - :return: The status of this InlineObject. + :return: The status of this PetForm. :rtype: str """ return self._status @status.setter def status(self, status): - """Sets the status of this InlineObject. + """Sets the status of this PetForm. Updated status of the pet # noqa: E501 - :param status: The status of this InlineObject. + :param status: The status of this PetForm. :type status: str """ + if status is None: + raise ValueError("Invalid value for `status`, must not be `None`") # noqa: E501 self._status = status diff --git a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/status_enum.py b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/status_enum.py new file mode 100644 index 000000000000..08bebbe6242f --- /dev/null +++ b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/status_enum.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +from __future__ import absolute_import +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from openapi_server.models.base_model_ import Model +from openapi_server import util + + +class StatusEnum(Model): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + """ + + """ + allowed enum values + """ + AVAILABLE = "available" + PENDING = "pending" + SOLD = "sold" + def __init__(self): # noqa: E501 + """StatusEnum - a model defined in OpenAPI + + """ + self.openapi_types = { + } + + self.attribute_map = { + } + + @classmethod + def from_dict(cls, dikt): + """Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The statusEnum of this StatusEnum. # noqa: E501 + :rtype: StatusEnum + """ + return util.deserialize_model(dikt, cls) diff --git a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/inline_object1.py b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/upload_form.py similarity index 71% rename from samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/inline_object1.py rename to samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/upload_form.py index a3517cf57982..7e91468ae988 100644 --- a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/inline_object1.py +++ b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/models/upload_form.py @@ -9,18 +9,18 @@ from openapi_server import util -class InlineObject1(Model): +class UploadForm(Model): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(self, additional_metadata=None, file=None): # noqa: E501 - """InlineObject1 - a model defined in OpenAPI + """UploadForm - a model defined in OpenAPI - :param additional_metadata: The additional_metadata of this InlineObject1. # noqa: E501 + :param additional_metadata: The additional_metadata of this UploadForm. # noqa: E501 :type additional_metadata: str - :param file: The file of this InlineObject1. # noqa: E501 + :param file: The file of this UploadForm. # noqa: E501 :type file: file """ self.openapi_types = { @@ -42,29 +42,29 @@ def from_dict(cls, dikt): :param dikt: A dict. :type: dict - :return: The inline_object_1 of this InlineObject1. # noqa: E501 - :rtype: InlineObject1 + :return: The UploadForm of this UploadForm. # noqa: E501 + :rtype: UploadForm """ return util.deserialize_model(dikt, cls) @property def additional_metadata(self): - """Gets the additional_metadata of this InlineObject1. + """Gets the additional_metadata of this UploadForm. Additional data to pass to server # noqa: E501 - :return: The additional_metadata of this InlineObject1. + :return: The additional_metadata of this UploadForm. :rtype: str """ return self._additional_metadata @additional_metadata.setter def additional_metadata(self, additional_metadata): - """Sets the additional_metadata of this InlineObject1. + """Sets the additional_metadata of this UploadForm. Additional data to pass to server # noqa: E501 - :param additional_metadata: The additional_metadata of this InlineObject1. + :param additional_metadata: The additional_metadata of this UploadForm. :type additional_metadata: str """ @@ -72,23 +72,25 @@ def additional_metadata(self, additional_metadata): @property def file(self): - """Gets the file of this InlineObject1. + """Gets the file of this UploadForm. file to upload # noqa: E501 - :return: The file of this InlineObject1. + :return: The file of this UploadForm. :rtype: file """ return self._file @file.setter def file(self, file): - """Sets the file of this InlineObject1. + """Sets the file of this UploadForm. file to upload # noqa: E501 - :param file: The file of this InlineObject1. + :param file: The file of this UploadForm. :type file: file """ + if file is None: + raise ValueError("Invalid value for `file`, must not be `None`") # noqa: E501 self._file = file diff --git a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/openapi/openapi.yaml b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/openapi/openapi.yaml index d98eee5eb1bf..142289318ae3 100644 --- a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/openapi/openapi.yaml +++ b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/openapi/openapi.yaml @@ -1,4 +1,4 @@ -openapi: 3.0.0 +openapi: 3.0.1 info: description: This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. @@ -220,6 +220,45 @@ paths: tags: - pet x-openapi-router-controller: openapi_server.controllers.pet_controller + patch: + operationId: update_pet_status_with_enum + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + - description: The required status + example: pending + explode: true + in: query + name: status + required: true + schema: + $ref: '#/components/schemas/statusEnum' + style: form + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + summary: Set the status of a pet in the store using an enum + tags: + - pet + x-openapi-router-controller: openapi_server.controllers.pet_controller post: operationId: update_pet_with_form parameters: @@ -233,18 +272,7 @@ paths: type: integer style: simple requestBody: - $ref: '#/components/requestBodies/inline_object' - content: - application/x-www-form-urlencoded: - schema: - properties: - name: - description: Updated name of the pet - type: string - status: - description: Updated status of the pet - type: string - type: object + $ref: '#/components/requestBodies/PetForm' responses: "405": description: Invalid input @@ -270,19 +298,7 @@ paths: type: integer style: simple requestBody: - $ref: '#/components/requestBodies/inline_object_1' - content: - multipart/form-data: - schema: - properties: - additionalMetadata: - description: Additional data to pass to server - type: string - file: - description: file to upload - format: binary - type: string - type: object + $ref: '#/components/requestBodies/UploadForm' responses: "200": content: @@ -605,6 +621,17 @@ paths: - user x-openapi-router-controller: openapi_server.controllers.user_controller components: + parameters: + statusEnum: + description: The required status + example: pending + explode: true + in: query + name: status + required: true + schema: + $ref: '#/components/schemas/statusEnum' + style: form requestBodies: UserArray: content: @@ -613,7 +640,7 @@ components: items: $ref: '#/components/schemas/User' type: array - description: List of user object + description: List of user objects required: true Pet: content: @@ -625,16 +652,22 @@ components: $ref: '#/components/schemas/Pet' description: Pet object that needs to be added to the store required: true - inline_object: + PetForm: content: application/x-www-form-urlencoded: + example: + name: fluffy + status: available schema: - $ref: '#/components/schemas/inline_object' - inline_object_1: + $ref: '#/components/schemas/PetForm' + UploadForm: content: multipart/form-data: + example: + additionalMetadata: additional metadata example + file: c29tZSB0ZXN0IGRhdGEK schema: - $ref: '#/components/schemas/inline_object_1' + $ref: '#/components/schemas/UploadForm' schemas: Order: description: An order for a pets from the pet store @@ -792,23 +825,8 @@ components: type: object xml: name: Pet - ApiResponse: - description: Describes the result of uploading an image resource - example: - code: 0 - type: type - message: message - properties: - code: - format: int32 - type: integer - type: - type: string - message: - type: string - title: An uploaded response - type: object - inline_object: + PetForm: + description: A form for updating a pet properties: name: description: Updated name of the pet @@ -816,8 +834,13 @@ components: status: description: Updated status of the pet type: string + required: + - name + - status + title: A pet form type: object - inline_object_1: + UploadForm: + description: A form for attaching files to a pet properties: additionalMetadata: description: Additional data to pass to server @@ -826,7 +849,33 @@ components: description: file to upload format: binary type: string + required: + - file + title: An upload form + type: object + ApiResponse: + description: Describes the result of uploading an image resource + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + title: An uploaded response type: object + statusEnum: + description: pet status in the store + enum: + - available + - pending + - sold + type: string securitySchemes: petstore_auth: flows: diff --git a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/test/test_pet_controller.py b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/test/test_pet_controller.py index 0d4565a36786..dc0a8e2deb0b 100644 --- a/samples/openapi3/server/petstore/python-flask-python2/openapi_server/test/test_pet_controller.py +++ b/samples/openapi3/server/petstore/python-flask-python2/openapi_server/test/test_pet_controller.py @@ -8,6 +8,9 @@ from openapi_server.models.api_response import ApiResponse # noqa: E501 from openapi_server.models.pet import Pet # noqa: E501 +from openapi_server.models.pet_form import PetForm # noqa: E501 +from openapi_server.models.status_enum import StatusEnum # noqa: E501 +from openapi_server.models.upload_form import UploadForm # noqa: E501 from openapi_server.test import BaseTestCase @@ -156,23 +159,39 @@ def test_update_pet(self): self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) + def test_update_pet_status_with_enum(self): + """Test case for update_pet_status_with_enum + + Set the status of a pet in the store using an enum + """ + query_string = [('status', pending)] + headers = { + 'Accept': 'application/json', + } + response = self.client.open( + '/v2/pet/{pet_id}'.format(pet_id=789), + method='PATCH', + headers=headers, + query_string=query_string) + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) + @unittest.skip("application/x-www-form-urlencoded not supported by Connexion") def test_update_pet_with_form(self): """Test case for update_pet_with_form Updates a pet in the store with form data """ + pet_form = {"name":"fluffy","status":"available"} headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer special-key', } - data = dict(name='name_example', - status='status_example') response = self.client.open( '/v2/pet/{pet_id}'.format(pet_id=789), method='POST', headers=headers, - data=data, + data=json.dumps(pet_form), content_type='application/x-www-form-urlencoded') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) @@ -183,18 +202,17 @@ def test_upload_file(self): uploads an image """ + upload_form = {"additionalMetadata":"additional metadata example","file":"c29tZSB0ZXN0IGRhdGEK"} headers = { 'Accept': 'application/json', 'Content-Type': 'multipart/form-data', 'Authorization': 'Bearer special-key', } - data = dict(additional_metadata='additional_metadata_example', - file=(BytesIO(b'some file data'), 'file.txt')) response = self.client.open( '/v2/pet/{pet_id}/uploadImage'.format(pet_id=789), method='POST', headers=headers, - data=data, + data=json.dumps(upload_form), content_type='multipart/form-data') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) diff --git a/samples/openapi3/server/petstore/python-flask-python2/requirements.txt b/samples/openapi3/server/petstore/python-flask-python2/requirements.txt index 5c5ce2a1a269..47350085aa10 100644 --- a/samples/openapi3/server/petstore/python-flask-python2/requirements.txt +++ b/samples/openapi3/server/petstore/python-flask-python2/requirements.txt @@ -1,4 +1,4 @@ -connexion >= 2.5.0; python_version>="3.6" +connexion >= 2.6.0; python_version>="3.6" connexion >= 2.3.0; python_version=="3.5" connexion >= 2.3.0; python_version=="3.4" connexion == 2.4.0; python_version<="2.7" diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/pet_controller.py b/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/pet_controller.py index 9376ab94244c..20b15fabbd98 100644 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/pet_controller.py +++ b/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/pet_controller.py @@ -3,6 +3,9 @@ from openapi_server.models.api_response import ApiResponse # noqa: E501 from openapi_server.models.pet import Pet # noqa: E501 +from openapi_server.models.pet_form import PetForm # noqa: E501 +from openapi_server.models.status_enum import StatusEnum # noqa: E501 +from openapi_server.models.upload_form import UploadForm # noqa: E501 from openapi_server import util @@ -90,35 +93,52 @@ def update_pet(pet): # noqa: E501 return 'do some magic!' -def update_pet_with_form(pet_id, name=None, status=None): # noqa: E501 +def update_pet_status_with_enum(pet_id, status): # noqa: E501 + """Set the status of a pet in the store using an enum + + # noqa: E501 + + :param pet_id: ID of pet to return + :type pet_id: int + :param status: The required status + :type status: dict | bytes + + :rtype: Pet + """ + if connexion.request.is_json: + status = StatusEnum.from_dict(connexion.request.get_json()) # noqa: E501 + return 'do some magic!' + + +def update_pet_with_form(pet_id, pet_form=None): # noqa: E501 """Updates a pet in the store with form data # noqa: E501 :param pet_id: ID of pet that needs to be updated :type pet_id: int - :param name: Updated name of the pet - :type name: str - :param status: Updated status of the pet - :type status: str + :param pet_form: + :type pet_form: dict | bytes :rtype: None """ + if connexion.request.is_json: + pet_form = PetForm.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' -def upload_file(pet_id, additional_metadata=None, file=None): # noqa: E501 +def upload_file(pet_id, upload_form=None): # noqa: E501 """uploads an image # noqa: E501 :param pet_id: ID of pet to update :type pet_id: int - :param additional_metadata: Additional data to pass to server - :type additional_metadata: str - :param file: file to upload - :type file: str + :param upload_form: + :type upload_form: dict | bytes :rtype: ApiResponse """ + if connexion.request.is_json: + upload_form = UploadForm.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!' diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/user_controller.py b/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/user_controller.py index 9b9706262121..e897814d4b0d 100644 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/user_controller.py +++ b/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/user_controller.py @@ -25,7 +25,7 @@ def create_users_with_array_input(user): # noqa: E501 # noqa: E501 - :param user: List of user object + :param user: List of user objects :type user: list | bytes :rtype: None @@ -40,7 +40,7 @@ def create_users_with_list_input(user): # noqa: E501 # noqa: E501 - :param user: List of user object + :param user: List of user objects :type user: list | bytes :rtype: None diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/__init__.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/__init__.py index 689233630d14..bb6f70f1569b 100644 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/__init__.py +++ b/samples/openapi3/server/petstore/python-flask/openapi_server/models/__init__.py @@ -5,9 +5,10 @@ # import models into model package from openapi_server.models.api_response import ApiResponse from openapi_server.models.category import Category -from openapi_server.models.inline_object import InlineObject -from openapi_server.models.inline_object1 import InlineObject1 from openapi_server.models.order import Order from openapi_server.models.pet import Pet +from openapi_server.models.pet_form import PetForm +from openapi_server.models.status_enum import StatusEnum from openapi_server.models.tag import Tag +from openapi_server.models.upload_form import UploadForm from openapi_server.models.user import User diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/inline_object.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/pet_form.py similarity index 62% rename from samples/openapi3/server/petstore/python-flask/openapi_server/models/inline_object.py rename to samples/openapi3/server/petstore/python-flask/openapi_server/models/pet_form.py index 1178d560625c..1f682346e4fb 100644 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/inline_object.py +++ b/samples/openapi3/server/petstore/python-flask/openapi_server/models/pet_form.py @@ -9,18 +9,18 @@ from openapi_server import util -class InlineObject(Model): +class PetForm(Model): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(self, name=None, status=None): # noqa: E501 - """InlineObject - a model defined in OpenAPI + """PetForm - a model defined in OpenAPI - :param name: The name of this InlineObject. # noqa: E501 + :param name: The name of this PetForm. # noqa: E501 :type name: str - :param status: The status of this InlineObject. # noqa: E501 + :param status: The status of this PetForm. # noqa: E501 :type status: str """ self.openapi_types = { @@ -37,58 +37,62 @@ def __init__(self, name=None, status=None): # noqa: E501 self._status = status @classmethod - def from_dict(cls, dikt) -> 'InlineObject': + def from_dict(cls, dikt) -> 'PetForm': """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The inline_object of this InlineObject. # noqa: E501 - :rtype: InlineObject + :return: The PetForm of this PetForm. # noqa: E501 + :rtype: PetForm """ return util.deserialize_model(dikt, cls) @property def name(self): - """Gets the name of this InlineObject. + """Gets the name of this PetForm. Updated name of the pet # noqa: E501 - :return: The name of this InlineObject. + :return: The name of this PetForm. :rtype: str """ return self._name @name.setter def name(self, name): - """Sets the name of this InlineObject. + """Sets the name of this PetForm. Updated name of the pet # noqa: E501 - :param name: The name of this InlineObject. + :param name: The name of this PetForm. :type name: str """ + if name is None: + raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 self._name = name @property def status(self): - """Gets the status of this InlineObject. + """Gets the status of this PetForm. Updated status of the pet # noqa: E501 - :return: The status of this InlineObject. + :return: The status of this PetForm. :rtype: str """ return self._status @status.setter def status(self, status): - """Sets the status of this InlineObject. + """Sets the status of this PetForm. Updated status of the pet # noqa: E501 - :param status: The status of this InlineObject. + :param status: The status of this PetForm. :type status: str """ + if status is None: + raise ValueError("Invalid value for `status`, must not be `None`") # noqa: E501 self._status = status diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/status_enum.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/status_enum.py new file mode 100644 index 000000000000..653c1684396f --- /dev/null +++ b/samples/openapi3/server/petstore/python-flask/openapi_server/models/status_enum.py @@ -0,0 +1,43 @@ +# coding: utf-8 + +from __future__ import absolute_import +from datetime import date, datetime # noqa: F401 + +from typing import List, Dict # noqa: F401 + +from openapi_server.models.base_model_ import Model +from openapi_server import util + + +class StatusEnum(Model): + """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + + Do not edit the class manually. + """ + + """ + allowed enum values + """ + AVAILABLE = "available" + PENDING = "pending" + SOLD = "sold" + def __init__(self): # noqa: E501 + """StatusEnum - a model defined in OpenAPI + + """ + self.openapi_types = { + } + + self.attribute_map = { + } + + @classmethod + def from_dict(cls, dikt) -> 'StatusEnum': + """Returns the dict as a model + + :param dikt: A dict. + :type: dict + :return: The statusEnum of this StatusEnum. # noqa: E501 + :rtype: StatusEnum + """ + return util.deserialize_model(dikt, cls) diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/inline_object1.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/upload_form.py similarity index 69% rename from samples/openapi3/server/petstore/python-flask/openapi_server/models/inline_object1.py rename to samples/openapi3/server/petstore/python-flask/openapi_server/models/upload_form.py index 349041c0c8fc..3e566f6837aa 100644 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/inline_object1.py +++ b/samples/openapi3/server/petstore/python-flask/openapi_server/models/upload_form.py @@ -9,18 +9,18 @@ from openapi_server import util -class InlineObject1(Model): +class UploadForm(Model): """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). Do not edit the class manually. """ def __init__(self, additional_metadata=None, file=None): # noqa: E501 - """InlineObject1 - a model defined in OpenAPI + """UploadForm - a model defined in OpenAPI - :param additional_metadata: The additional_metadata of this InlineObject1. # noqa: E501 + :param additional_metadata: The additional_metadata of this UploadForm. # noqa: E501 :type additional_metadata: str - :param file: The file of this InlineObject1. # noqa: E501 + :param file: The file of this UploadForm. # noqa: E501 :type file: file """ self.openapi_types = { @@ -37,34 +37,34 @@ def __init__(self, additional_metadata=None, file=None): # noqa: E501 self._file = file @classmethod - def from_dict(cls, dikt) -> 'InlineObject1': + def from_dict(cls, dikt) -> 'UploadForm': """Returns the dict as a model :param dikt: A dict. :type: dict - :return: The inline_object_1 of this InlineObject1. # noqa: E501 - :rtype: InlineObject1 + :return: The UploadForm of this UploadForm. # noqa: E501 + :rtype: UploadForm """ return util.deserialize_model(dikt, cls) @property def additional_metadata(self): - """Gets the additional_metadata of this InlineObject1. + """Gets the additional_metadata of this UploadForm. Additional data to pass to server # noqa: E501 - :return: The additional_metadata of this InlineObject1. + :return: The additional_metadata of this UploadForm. :rtype: str """ return self._additional_metadata @additional_metadata.setter def additional_metadata(self, additional_metadata): - """Sets the additional_metadata of this InlineObject1. + """Sets the additional_metadata of this UploadForm. Additional data to pass to server # noqa: E501 - :param additional_metadata: The additional_metadata of this InlineObject1. + :param additional_metadata: The additional_metadata of this UploadForm. :type additional_metadata: str """ @@ -72,23 +72,25 @@ def additional_metadata(self, additional_metadata): @property def file(self): - """Gets the file of this InlineObject1. + """Gets the file of this UploadForm. file to upload # noqa: E501 - :return: The file of this InlineObject1. + :return: The file of this UploadForm. :rtype: file """ return self._file @file.setter def file(self, file): - """Sets the file of this InlineObject1. + """Sets the file of this UploadForm. file to upload # noqa: E501 - :param file: The file of this InlineObject1. + :param file: The file of this UploadForm. :type file: file """ + if file is None: + raise ValueError("Invalid value for `file`, must not be `None`") # noqa: E501 self._file = file diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/openapi/openapi.yaml b/samples/openapi3/server/petstore/python-flask/openapi_server/openapi/openapi.yaml index d98eee5eb1bf..142289318ae3 100644 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/openapi/openapi.yaml +++ b/samples/openapi3/server/petstore/python-flask/openapi_server/openapi/openapi.yaml @@ -1,4 +1,4 @@ -openapi: 3.0.0 +openapi: 3.0.1 info: description: This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. @@ -220,6 +220,45 @@ paths: tags: - pet x-openapi-router-controller: openapi_server.controllers.pet_controller + patch: + operationId: update_pet_status_with_enum + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + - description: The required status + example: pending + explode: true + in: query + name: status + required: true + schema: + $ref: '#/components/schemas/statusEnum' + style: form + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + summary: Set the status of a pet in the store using an enum + tags: + - pet + x-openapi-router-controller: openapi_server.controllers.pet_controller post: operationId: update_pet_with_form parameters: @@ -233,18 +272,7 @@ paths: type: integer style: simple requestBody: - $ref: '#/components/requestBodies/inline_object' - content: - application/x-www-form-urlencoded: - schema: - properties: - name: - description: Updated name of the pet - type: string - status: - description: Updated status of the pet - type: string - type: object + $ref: '#/components/requestBodies/PetForm' responses: "405": description: Invalid input @@ -270,19 +298,7 @@ paths: type: integer style: simple requestBody: - $ref: '#/components/requestBodies/inline_object_1' - content: - multipart/form-data: - schema: - properties: - additionalMetadata: - description: Additional data to pass to server - type: string - file: - description: file to upload - format: binary - type: string - type: object + $ref: '#/components/requestBodies/UploadForm' responses: "200": content: @@ -605,6 +621,17 @@ paths: - user x-openapi-router-controller: openapi_server.controllers.user_controller components: + parameters: + statusEnum: + description: The required status + example: pending + explode: true + in: query + name: status + required: true + schema: + $ref: '#/components/schemas/statusEnum' + style: form requestBodies: UserArray: content: @@ -613,7 +640,7 @@ components: items: $ref: '#/components/schemas/User' type: array - description: List of user object + description: List of user objects required: true Pet: content: @@ -625,16 +652,22 @@ components: $ref: '#/components/schemas/Pet' description: Pet object that needs to be added to the store required: true - inline_object: + PetForm: content: application/x-www-form-urlencoded: + example: + name: fluffy + status: available schema: - $ref: '#/components/schemas/inline_object' - inline_object_1: + $ref: '#/components/schemas/PetForm' + UploadForm: content: multipart/form-data: + example: + additionalMetadata: additional metadata example + file: c29tZSB0ZXN0IGRhdGEK schema: - $ref: '#/components/schemas/inline_object_1' + $ref: '#/components/schemas/UploadForm' schemas: Order: description: An order for a pets from the pet store @@ -792,23 +825,8 @@ components: type: object xml: name: Pet - ApiResponse: - description: Describes the result of uploading an image resource - example: - code: 0 - type: type - message: message - properties: - code: - format: int32 - type: integer - type: - type: string - message: - type: string - title: An uploaded response - type: object - inline_object: + PetForm: + description: A form for updating a pet properties: name: description: Updated name of the pet @@ -816,8 +834,13 @@ components: status: description: Updated status of the pet type: string + required: + - name + - status + title: A pet form type: object - inline_object_1: + UploadForm: + description: A form for attaching files to a pet properties: additionalMetadata: description: Additional data to pass to server @@ -826,7 +849,33 @@ components: description: file to upload format: binary type: string + required: + - file + title: An upload form + type: object + ApiResponse: + description: Describes the result of uploading an image resource + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + title: An uploaded response type: object + statusEnum: + description: pet status in the store + enum: + - available + - pending + - sold + type: string securitySchemes: petstore_auth: flows: diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_pet_controller.py b/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_pet_controller.py index 50a1e25cbb89..be94fa8d5af5 100644 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_pet_controller.py +++ b/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_pet_controller.py @@ -8,6 +8,9 @@ from openapi_server.models.api_response import ApiResponse # noqa: E501 from openapi_server.models.pet import Pet # noqa: E501 +from openapi_server.models.pet_form import PetForm # noqa: E501 +from openapi_server.models.status_enum import StatusEnum # noqa: E501 +from openapi_server.models.upload_form import UploadForm # noqa: E501 from openapi_server.test import BaseTestCase @@ -156,23 +159,39 @@ def test_update_pet(self): self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) + def test_update_pet_status_with_enum(self): + """Test case for update_pet_status_with_enum + + Set the status of a pet in the store using an enum + """ + query_string = [('status', pending)] + headers = { + 'Accept': 'application/json', + } + response = self.client.open( + '/v2/pet/{pet_id}'.format(pet_id=56), + method='PATCH', + headers=headers, + query_string=query_string) + self.assert200(response, + 'Response body is : ' + response.data.decode('utf-8')) + @unittest.skip("application/x-www-form-urlencoded not supported by Connexion") def test_update_pet_with_form(self): """Test case for update_pet_with_form Updates a pet in the store with form data """ + pet_form = {"name":"fluffy","status":"available"} headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer special-key', } - data = dict(name='name_example', - status='status_example') response = self.client.open( '/v2/pet/{pet_id}'.format(pet_id=56), method='POST', headers=headers, - data=data, + data=json.dumps(pet_form), content_type='application/x-www-form-urlencoded') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) @@ -183,18 +202,17 @@ def test_upload_file(self): uploads an image """ + upload_form = {"additionalMetadata":"additional metadata example","file":"c29tZSB0ZXN0IGRhdGEK"} headers = { 'Accept': 'application/json', 'Content-Type': 'multipart/form-data', 'Authorization': 'Bearer special-key', } - data = dict(additional_metadata='additional_metadata_example', - file=(BytesIO(b'some file data'), 'file.txt')) response = self.client.open( '/v2/pet/{pet_id}/uploadImage'.format(pet_id=56), method='POST', headers=headers, - data=data, + data=json.dumps(upload_form), content_type='multipart/form-data') self.assert200(response, 'Response body is : ' + response.data.decode('utf-8')) diff --git a/samples/openapi3/server/petstore/python-flask/requirements.txt b/samples/openapi3/server/petstore/python-flask/requirements.txt index 029a9dae4cdf..2639eedf1361 100644 --- a/samples/openapi3/server/petstore/python-flask/requirements.txt +++ b/samples/openapi3/server/petstore/python-flask/requirements.txt @@ -1,4 +1,4 @@ -connexion >= 2.5.0; python_version>="3.6" +connexion >= 2.6.0; python_version>="3.6" connexion >= 2.3.0; python_version=="3.5" connexion >= 2.3.0; python_version=="3.4" connexion == 2.4.0; python_version<="2.7" diff --git a/samples/server/petstore/python-flask-python2/requirements.txt b/samples/server/petstore/python-flask-python2/requirements.txt index 5c5ce2a1a269..47350085aa10 100644 --- a/samples/server/petstore/python-flask-python2/requirements.txt +++ b/samples/server/petstore/python-flask-python2/requirements.txt @@ -1,4 +1,4 @@ -connexion >= 2.5.0; python_version>="3.6" +connexion >= 2.6.0; python_version>="3.6" connexion >= 2.3.0; python_version=="3.5" connexion >= 2.3.0; python_version=="3.4" connexion == 2.4.0; python_version<="2.7" diff --git a/samples/server/petstore/python-flask/requirements.txt b/samples/server/petstore/python-flask/requirements.txt index 029a9dae4cdf..2639eedf1361 100644 --- a/samples/server/petstore/python-flask/requirements.txt +++ b/samples/server/petstore/python-flask/requirements.txt @@ -1,4 +1,4 @@ -connexion >= 2.5.0; python_version>="3.6" +connexion >= 2.6.0; python_version>="3.6" connexion >= 2.3.0; python_version=="3.5" connexion >= 2.3.0; python_version=="3.4" connexion == 2.4.0; python_version<="2.7" diff --git a/samples/server/petstore/scala-lagom-server/.openapi-generator/VERSION b/samples/server/petstore/scala-lagom-server/.openapi-generator/VERSION index 58592f031f65..bfbf77eb7fad 100644 --- a/samples/server/petstore/scala-lagom-server/.openapi-generator/VERSION +++ b/samples/server/petstore/scala-lagom-server/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/scala-play-server/.openapi-generator/VERSION b/samples/server/petstore/scala-play-server/.openapi-generator/VERSION index 58592f031f65..bfbf77eb7fad 100644 --- a/samples/server/petstore/scala-play-server/.openapi-generator/VERSION +++ b/samples/server/petstore/scala-play-server/.openapi-generator/VERSION @@ -1 +1 @@ -4.2.3-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/scala-play-server/README.md b/samples/server/petstore/scala-play-server/README.md index 87528aac7f01..a4694cf93f47 100644 --- a/samples/server/petstore/scala-play-server/README.md +++ b/samples/server/petstore/scala-play-server/README.md @@ -2,7 +2,7 @@ This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -This Scala Play Framework project was generated by the OpenAPI generator tool at 2020-01-04T23:10:22.106-05:00[America/New_York]. +This Scala Play Framework project was generated by the OpenAPI generator tool at 2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]. ## API diff --git a/samples/server/petstore/scala-play-server/app/api/PetApi.scala b/samples/server/petstore/scala-play-server/app/api/PetApi.scala index ec7dc810a4b6..e7e0604b377e 100644 --- a/samples/server/petstore/scala-play-server/app/api/PetApi.scala +++ b/samples/server/petstore/scala-play-server/app/api/PetApi.scala @@ -4,7 +4,7 @@ import model.ApiResponse import model.Pet import play.api.libs.Files.TemporaryFile -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") trait PetApi { /** * Add a new pet to the store diff --git a/samples/server/petstore/scala-play-server/app/api/PetApiController.scala b/samples/server/petstore/scala-play-server/app/api/PetApiController.scala index 36d5ff287fd4..732ac4acb527 100644 --- a/samples/server/petstore/scala-play-server/app/api/PetApiController.scala +++ b/samples/server/petstore/scala-play-server/app/api/PetApiController.scala @@ -8,7 +8,7 @@ import model.ApiResponse import model.Pet import play.api.libs.Files.TemporaryFile -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") @Singleton class PetApiController @Inject()(cc: ControllerComponents, api: PetApi) extends AbstractController(cc) { /** diff --git a/samples/server/petstore/scala-play-server/app/api/PetApiImpl.scala b/samples/server/petstore/scala-play-server/app/api/PetApiImpl.scala index b5186deba44d..757bacbd6ab9 100644 --- a/samples/server/petstore/scala-play-server/app/api/PetApiImpl.scala +++ b/samples/server/petstore/scala-play-server/app/api/PetApiImpl.scala @@ -7,7 +7,7 @@ import play.api.libs.Files.TemporaryFile /** * Provides a default implementation for [[PetApi]]. */ -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") class PetApiImpl extends PetApi { /** * @inheritdoc diff --git a/samples/server/petstore/scala-play-server/app/api/StoreApi.scala b/samples/server/petstore/scala-play-server/app/api/StoreApi.scala index 3197b95ed814..2b84cc0f9d7a 100644 --- a/samples/server/petstore/scala-play-server/app/api/StoreApi.scala +++ b/samples/server/petstore/scala-play-server/app/api/StoreApi.scala @@ -2,7 +2,7 @@ package api import model.Order -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") trait StoreApi { /** * Delete purchase order by ID diff --git a/samples/server/petstore/scala-play-server/app/api/StoreApiController.scala b/samples/server/petstore/scala-play-server/app/api/StoreApiController.scala index f36218bd62d6..f34614730d9d 100644 --- a/samples/server/petstore/scala-play-server/app/api/StoreApiController.scala +++ b/samples/server/petstore/scala-play-server/app/api/StoreApiController.scala @@ -6,7 +6,7 @@ import play.api.libs.json._ import play.api.mvc._ import model.Order -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") @Singleton class StoreApiController @Inject()(cc: ControllerComponents, api: StoreApi) extends AbstractController(cc) { /** diff --git a/samples/server/petstore/scala-play-server/app/api/StoreApiImpl.scala b/samples/server/petstore/scala-play-server/app/api/StoreApiImpl.scala index efe32363e9cd..32ea8d1562bc 100644 --- a/samples/server/petstore/scala-play-server/app/api/StoreApiImpl.scala +++ b/samples/server/petstore/scala-play-server/app/api/StoreApiImpl.scala @@ -5,7 +5,7 @@ import model.Order /** * Provides a default implementation for [[StoreApi]]. */ -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") class StoreApiImpl extends StoreApi { /** * @inheritdoc diff --git a/samples/server/petstore/scala-play-server/app/api/UserApi.scala b/samples/server/petstore/scala-play-server/app/api/UserApi.scala index df0471d833f5..937758724385 100644 --- a/samples/server/petstore/scala-play-server/app/api/UserApi.scala +++ b/samples/server/petstore/scala-play-server/app/api/UserApi.scala @@ -2,7 +2,7 @@ package api import model.User -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") trait UserApi { /** * Create user diff --git a/samples/server/petstore/scala-play-server/app/api/UserApiController.scala b/samples/server/petstore/scala-play-server/app/api/UserApiController.scala index 2675c44bafa6..0a78f46385bc 100644 --- a/samples/server/petstore/scala-play-server/app/api/UserApiController.scala +++ b/samples/server/petstore/scala-play-server/app/api/UserApiController.scala @@ -6,7 +6,7 @@ import play.api.libs.json._ import play.api.mvc._ import model.User -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") @Singleton class UserApiController @Inject()(cc: ControllerComponents, api: UserApi) extends AbstractController(cc) { /** diff --git a/samples/server/petstore/scala-play-server/app/api/UserApiImpl.scala b/samples/server/petstore/scala-play-server/app/api/UserApiImpl.scala index b14446f643f4..419856d87ef5 100644 --- a/samples/server/petstore/scala-play-server/app/api/UserApiImpl.scala +++ b/samples/server/petstore/scala-play-server/app/api/UserApiImpl.scala @@ -5,7 +5,7 @@ import model.User /** * Provides a default implementation for [[UserApi]]. */ -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") class UserApiImpl extends UserApi { /** * @inheritdoc diff --git a/samples/server/petstore/scala-play-server/app/model/ApiResponse.scala b/samples/server/petstore/scala-play-server/app/model/ApiResponse.scala index 956360fa5ea1..6d846a96d2c6 100644 --- a/samples/server/petstore/scala-play-server/app/model/ApiResponse.scala +++ b/samples/server/petstore/scala-play-server/app/model/ApiResponse.scala @@ -5,7 +5,7 @@ import play.api.libs.json._ /** * Describes the result of uploading an image resource */ -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") case class ApiResponse( code: Option[Int], `type`: Option[String], diff --git a/samples/server/petstore/scala-play-server/app/model/Category.scala b/samples/server/petstore/scala-play-server/app/model/Category.scala index 120411990fb3..f162cc450b39 100644 --- a/samples/server/petstore/scala-play-server/app/model/Category.scala +++ b/samples/server/petstore/scala-play-server/app/model/Category.scala @@ -5,7 +5,7 @@ import play.api.libs.json._ /** * A category for a pet */ -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") case class Category( id: Option[Long], name: Option[String] diff --git a/samples/server/petstore/scala-play-server/app/model/Order.scala b/samples/server/petstore/scala-play-server/app/model/Order.scala index c911b7f444d2..2abd87755f28 100644 --- a/samples/server/petstore/scala-play-server/app/model/Order.scala +++ b/samples/server/petstore/scala-play-server/app/model/Order.scala @@ -7,7 +7,7 @@ import java.time.OffsetDateTime * An order for a pets from the pet store * @param status Order Status */ -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") case class Order( id: Option[Long], petId: Option[Long], diff --git a/samples/server/petstore/scala-play-server/app/model/Pet.scala b/samples/server/petstore/scala-play-server/app/model/Pet.scala index 2f50116cd436..fba74ec5e7ad 100644 --- a/samples/server/petstore/scala-play-server/app/model/Pet.scala +++ b/samples/server/petstore/scala-play-server/app/model/Pet.scala @@ -6,7 +6,7 @@ import play.api.libs.json._ * A pet for sale in the pet store * @param status pet status in the store */ -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") case class Pet( id: Option[Long], category: Option[Category], diff --git a/samples/server/petstore/scala-play-server/app/model/Tag.scala b/samples/server/petstore/scala-play-server/app/model/Tag.scala index 4a20e2acdf08..c0d53b02853c 100644 --- a/samples/server/petstore/scala-play-server/app/model/Tag.scala +++ b/samples/server/petstore/scala-play-server/app/model/Tag.scala @@ -5,7 +5,7 @@ import play.api.libs.json._ /** * A tag for a pet */ -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") case class Tag( id: Option[Long], name: Option[String] diff --git a/samples/server/petstore/scala-play-server/app/model/User.scala b/samples/server/petstore/scala-play-server/app/model/User.scala index af11a3d3c934..de3fd45b7d19 100644 --- a/samples/server/petstore/scala-play-server/app/model/User.scala +++ b/samples/server/petstore/scala-play-server/app/model/User.scala @@ -6,7 +6,7 @@ import play.api.libs.json._ * A User who is purchasing from the pet store * @param userStatus User Status */ -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") case class User( id: Option[Long], username: Option[String], diff --git a/samples/server/petstore/scala-play-server/app/org/openapitools/Module.scala b/samples/server/petstore/scala-play-server/app/org/openapitools/Module.scala index 98382284f9e9..9d083966f008 100644 --- a/samples/server/petstore/scala-play-server/app/org/openapitools/Module.scala +++ b/samples/server/petstore/scala-play-server/app/org/openapitools/Module.scala @@ -4,7 +4,7 @@ import api._ import play.api.inject.{Binding, Module => PlayModule} import play.api.{Configuration, Environment} -@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-01-04T23:10:22.106-05:00[America/New_York]") +@javax.annotation.Generated(value = Array("org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen"), date = "2020-02-25T23:20:59.671788+07:00[Asia/Bangkok]") class Module extends PlayModule { override def bindings(environment: Environment, configuration: Configuration): Seq[Binding[_]] = Seq( bind[PetApi].to[PetApiImpl], diff --git a/samples/server/petstore/scalatra/.openapi-generator/VERSION b/samples/server/petstore/scalatra/.openapi-generator/VERSION index 096bf47efe31..bfbf77eb7fad 100644 --- a/samples/server/petstore/scalatra/.openapi-generator/VERSION +++ b/samples/server/petstore/scalatra/.openapi-generator/VERSION @@ -1 +1 @@ -3.0.0-SNAPSHOT \ No newline at end of file +4.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/scalatra/src/main/scala/JettyMain.scala b/samples/server/petstore/scalatra/src/main/scala/JettyMain.scala index 9f9e5c93f808..e812796c15ce 100644 --- a/samples/server/petstore/scalatra/src/main/scala/JettyMain.scala +++ b/samples/server/petstore/scalatra/src/main/scala/JettyMain.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala index bdab3861475b..b949318aebc4 100644 --- a/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala +++ b/samples/server/petstore/scalatra/src/main/scala/ScalatraBootstrap.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala b/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala index d532f77b366a..8d8d0269d14f 100644 --- a/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala +++ b/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/PetApi.scala b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/PetApi.scala index 8ecf1d6283a8..f7e1b79ca57e 100644 --- a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/PetApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/PetApi.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -41,7 +41,7 @@ class PetApi(implicit val swagger: Swagger) extends ScalatraServlet } - val addPetOperation = (apiOperation[Unit]("addPet") + val addPetOperation = (apiOperation[Pet]("addPet") summary "Add a new pet to the store" parameters(bodyParam[Pet]("pet").description("")) ) @@ -118,7 +118,7 @@ class PetApi(implicit val swagger: Swagger) extends ScalatraServlet - val updatePetOperation = (apiOperation[Unit]("updatePet") + val updatePetOperation = (apiOperation[Pet]("updatePet") summary "Update an existing pet" parameters(bodyParam[Pet]("pet").description("")) ) diff --git a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/StoreApi.scala b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/StoreApi.scala index 3419f02abfbf..e640f4a3e28b 100644 --- a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/StoreApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/StoreApi.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/UserApi.scala b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/UserApi.scala index 90ee1e201d58..8cdc75071cf0 100644 --- a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/UserApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/api/UserApi.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/ApiResponse.scala b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/ApiResponse.scala index e14b6bbaaf56..05dc357b10b4 100644 --- a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/ApiResponse.scala +++ b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/ApiResponse.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Category.scala b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Category.scala index 148704eeb083..fb2ef7844d1b 100644 --- a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Category.scala +++ b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Category.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/InlineObject.scala b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/InlineObject.scala new file mode 100644 index 000000000000..9a521c62250e --- /dev/null +++ b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/InlineObject.scala @@ -0,0 +1,21 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + */ + +package org.openapitools.server.model + +case class InlineObject( + /* Updated name of the pet */ + name: Option[String], + + /* Updated status of the pet */ + status: Option[String] + + ) diff --git a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/InlineObject1.scala b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/InlineObject1.scala new file mode 100644 index 000000000000..aa938e897132 --- /dev/null +++ b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/InlineObject1.scala @@ -0,0 +1,22 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + */ + +package org.openapitools.server.model +import java.io.File + +case class InlineObject1( + /* Additional data to pass to server */ + additionalMetadata: Option[String], + + /* file to upload */ + file: Option[File] + + ) diff --git a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Order.scala b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Order.scala index 9394dc1b8eba..809f722db475 100644 --- a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Order.scala +++ b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Order.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -10,7 +10,7 @@ */ package org.openapitools.server.model -import java.util.Date +import org.joda.time.DateTime case class Order( id: Option[Long], @@ -19,7 +19,7 @@ case class Order( quantity: Option[Int], - shipDate: Option[Date], + shipDate: Option[DateTime], /* Order Status */ status: Option[String], diff --git a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Pet.scala b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Pet.scala index 7296720147c2..062ed9dd53f9 100644 --- a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Pet.scala +++ b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Pet.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Tag.scala b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Tag.scala index 4002f962d088..458f5335bde5 100644 --- a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Tag.scala +++ b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/Tag.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/User.scala b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/User.scala index ef69c5ffed26..b4edb94c0a77 100644 --- a/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/User.scala +++ b/samples/server/petstore/scalatra/src/main/scala/org/openapitools/server/model/User.scala @@ -2,7 +2,7 @@ * OpenAPI Petstore * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * - * OpenAPI spec version: 1.0.0 + * The version of the OpenAPI document: 1.0.0 * Contact: team@openapitools.org * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js index dd300fe1aeab..c37c1641f024 100755 --- a/website/docusaurus.config.js +++ b/website/docusaurus.config.js @@ -60,11 +60,11 @@ const docusaurusConfig = { trackingID: 'UA-132927057-1', }, - // algolia: { - // apiKey: '47ecd3b21be71c5822571b9f59e52544', - // indexName: 'docusaurus-2', - // algoliaOptions: { ... }, - // }, + algolia: { + apiKey: '28e55aff9bab37236baa1c5f0f84f4bb', + indexName: 'openapi-generator', + algoliaOptions: { advancedSyntax: true, hitsPerPage: 5}, + }, footer: {