diff --git a/bin/security/go-petstore.sh b/bin/security/go-petstore.sh new file mode 100755 index 00000000000..e81d52ac258 --- /dev/null +++ b/bin/security/go-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/go -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l go -o samples/client/petstore-security-test/go" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/objc-petstore.sh b/bin/security/objc-petstore.sh new file mode 100755 index 00000000000..fa3a7bc7afd --- /dev/null +++ b/bin/security/objc-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/objc -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l objc -o samples/client/petstore-security-test/objc" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/qt5cpp-petstore.sh b/bin/security/qt5cpp-petstore.sh new file mode 100755 index 00000000000..fd76bda8b57 --- /dev/null +++ b/bin/security/qt5cpp-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/qt5cpp -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l qt5cpp -o samples/client/petstore-security-test/qt5cpp" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/run-all-petstore-security-test b/bin/security/run-all-petstore-security-test new file mode 100755 index 00000000000..cbddeeb58aa --- /dev/null +++ b/bin/security/run-all-petstore-security-test @@ -0,0 +1,15 @@ +#!/bin/bash -e + +for SCRIPT in ./bin/security/*.sh +do + if [ -f $SCRIPT -a -x $SCRIPT ] + then + $SCRIPT + rc=$? + if [[ $rc != 0 ]] + then + echo "ERROR!! FAILED TO RUN $SCRIPT" + exit $rc; + fi + fi +done diff --git a/bin/security/scala-petstore.sh b/bin/security/scala-petstore.sh new file mode 100755 index 00000000000..2e842d7b7d0 --- /dev/null +++ b/bin/security/scala-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/scala -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l scala -o samples/client/petstore-security-test/scala" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/swift-petstore.sh b/bin/security/swift-petstore.sh new file mode 100755 index 00000000000..022edf2a1d7 --- /dev/null +++ b/bin/security/swift-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l swift -o samples/client/petstore-security-test/swift" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/typescript-angular.sh b/bin/security/typescript-angular.sh new file mode 100755 index 00000000000..5f6f1bab0aa --- /dev/null +++ b/bin/security/typescript-angular.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/typescript-angular -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l typescript-angular -o samples/client/petstore-security-test/typescript-angular" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/typescript-angular2.sh b/bin/security/typescript-angular2.sh new file mode 100755 index 00000000000..cdf5b44b695 --- /dev/null +++ b/bin/security/typescript-angular2.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/typescript-angular2 -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l typescript-angular2 -o samples/client/petstore-security-test/typescript-angular2" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/typescript-fetch.sh b/bin/security/typescript-fetch.sh new file mode 100755 index 00000000000..17c61cf26ed --- /dev/null +++ b/bin/security/typescript-fetch.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/typescript-fetch -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l typescript-fetch -o samples/client/petstore-security-test/typescript-fetch" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/security/typescript-node.sh b/bin/security/typescript-node.sh new file mode 100755 index 00000000000..f9b8ef6f3b6 --- /dev/null +++ b/bin/security/typescript-node.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/typescript-node -i modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml -l typescript-node -o samples/client/petstore-security-test/typescript-node" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index ad97e96cf50..1eceabdd973 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1774,7 +1774,7 @@ public class DefaultCodegen { for (String key : consumes) { Map mediaType = new HashMap(); // escape quotation to avoid code injection - mediaType.put("mediaType", escapeQuotationMark(key)); + mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); count += 1; if (count < consumes.size()) { mediaType.put("hasMore", "true"); @@ -1808,7 +1808,7 @@ public class DefaultCodegen { for (String key : produces) { Map mediaType = new HashMap(); // escape quotation to avoid code injection - mediaType.put("mediaType", escapeQuotationMark(key)); + mediaType.put("mediaType", escapeText(escapeQuotationMark(key))); count += 1; if (count < produces.size()) { mediaType.put("hasMore", "true"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index 09672f6b6f6..06c4f0ddfae 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -182,7 +182,7 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toVarName(String name) { // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + name = sanitizeName(name.replaceAll("-", "_")); // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) @@ -346,13 +346,15 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toOperationId(String operationId) { + String sanitizedOperationId = new String(sanitizeName(operationId)); + // method name cannot use reserved keyword, e.g. return - if (isReservedWord(operationId)) { - LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize(sanitizeName("call_" + operationId))); - operationId = "call_" + operationId; + if (isReservedWord(sanitizedOperationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + camelize("call_" + operationId)); + sanitizedOperationId = "call_" + sanitizedOperationId; } - return camelize(operationId); + return camelize(sanitizedOperationId); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java index 700bdfd3a50..bd52bbf9b25 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java @@ -23,7 +23,7 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig * @see io.swagger.codegen.CodegenType */ public CodegenType getTag() { - return CodegenType.CLIENT; + return CodegenType.SERVER; } /** diff --git a/modules/swagger-codegen/src/main/resources/go/api.mustache b/modules/swagger-codegen/src/main/resources/go/api.mustache index b3e2f6db9af..6ddb9ee2753 100644 --- a/modules/swagger-codegen/src/main/resources/go/api.mustache +++ b/modules/swagger-codegen/src/main/resources/go/api.mustache @@ -39,7 +39,7 @@ func New{{classname}}WithBasePath(basePath string) *{{classname}} { {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{^isListContainer}}*{{/isListContainer}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ -func (a {{classname}}) {{nickname}}({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{^isListContainer}}*{{/isListContainer}}{{{returnType}}}, {{/returnType}}*APIResponse, error) { +func (a {{{classname}}}) {{{nickname}}}({{#allParams}}{{paramName}} {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) ({{#returnType}}{{^isListContainer}}*{{/isListContainer}}{{{returnType}}}, {{/returnType}}*APIResponse, error) { var httpMethod = "{{httpMethod}}" // create path and map variables diff --git a/modules/swagger-codegen/src/main/resources/go/configuration.mustache b/modules/swagger-codegen/src/main/resources/go/configuration.mustache index fbc22f603d0..d8d2260b2e6 100644 --- a/modules/swagger-codegen/src/main/resources/go/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/go/configuration.mustache @@ -25,7 +25,7 @@ type Configuration struct { func NewConfiguration() *Configuration { return &Configuration{ - BasePath: "{{basePath}}", + BasePath: "{{{basePath}}}", UserName: "", debug: false, DefaultHeader: make(map[string]string), diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml index 38da7ff44d6..6a201ba7b3d 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-security-test.yaml @@ -1,68 +1,68 @@ swagger: '2.0' info: - description: "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end" - version: 1.0.0 */ ' " =end - title: Swagger Petstore */ ' " =end - termsOfService: http://swagger.io/terms/ */ ' " =end + description: "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end \r\n \n \r" + version: 1.0.0 */ ' " =end \r\n \n \r + title: Swagger Petstore */ ' " =end \r\n \n \r + termsOfService: http://swagger.io/terms/ */ ' " =end \r\n \n \r contact: - email: apiteam@swagger.io */ ' " =end + email: apiteam@swagger.io */ ' " =end \r\n \n \r license: - name: Apache 2.0 */ ' " =end - url: http://www.apache.org/licenses/LICENSE-2.0.html */ ' " =end -host: petstore.swagger.io */ ' " =end -basePath: /v2 */ ' " =end + name: Apache 2.0 */ ' " =end \r\n \n \r + url: http://www.apache.org/licenses/LICENSE-2.0.html */ ' " =end \r\n \n \r +host: petstore.swagger.io */ ' " =end \r\n \n \r +basePath: /v2 */ ' " =end \r\n \n \r tags: - name: fake - description: Everything about your Pets */ ' " =end + description: Everything about your Pets */ ' " =end \r\n \n \r externalDocs: - description: Find out more */ ' " = end + description: Find out more */ ' " =end \r\n \n \r url: 'http://swagger.io' schemes: - - http */ end ' " + - http */ ' " =end \r\n \n \r paths: /fake: put: tags: - fake - summary: To test code injection */ ' " =end - descriptions: To test code injection */ ' " =end - operationId: testCodeInject */ ' " =end + summary: To test code injection */ ' " =end \r\n \n \r + descriptions: To test code injection */ ' " =end \r\n \n \r + operationId: testCodeInject */ ' " =end \r\n \n \r consumes: - application/json - - "*/ ' \" =end" + - "*/ ' \" =end \r\n \n \r" produces: - application/json - - "*/ ' \" =end" + - "*/ ' \" =end \r\n \n \r" parameters: - - name: test code inject */ ' " =end + - name: test code inject */ ' " =end \r\n \n \r type: string in: formData - description: To test code injection */ ' " =end + description: To test code injection */ ' " =end \r\n \n \r responses: '400': - description: To test code injection */ ' " =end + description: To test code injection */ ' " =end \r\n \n \r securityDefinitions: petstore_auth: type: oauth2 authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' flow: implicit scopes: - 'write:pets': modify pets in your account */ ' " =end - 'read:pets': read your pets */ ' " =end + 'write:pets': modify pets in your account */ ' " =end \r\n \n \r + 'read:pets': read your pets */ ' " =end \r\n \n \r api_key: type: apiKey - name: api_key */ ' " =end + name: api_key */ ' " =end \r\n \n \r in: header definitions: Return: - description: Model for testing reserved words */ ' " =end + description: Model for testing reserved words */ ' " =end \r\n \n \r properties: return: - description: property description */ ' " =end + description: property description */ ' " =end \r\n \n \r type: integer format: int32 xml: name: Return externalDocs: - description: Find out more about Swagger */ ' " =end + description: Find out more about Swagger */ ' " =end \r\n \n \r url: 'http://swagger.io' diff --git a/samples/client/petstore-security-test/go/.gitignore b/samples/client/petstore-security-test/go/.gitignore new file mode 100644 index 00000000000..daf913b1b34 --- /dev/null +++ b/samples/client/petstore-security-test/go/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/samples/client/petstore-security-test/go/.swagger-codegen-ignore b/samples/client/petstore-security-test/go/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/go/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/go/.travis.yml b/samples/client/petstore-security-test/go/.travis.yml new file mode 100644 index 00000000000..f5cb2ce9a5a --- /dev/null +++ b/samples/client/petstore-security-test/go/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/samples/client/petstore-security-test/go/LICENSE b/samples/client/petstore-security-test/go/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/go/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/go/README.md b/samples/client/petstore-security-test/go/README.md new file mode 100644 index 00000000000..965b0aca530 --- /dev/null +++ b/samples/client/petstore-security-test/go/README.md @@ -0,0 +1,55 @@ +# Go API client for swagger + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + +## Overview +This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +- Package version: 1.0.0 +- Build date: 2016-07-12T18:49:24.937+08:00 +- Build package: class io.swagger.codegen.languages.GoClientCodegen + +## Installation +Put the package under your project folder and add the following in import: +``` + "./swagger" +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*FakeApi* | [**TestCodeInjectEndRnNR**](docs/FakeApi.md#testcodeinjectendrnnr) | **Put** /fake | To test code injection *_/ ' \" =end \\r\\n \\n \\r + + +## Documentation For Models + + - [ModelReturn](docs/ModelReturn.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key */ ' " =end \r\n \n \r +- **Location**: HTTP header + +## petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorizatoin URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account */ ' " =end \r\n \n \r + - **read:pets**: read your pets */ ' " =end \r\n \n \r + + +## Author + +apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + diff --git a/samples/client/petstore-security-test/go/api_client.go b/samples/client/petstore-security-test/go/api_client.go new file mode 100644 index 00000000000..a331bfa010e --- /dev/null +++ b/samples/client/petstore-security-test/go/api_client.go @@ -0,0 +1,151 @@ +/* + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package swagger + +import ( + "bytes" + "fmt" + "path/filepath" + "reflect" + "strings" + "net/url" + "github.com/go-resty/resty" +) + +type APIClient struct { +} + +func (c *APIClient) SelectHeaderContentType(contentTypes []string) string { + + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +func (c *APIClient) SelectHeaderAccept(accepts []string) string { + + if len(accepts) == 0 { + return "" + } + if contains(accepts, "application/json") { + return "application/json" + } + return strings.Join(accepts, ",") +} + +func contains(source []string, containvalue string) bool { + for _, a := range source { + if strings.ToLower(a) == strings.ToLower(containvalue) { + return true + } + } + return false +} + +func (c *APIClient) CallAPI(path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams map[string]string, + fileName string, + fileBytes []byte) (*resty.Response, error) { + + //set debug flag + configuration := NewConfiguration() + resty.SetDebug(configuration.GetDebug()) + + request := prepareRequest(postBody, headerParams, queryParams, formParams, fileName, fileBytes) + + switch strings.ToUpper(method) { + case "GET": + response, err := request.Get(path) + return response, err + case "POST": + response, err := request.Post(path) + return response, err + case "PUT": + response, err := request.Put(path) + return response, err + case "PATCH": + response, err := request.Patch(path) + return response, err + case "DELETE": + response, err := request.Delete(path) + return response, err + } + + return nil, fmt.Errorf("invalid method %v", method) +} + +func (c *APIClient) ParameterToString(obj interface{},collectionFormat string) string { + if reflect.TypeOf(obj).String() == "[]string" { + switch collectionFormat { + case "pipes": + return strings.Join(obj.([]string), "|") + case "ssv": + return strings.Join(obj.([]string), " ") + case "tsv": + return strings.Join(obj.([]string), "\t") + case "csv" : + return strings.Join(obj.([]string), ",") + } + } + + return obj.(string) +} + +func prepareRequest(postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams map[string]string, + fileName string, + fileBytes []byte) *resty.Request { + + request := resty.R() + request.SetBody(postBody) + + // add header parameter, if any + if len(headerParams) > 0 { + request.SetHeaders(headerParams) + } + + // add query parameter, if any + if len(queryParams) > 0 { + request.SetMultiValueQueryParams(queryParams) + } + + // add form parameter, if any + if len(formParams) > 0 { + request.SetFormData(formParams) + } + + if len(fileBytes) > 0 && fileName != "" { + _, fileNm := filepath.Split(fileName) + request.SetFileReader("file", fileNm, bytes.NewReader(fileBytes)) + } + return request +} diff --git a/samples/client/petstore-security-test/go/api_response.go b/samples/client/petstore-security-test/go/api_response.go new file mode 100644 index 00000000000..b4dd979d54e --- /dev/null +++ b/samples/client/petstore-security-test/go/api_response.go @@ -0,0 +1,44 @@ +/* + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package swagger + +import ( + "net/http" +) + +type APIResponse struct { + *http.Response + Message string `json:"message,omitempty"` +} + +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/samples/client/petstore-security-test/go/configuration.go b/samples/client/petstore-security-test/go/configuration.go new file mode 100644 index 00000000000..ffe8a09186e --- /dev/null +++ b/samples/client/petstore-security-test/go/configuration.go @@ -0,0 +1,81 @@ +/* + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package swagger + +import ( + "encoding/base64" +) + +type Configuration struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` + APIKeyPrefix map[string]string `json:"APIKeyPrefix,omitempty"` + APIKey map[string]string `json:"APIKey,omitempty"` + debug bool `json:"debug,omitempty"` + DebugFile string `json:"debugFile,omitempty"` + OAuthToken string `json:"oAuthToken,omitempty"` + Timeout int `json:"timeout,omitempty"` + BasePath string `json:"basePath,omitempty"` + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + AccessToken string `json:"accessToken,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + APIClient APIClient `json:"APIClient,omitempty"` +} + +func NewConfiguration() *Configuration { + return &Configuration{ + BasePath: "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r", + UserName: "", + debug: false, + DefaultHeader: make(map[string]string), + APIKey: make(map[string]string), + APIKeyPrefix: make(map[string]string), + UserAgent: "Swagger-Codegen/1.0.0/go", + } +} + +func (c *Configuration) GetBasicAuthEncodedString() string { + return base64.StdEncoding.EncodeToString([]byte(c.UserName + ":" + c.Password)) +} + +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} + +func (c *Configuration) GetAPIKeyWithPrefix(APIKeyIdentifier string) string { + if c.APIKeyPrefix[APIKeyIdentifier] != "" { + return c.APIKeyPrefix[APIKeyIdentifier] + " " + c.APIKey[APIKeyIdentifier] + } + + return c.APIKey[APIKeyIdentifier] +} + +func (c *Configuration) SetDebug(enable bool) { + c.debug = enable +} + +func (c *Configuration) GetDebug() bool { + return c.debug +} diff --git a/samples/client/petstore-security-test/go/docs/FakeApi.md b/samples/client/petstore-security-test/go/docs/FakeApi.md new file mode 100644 index 00000000000..0f0facbbd07 --- /dev/null +++ b/samples/client/petstore-security-test/go/docs/FakeApi.md @@ -0,0 +1,36 @@ +# \FakeApi + +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**TestCodeInjectEndRnNR**](FakeApi.md#TestCodeInjectEndRnNR) | **Put** /fake | To test code injection *_/ ' \" =end \\r\\n \\n \\r + + +# **TestCodeInjectEndRnNR** +> TestCodeInjectEndRnNR($testCodeInjectEndRnNR) + +To test code injection *_/ ' \" =end \\r\\n \\n \\r + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **testCodeInjectEndRnNR** | **string**| To test code injection *_/ ' \" =end \\r\\n \\n \\r | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json, *_/ ' =end + - **Accept**: application/json, *_/ ' =end + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore-security-test/go/docs/ModelReturn.md b/samples/client/petstore-security-test/go/docs/ModelReturn.md new file mode 100644 index 00000000000..571b22dc562 --- /dev/null +++ b/samples/client/petstore-security-test/go/docs/ModelReturn.md @@ -0,0 +1,10 @@ +# ModelReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Return_** | **int32** | property description *_/ ' \" =end \\r\\n \\n \\r | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore-security-test/go/fake_api.go b/samples/client/petstore-security-test/go/fake_api.go new file mode 100644 index 00000000000..29df6e2a1aa --- /dev/null +++ b/samples/client/petstore-security-test/go/fake_api.go @@ -0,0 +1,107 @@ +/* + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package swagger + +import ( + "strings" + "fmt" + "errors" + "net/url" + ) + +type FakeApi struct { + Configuration Configuration +} + +func NewFakeApi() *FakeApi { + configuration := NewConfiguration() + return &FakeApi{ + Configuration: *configuration, + } +} + +func NewFakeApiWithBasePath(basePath string) *FakeApi { + configuration := NewConfiguration() + configuration.BasePath = basePath + + return &FakeApi{ + Configuration: *configuration, + } +} + +/** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end \\r\\n \\n \\r + * @return void + */ +func (a FakeApi) TestCodeInjectEndRnNR(testCodeInjectEndRnNR string) (*APIResponse, error) { + + var httpMethod = "Put" + // create path and map variables + path := a.Configuration.BasePath + "/fake" + + + headerParams := make(map[string]string) + queryParams := url.Values{} + formParams := make(map[string]string) + var postBody interface{} + var fileName string + var fileBytes []byte + + // add default headers if any + for key := range a.Configuration.DefaultHeader { + headerParams[key] = a.Configuration.DefaultHeader[key] + } + + + // to determine the Content-Type header + localVarHttpContentTypes := []string{ "application/json", "*_/ ' =end ", } + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + headerParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/json", +"*_/ ' =end ", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + headerParams["Accept"] = localVarHttpHeaderAccept + } + + formParams["testCodeInjectEndRnNR"] = testCodeInjectEndRnNR + + httpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes) + if err != nil { + return NewAPIResponse(httpResponse.RawResponse), err + } + + return NewAPIResponse(httpResponse.RawResponse), err +} + diff --git a/samples/client/petstore-security-test/go/git_push.sh b/samples/client/petstore-security-test/go/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/go/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore-security-test/go/model_return.go b/samples/client/petstore-security-test/go/model_return.go new file mode 100644 index 00000000000..d9202b31736 --- /dev/null +++ b/samples/client/petstore-security-test/go/model_return.go @@ -0,0 +1,30 @@ +/* + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * Generated by: https://github.com/swagger-api/swagger-codegen.git + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package swagger + +// Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r +type ModelReturn struct { + + // property description *_/ ' \" =end \\r\\n \\n \\r + Return_ int32 `json:"return,omitempty"` +} diff --git a/samples/client/petstore-security-test/go/pom.xml b/samples/client/petstore-security-test/go/pom.xml new file mode 100644 index 00000000000..50bfe7f14f8 --- /dev/null +++ b/samples/client/petstore-security-test/go/pom.xml @@ -0,0 +1,75 @@ + + 4.0.0 + com.wordnik + Goswagger + pom + 1.0.0 + Goswagger + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + go-get-testify + pre-integration-test + + exec + + + go + + get + github.com/stretchr/testify/assert + + + + + go-get-sling + pre-integration-test + + exec + + + go + + get + github.com/dghubble/sling + + + + + go-test + integration-test + + exec + + + go + + test + -v + + + + + + + + \ No newline at end of file diff --git a/samples/client/petstore-security-test/objc/.gitignore b/samples/client/petstore-security-test/objc/.gitignore new file mode 100644 index 00000000000..79d9331b6d4 --- /dev/null +++ b/samples/client/petstore-security-test/objc/.gitignore @@ -0,0 +1,53 @@ +# 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 +*.xccheckout +*.moved-aside +*.xcuserstate +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa + +# 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://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md + +fastlane/report.xml +fastlane/screenshots diff --git a/samples/client/petstore-security-test/objc/.swagger-codegen-ignore b/samples/client/petstore-security-test/objc/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/objc/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/objc/LICENSE b/samples/client/petstore-security-test/objc/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/objc/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/objc/README.md b/samples/client/petstore-security-test/objc/README.md new file mode 100644 index 00000000000..3365aba9056 --- /dev/null +++ b/samples/client/petstore-security-test/objc/README.md @@ -0,0 +1,113 @@ +# SwaggerClient + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + +This ObjC package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: + +- API version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +- Package version: +- Build date: 2016-07-12T17:06:42.405+08:00 +- Build package: class io.swagger.codegen.languages.ObjcClientCodegen + +## Requirements + +The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.com/questions/7778356/how-to-enable-disable-automatic-reference-counting) to be enabled in the Xcode project. + +## Installation & Usage +### Install from Github using [CocoaPods](https://cocoapods.org/) + +Add the following to the Podfile: + +```ruby +pod 'SwaggerClient', :git => 'https://github.com/GIT_USER_ID/GIT_REPO_ID.git' +``` + +To specify a particular branch, append `, :branch => 'branch-name-here'` + +To specify a particular commit, append `, :commit => '11aa22'` + +### Install from local path using [CocoaPods](https://cocoapods.org/) + +Put the SDK under your project folder (e.g. /path/to/objc_project/Vendor/SwaggerClient) and then add the following to the Podfile: + +```ruby +pod 'SwaggerClient', :path => 'Vendor/SwaggerClient' +``` + +### Usage + +Import the following: + +```objc +#import +#import +// load models +#import +// load API classes for accessing endpoints +#import + +``` + +## Recommendation + +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. + +## Getting Started + +Please follow the [installation procedure](#installation--usage) and then run the following: + +```objc + + +NSString* *testCodeInjectEndRnNR = @"testCodeInjectEndRnNR_example"; // To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + +SWGFakeApi *apiInstance = [[SWGFakeApi alloc] init]; + +// To test code injection *_/ ' \" =end \\r\\n \\n \\r +[apiInstance testCodeInjectEndRnNRWithTestCodeInjectEndRnNR:testCodeInjectEndRnNR + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error: %@", error); + } + }]; + +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*SWGFakeApi* | [**testCodeInjectEndRnNR**](docs/SWGFakeApi.md#testcodeinjectendrnnr) | **PUT** /fake | To test code injection *_/ ' \" =end \\r\\n \\n \\r + + +## Documentation For Models + + - [SWGReturn](docs/SWGReturn.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key */ ' " =end \r\n \n \r +- **Location**: HTTP header + +## petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account */ ' " =end \r\n \n \r + - **read:pets**: read your pets */ ' " =end \r\n \n \r + + +## Author + +apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + + diff --git a/samples/client/petstore-security-test/objc/SwaggerClient.podspec b/samples/client/petstore-security-test/objc/SwaggerClient.podspec new file mode 100644 index 00000000000..b3ef54ca1de --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient.podspec @@ -0,0 +1,37 @@ +# +# Be sure to run `pod lib lint SwaggerClient.podspec' to ensure this is a +# valid spec and remove all comments before submitting the spec. +# +# Any lines starting with a # are optional, but encouraged +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html +# + +Pod::Spec.new do |s| + s.name = "SwaggerClient" + s.version = "1.0.0" + + s.summary = "Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r" + s.description = <<-DESC + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + DESC + + s.platform = :ios, '7.0' + s.requires_arc = true + + s.framework = 'SystemConfiguration' + + s.homepage = "https://github.com/swagger-api/swagger-codegen" + s.license = "Apache License, Version 2.0" + s.source = { :git => "https://github.com/swagger-api/swagger-codegen.git", :tag => "#{s.version}" } + s.author = { "Swagger" => "apiteam@swagger.io" } + + s.source_files = 'SwaggerClient/**/*.{m,h}' + s.public_header_files = 'SwaggerClient/**/*.h' + + + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' + s.dependency 'ISO8601', '~> 0.5' +end + diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Api/SWGFakeApi.h b/samples/client/petstore-security-test/objc/SwaggerClient/Api/SWGFakeApi.h new file mode 100644 index 00000000000..50daf69d833 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Api/SWGFakeApi.h @@ -0,0 +1,49 @@ +#import +#import "SWGApi.h" + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +@interface SWGFakeApi: NSObject + +extern NSString* kSWGFakeApiErrorDomain; +extern NSInteger kSWGFakeApiMissingParamErrorCode; + ++(instancetype) sharedAPI; + +/// To test code injection *_/ ' \" =end \\r\\n \\n \\r +/// +/// +/// @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) +/// +/// code:400 message:"To test code injection *_/ ' \" =end \\r\\n \\n \\r" +/// +/// @return +-(NSNumber*) testCodeInjectEndRnNRWithTestCodeInjectEndRnNR: (NSString*) testCodeInjectEndRnNR + completionHandler: (void (^)(NSError* error)) handler; + + + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Api/SWGFakeApi.m b/samples/client/petstore-security-test/objc/SwaggerClient/Api/SWGFakeApi.m new file mode 100644 index 00000000000..33c15278886 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Api/SWGFakeApi.m @@ -0,0 +1,138 @@ +#import "SWGFakeApi.h" +#import "SWGQueryParamCollection.h" + + +@interface SWGFakeApi () + +@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; + +@end + +@implementation SWGFakeApi + +NSString* kSWGFakeApiErrorDomain = @"SWGFakeApiErrorDomain"; +NSInteger kSWGFakeApiMissingParamErrorCode = 234513; + +@synthesize apiClient = _apiClient; + +#pragma mark - Initialize methods + +- (instancetype) init { + self = [super init]; + if (self) { + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + if (config.apiClient == nil) { + config.apiClient = [[SWGApiClient alloc] init]; + } + _apiClient = config.apiClient; + _defaultHeaders = [NSMutableDictionary dictionary]; + } + return self; +} + +- (id) initWithApiClient:(SWGApiClient *)apiClient { + self = [super init]; + if (self) { + _apiClient = apiClient; + _defaultHeaders = [NSMutableDictionary dictionary]; + } + return self; +} + +#pragma mark - + ++ (instancetype)sharedAPI { + static SWGFakeApi *sharedAPI; + static dispatch_once_t once; + dispatch_once(&once, ^{ + sharedAPI = [[self alloc] init]; + }); + return sharedAPI; +} + +-(NSString*) defaultHeaderForKey:(NSString*)key { + return self.defaultHeaders[key]; +} + +-(void) addHeader:(NSString*)value forKey:(NSString*)key { + [self setDefaultHeaderValue:value forKey:key]; +} + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { + [self.defaultHeaders setValue:value forKey:key]; +} + +-(NSUInteger) requestQueueSize { + return [SWGApiClient requestQueueSize]; +} + +#pragma mark - Api Methods + +/// +/// To test code injection *_/ ' \" =end \\r\\n \\n \\r +/// +/// @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) +/// +/// @returns void +/// +-(NSNumber*) testCodeInjectEndRnNRWithTestCodeInjectEndRnNR: (NSString*) testCodeInjectEndRnNR + completionHandler: (void (^)(NSError* error)) handler { + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/fake"]; + + // remove format in URL if needed + [resourcePath replaceOccurrencesOfString:@".{format}" withString:@".json" options:0 range:NSMakeRange(0,resourcePath.length)]; + + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.apiClient.configuration.defaultHeaders]; + [headerParams addEntriesFromDictionary:self.defaultHeaders]; + // HTTP header `Accept` + NSString *acceptHeader = [self.apiClient.sanitizer selectHeaderAccept:@[@"application/json", @"*/ ' =end + + "]]; + if(acceptHeader.length > 0) { + headerParams[@"Accept"] = acceptHeader; + } + + // response content type + NSString *responseContentType = [[acceptHeader componentsSeparatedByString:@", "] firstObject] ?: @""; + + // request content type + NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[@"application/json", @"*/ ' =end + + "]]; + + // Authentication setting + NSArray *authSettings = @[]; + + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *localVarFiles = [[NSMutableDictionary alloc] init]; + if (testCodeInjectEndRnNR) { + formParams[@"test code inject */ ' " =end \r\n \n \r"] = testCodeInjectEndRnNR; + } + + return [self.apiClient requestWithPath: resourcePath + method: @"PUT" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: localVarFiles + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: nil + completionBlock: ^(id data, NSError *error) { + if(handler) { + handler(error); + } + } + ]; +} + + + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.h new file mode 100644 index 00000000000..e91fb24ebcf --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.h @@ -0,0 +1,31 @@ +#import +#import +#import + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +@interface JSONValueTransformer (ISO8601) + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.m b/samples/client/petstore-security-test/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.m new file mode 100644 index 00000000000..cec8bdeea27 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/JSONValueTransformer+ISO8601.m @@ -0,0 +1,10 @@ +#import "JSONValueTransformer+ISO8601.h" + +@implementation JSONValueTransformer (ISO8601) + +- (NSDate *) NSDateFromNSString:(NSString *)string +{ + return [NSDate dateWithISO8601String:string]; +} + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApi.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApi.h new file mode 100644 index 00000000000..754b95d7b44 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApi.h @@ -0,0 +1,42 @@ +#import +#import "SWGObject.h" +#import "SWGApiClient.h" + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +@protocol SWGApi + +@property(nonatomic, assign) SWGApiClient *apiClient; + +-(id) initWithApiClient:(SWGApiClient *)apiClient; + +-(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:"); + +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; +-(NSString*) defaultHeaderForKey:(NSString*)key; + +-(NSUInteger) requestQueueSize; + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApiClient.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApiClient.h new file mode 100644 index 00000000000..47e66aa1a3b --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApiClient.h @@ -0,0 +1,206 @@ +#import +#import +#import +#import "SWGJSONResponseSerializer.h" +#import "SWGJSONRequestSerializer.h" +#import "SWGQueryParamCollection.h" +#import "SWGConfiguration.h" +#import "SWGResponseDeserializer.h" +#import "SWGSanitizer.h" +#import "SWGLogger.h" + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#import "SWGReturn.h" + + + +@class SWGConfiguration; + +/** + * A key for `NSError` user info dictionaries. + * + * The corresponding value is the parsed response body for an HTTP error. + */ +extern NSString *const SWGResponseObjectErrorKey; + +@interface SWGApiClient : AFHTTPSessionManager + +@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; +@property(nonatomic, assign) NSTimeInterval timeoutInterval; +@property(nonatomic, readonly) NSOperationQueue* queue; + +/// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one SWGApiClient instance per thread. +@property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders; + +@property(nonatomic, strong) id responseDeserializer; + +@property(nonatomic, strong) id sanitizer; +/** + * Clears Cache + */ ++(void)clearCache; + +/** + * Turns on cache + * + * @param enabled If the cached is enable, must be `YES` or `NO` + */ ++(void)setCacheEnabled:(BOOL) enabled; + +/** + * Gets the request queue size + * + * @return The size of `queuedRequests` static variable. + */ ++(NSUInteger)requestQueueSize; + +/** + * Sets the client unreachable + * + * @param state off line state, must be `YES` or `NO` + */ ++(void) setOfflineState:(BOOL) state; + +/** + * Gets if the client is unreachable + * + * @return The client offline state + */ ++(BOOL) getOfflineState; + +/** + * Sets the client reachability, this may be overridden by the reachability manager if reachability changes + * + * @param The client reachability. + */ ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; + +/** + * Gets the client reachability + * + * @return The client reachability. + */ ++(AFNetworkReachabilityStatus) getReachabilityStatus; + +/** + * Gets the next request id + * + * @return The next executed request id. + */ ++(NSNumber*) nextRequestId; + +/** + * Generates request id and add it to the queue + * + * @return The next executed request id. + */ ++(NSNumber*) queueRequest; + +/** + * Removes request id from the queue + * + * @param requestId The request which will be removed. + */ ++(void) cancelRequest:(NSNumber*)requestId; + +/** + * Customizes the behavior when the reachability changed + * + * @param changeBlock The block will be executed when the reachability changed. + */ ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; + +/** + * Sets the api client reachability strategy + */ +- (void)configureCacheReachibility; + +/** + * Sets header for request + * + * @param value The header value + * @param forKey The header key + */ +-(void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey; + +/** + * Updates header parameters and query parameters for authentication + * + * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param querys The query parameters will be updated, passed by pointer to pointer. + * @param authSettings The authentication names NSArray. + */ +- (void) updateHeaderParams:(NSDictionary **)headers + queryParams:(NSDictionary **)querys + WithAuthSettings:(NSArray *)authSettings; + +/** + * Performs request + * + * @param path Request url. + * @param method Request method. + * @param pathParams Request path parameters. + * @param queryParams Request query parameters. + * @param body Request body. + * @param headerParams Request header parameters. + * @param authSettings Request authentication names. + * @param requestContentType Request content-type. + * @param responseContentType Response content-type. + * @param completionBlock The block will be executed when the request completed. + * + * @return The request id. + */ +-(NSNumber*) requestWithPath:(NSString*) path + method:(NSString*) method + pathParams:(NSDictionary *) pathParams + queryParams:(NSDictionary*) queryParams + formParams:(NSDictionary *) formParams + files:(NSDictionary *) files + body:(id) body + headerParams:(NSDictionary*) headerParams + authSettings:(NSArray *) authSettings + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + responseType:(NSString *) responseType + completionBlock:(void (^)(id, NSError *))completionBlock; + +/** + * Custom security policy + * + * @return AFSecurityPolicy + */ +- (AFSecurityPolicy *) customSecurityPolicy; + +/** + * SWGConfiguration return sharedConfig + * + * @return SWGConfiguration + */ +- (SWGConfiguration*) configuration; + + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApiClient.m b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApiClient.m new file mode 100644 index 00000000000..f004200b2eb --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGApiClient.m @@ -0,0 +1,504 @@ +#import "SWGApiClient.h" + +NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject"; + +static NSUInteger requestId = 0; +static bool offlineState = false; +static NSMutableSet * queuedRequests = nil; +static bool cacheEnabled = false; +static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; +static void (^reachabilityChangeBlock)(int); + + +static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) { + if(![response isKindOfClass:[NSHTTPURLResponse class]]) { + return nil; + } + return ((NSHTTPURLResponse*)response).allHeaderFields; +} + +static NSString * SWG__fileNameForResponse(NSURLResponse *response) { + NSDictionary * headers = SWG__headerFieldsForResponse(response); + if(!headers[@"Content-Disposition"]) { + return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = headers[@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; +} + + +@interface SWGApiClient () + +@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; + +@end + +@implementation SWGApiClient + +- (instancetype)init { + NSString *baseUrl = [[SWGConfiguration sharedConfig] host]; + return [self initWithBaseURL:[NSURL URLWithString:baseUrl]]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + self = [super initWithBaseURL:url]; + if (self) { + self.timeoutInterval = 60; + self.requestSerializer = [AFJSONRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + self.securityPolicy = [self customSecurityPolicy]; + self.responseDeserializer = [[SWGResponseDeserializer alloc] init]; + self.sanitizer = [[SWGSanitizer alloc] init]; + // configure reachability + [self configureCacheReachibility]; + } + return self; +} + ++ (void)initialize { + if (self == [SWGApiClient class]) { + queuedRequests = [[NSMutableSet alloc] init]; + // initialize URL cache + [self configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; + } +} + +#pragma mark - Setter Methods + ++ (void) setOfflineState:(BOOL) state { + offlineState = state; +} + ++ (void) setCacheEnabled:(BOOL)enabled { + cacheEnabled = enabled; +} + ++(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { + reachabilityStatus = status; +} + +- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { + [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; +} + +- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { + [super setRequestSerializer:requestSerializer]; + requestSerializer.timeoutInterval = self.timeoutInterval; +} + +#pragma mark - Cache Methods + ++(void)clearCache { + [[NSURLCache sharedURLCache] removeAllCachedResponses]; +} + ++(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize + diskSize: (unsigned long) diskSize { + NSAssert(memorySize > 0, @"invalid in-memory cache size"); + NSAssert(diskSize >= 0, @"invalid disk cache size"); + + NSURLCache *cache = + [[NSURLCache alloc] + initWithMemoryCapacity:memorySize + diskCapacity:diskSize + diskPath:@"swagger_url_cache"]; + + [NSURLCache setSharedURLCache:cache]; +} + +#pragma mark - Request Methods + ++(NSUInteger)requestQueueSize { + return [queuedRequests count]; +} + ++(NSNumber*) nextRequestId { + @synchronized(self) { + return @(++requestId); + } +} + ++(NSNumber*) queueRequest { + NSNumber* requestId = [[self class] nextRequestId]; + SWGDebugLog(@"added %@ to request queue", requestId); + [queuedRequests addObject:requestId]; + return requestId; +} + ++(void) cancelRequest:(NSNumber*)requestId { + [queuedRequests removeObject:requestId]; +} + +-(Boolean) executeRequestWithId:(NSNumber*) requestId { + NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { + return [obj intValue] == [requestId intValue]; + }]; + + if (matchingItems.count == 1) { + SWGDebugLog(@"removed request id %@", requestId); + [queuedRequests removeObject:requestId]; + return YES; + } else { + return NO; + } +} + +#pragma mark - Reachability Methods + ++(AFNetworkReachabilityStatus) getReachabilityStatus { + return reachabilityStatus; +} + ++(BOOL) getOfflineState { + return offlineState; +} + ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { + reachabilityChangeBlock = changeBlock; +} + +- (void) configureCacheReachibility { + [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + reachabilityStatus = status; + SWGDebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); + [SWGApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; + + // call the reachability block, if configured + if (reachabilityChangeBlock != nil) { + reachabilityChangeBlock(status); + } + }]; + + [self.reachabilityManager startMonitoring]; +} + +#pragma mark - Operation Methods + +- (void) operationWithCompletionBlock: (NSURLRequest *)request + requestId: (NSNumber *) requestId + completionBlock: (void (^)(id, NSError *))completionBlock { + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } + SWGDebugLogResponse(response, responseObject,request,error); + strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); + if(!error) { + completionBlock(responseObject, nil); + return; + } + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + // Add in the (parsed) response body. + userInfo[SWGResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + }]; + [op resume]; +} + +- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request + requestId: (NSNumber *) requestId + completionBlock: (void (^)(id, NSError *))completionBlock { + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } + strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); + SWGDebugLogResponse(response, responseObject,request,error); + if(error) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + userInfo[SWGResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + } + NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory(); + NSString * filename = SWG__fileNameForResponse(response); + + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; + + [responseObject writeToURL:file atomically:YES]; + + completionBlock(file, nil); + }]; + [op resume]; +} + +#pragma mark - Perform Request Methods + +-(NSNumber*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock { + // setting request serializer + if ([requestContentType isEqualToString:@"application/json"]) { + self.requestSerializer = [SWGJSONRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else if ([requestContentType isEqualToString:@"multipart/form-data"]) { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + } + else { + self.requestSerializer = [AFHTTPRequestSerializer serializer]; + NSAssert(NO, @"Unsupported request type %@", requestContentType); + } + + // setting response serializer + if ([responseContentType isEqualToString:@"application/json"]) { + self.responseSerializer = [SWGJSONResponseSerializer serializer]; + } else { + self.responseSerializer = [AFHTTPResponseSerializer serializer]; + } + + // sanitize parameters + pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; + queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; + headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; + formParams = [self.sanitizer sanitizeForSerialization:formParams]; + if(![body isKindOfClass:[NSData class]]) { + body = [self.sanitizer sanitizeForSerialization:body]; + } + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + + NSMutableString *resourcePath = [NSMutableString stringWithString:path]; + [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSString * safeString = ([obj isKindOfClass:[NSString class]]) ? obj : [NSString stringWithFormat:@"%@", obj]; + safeString = SWGPercentEscapedStringFromString(safeString); + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; + }]; + + NSMutableURLRequest * request = nil; + + NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; + if ([pathWithQueryParams hasPrefix:@"/"]) { + pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; + } + + NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + if (files.count > 0) { + __weak __typeof(self)weakSelf = self; + request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" + URLString:urlString + parameters:nil + constructingBodyWithBlock:^(id formData) { + [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSString *objString = [weakSelf.sanitizer parameterToString:obj]; + NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; + [formData appendPartWithFormData:data name:key]; + }]; + [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSURL *filePath = (NSURL *)obj; + [formData appendPartWithFileURL:filePath name:key error:nil]; + }]; + } error:nil]; + } + else { + if (formParams) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:formParams + error:nil]; + } + if (body) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:body + error:nil]; + } + } + + // request cache + BOOL hasHeaderParams = [headerParams count] > 0; + if (offlineState) { + SWGDebugLog(@"%@ cache forced", resourcePath); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + SWGDebugLog(@"%@ cache enabled", resourcePath); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + SWGDebugLog(@"%@ cache disabled", resourcePath); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + if (hasHeaderParams){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + + [self postProcessRequest:request]; + + NSNumber* requestId = [SWGApiClient queueRequest]; + if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { + [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + completionBlock(data, error); + }]; + } + else { + [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + NSError * serializationError; + id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; + if(!response && !error){ + error = serializationError; + } + completionBlock(response, error); + }]; + } + return requestId; +} + +//Added for easier override to modify request +-(void)postProcessRequest:(NSMutableURLRequest *)request { + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; +} + +#pragma mark - + +- (NSString*) pathWithQueryParamsToString:(NSString*) path + queryParams:(NSDictionary*) queryParams { + if(queryParams.count == 0) { + return path; + } + NSString * separator = nil; + NSUInteger counter = 0; + + NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; + + NSDictionary *separatorStyles = @{@"csv" : @",", + @"tsv" : @"\t", + @"pipes": @"|" + }; + for(NSString * key in [queryParams keyEnumerator]){ + if (counter == 0) { + separator = @"?"; + } else { + separator = @"&"; + } + id queryParam = [queryParams valueForKey:key]; + if(!queryParam) { + continue; + } + NSString *safeKey = SWGPercentEscapedStringFromString(key); + if ([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, SWGPercentEscapedStringFromString(queryParam)]]; + + } else if ([queryParam isKindOfClass:[SWGQueryParamCollection class]]){ + SWGQueryParamCollection * coll = (SWGQueryParamCollection*) queryParam; + NSArray* values = [coll values]; + NSString* format = [coll format]; + + if([format isEqualToString:@"multi"]) { + for(id obj in values) { + if (counter > 0) { + separator = @"&"; + } + NSString * safeValue = SWGPercentEscapedStringFromString([NSString stringWithFormat:@"%@",obj]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + counter += 1; + } + continue; + } + NSString * separatorStyle = separatorStyles[format]; + NSString * safeValue = SWGPercentEscapedStringFromString([values componentsJoinedByString:separatorStyle]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } else { + NSString * safeValue = SWGPercentEscapedStringFromString([NSString stringWithFormat:@"%@",queryParam]); + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, safeKey, safeValue]]; + } + counter += 1; + } + return requestUrl; +} + +/** + * Update header and query params based on authentication settings + */ +- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers + queryParams:(NSDictionary *__autoreleasing *)querys + WithAuthSettings:(NSArray *)authSettings { + + if ([authSettings count] == 0) { + return; + } + + NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; + NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; + + NSDictionary* configurationAuthSettings = [[self configuration] authSettings]; + for (NSString *auth in authSettings) { + NSDictionary *authSetting = configurationAuthSettings[auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty + continue; + } + NSString *type = authSetting[@"in"]; + NSString *key = authSetting[@"key"]; + NSString *value = authSetting[@"value"]; + if ([type isEqualToString:@"header"] && [key length] > 0 ) { + headersWithAuth[key] = value; + } else if ([type isEqualToString:@"query"] && [key length] != 0) { + querysWithAuth[key] = value; + } + } + + *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; + *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; +} + +- (AFSecurityPolicy *) customSecurityPolicy { + AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + + SWGConfiguration *config = [self configuration]; + + if (config.sslCaCert) { + NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; + [securityPolicy setPinnedCertificates:@[certData]]; + } + + if (config.verifySSL) { + [securityPolicy setAllowInvalidCertificates:NO]; + } + else { + [securityPolicy setAllowInvalidCertificates:YES]; + [securityPolicy setValidatesDomainName:NO]; + } + + return securityPolicy; +} + +- (SWGConfiguration*) configuration { + return [SWGConfiguration sharedConfig]; +} + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGConfiguration.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGConfiguration.h new file mode 100644 index 00000000000..b1bbd4bc7f6 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGConfiguration.h @@ -0,0 +1,182 @@ +#import +#import "SWGApiClient.h" +#import "SWGLogger.h" + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +@class SWGApiClient; + +@interface SWGConfiguration : NSObject + +/** + * Default api logger + */ +@property (nonatomic, strong) SWGLogger * logger; + +/** + * Default api client + */ +@property (nonatomic) SWGApiClient *apiClient; + +/** + * Default base url + */ +@property (nonatomic) NSString *host; + +/** + * Api key values for Api Key type Authentication + * + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + * + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; + +/** + * Username for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (nonatomic) NSString *password; + +/** + * Access token for OAuth + */ +@property (nonatomic) NSString *accessToken; + +/** + * Temp folder for file download + */ +@property (nonatomic) NSString *tempFolderPath; + +/** + * Debug switch, default false + */ +@property (nonatomic) BOOL debug; + +/** + * Gets configuration singleton instance + */ ++ (instancetype) sharedConfig; + +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (nonatomic) NSString *sslCaCert; + +/** + * Sets API key + * + * To remove a apiKey for an identifier, just set the apiKey to nil. + * + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). + * + */ +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; + +/** + * Removes api key + * + * @param identifier API key identifier. + */ +- (void) removeApiKey:(NSString *)identifier; + +/** + * Sets the prefix for API key + * + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. + */ +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Removes api key prefix + * + * @param identifier API key identifier. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; + +/** + * Gets API key (with prefix if set) + */ +- (NSString *) getApiKeyWithPrefix:(NSString *) key; + +/** + * Gets Basic Auth token + */ +- (NSString *) getBasicAuthToken; + +/** + * Gets OAuth access token + */ +- (NSString *) getAccessToken; + +/** + * Gets Authentication Settings + */ +- (NSDictionary *) authSettings; + +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; + +/** +* Removes header from defaultHeaders +* +* @param Header name. +*/ +-(void) removeDefaultHeaderForKey:(NSString*)key; + +/** +* Sets the header for key +* +* @param value Value for header name +* @param key Header name +*/ +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; + +/** +* @param Header key name. +*/ +-(NSString*) defaultHeaderForKey:(NSString*)key; + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGConfiguration.m b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGConfiguration.m new file mode 100644 index 00000000000..ecc6cc4b6ed --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGConfiguration.m @@ -0,0 +1,160 @@ +#import "SWGConfiguration.h" + +@interface SWGConfiguration () + +@property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders; +@property (nonatomic, strong) NSMutableDictionary *mutableApiKey; +@property (nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix; + +@end + +@implementation SWGConfiguration + +#pragma mark - Singleton Methods + ++ (instancetype) sharedConfig { + static SWGConfiguration *shardConfig = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardConfig = [[self alloc] init]; + }); + return shardConfig; +} + +#pragma mark - Initialize Methods + +- (instancetype) init { + self = [super init]; + if (self) { + self.apiClient = nil; + self.host = @"https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r"; + self.username = @""; + self.password = @""; + self.accessToken= @""; + self.verifySSL = YES; + self.mutableApiKey = [NSMutableDictionary dictionary]; + self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + self.mutableDefaultHeaders = [NSMutableDictionary dictionary]; + self.mutableDefaultHeaders[@"User-Agent"] = [NSString stringWithFormat:@"Swagger-Codegen/1.0.0 *_/ ' \" =end \\r\\n \\n \\r/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; + self.logger = [SWGLogger sharedLogger]; + } + return self; +} + +#pragma mark - Instance Methods + +- (NSString *) getApiKeyWithPrefix:(NSString *)key { + NSString *prefix = self.apiKeyPrefix[key]; + NSString *apiKey = self.apiKey[key]; + if (prefix && apiKey != (id)[NSNull null] && apiKey.length > 0) { // both api key prefix and api key are set + return [NSString stringWithFormat:@"%@ %@", prefix, apiKey]; + } + else if (apiKey != (id)[NSNull null] && apiKey.length > 0) { // only api key, no api key prefix + return [NSString stringWithFormat:@"%@", self.apiKey[key]]; + } + else { // return empty string if nothing is set + return @""; + } +} + +- (NSString *) getBasicAuthToken { + // return empty string if username and password are empty + if (self.username.length == 0 && self.password.length == 0){ + return @""; + } + + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + +- (NSString *) getAccessToken { + if (self.accessToken.length == 0) { // token not set, return empty string + return @""; + } else { + return [NSString stringWithFormat:@"Bearer %@", self.accessToken]; + } +} + +#pragma mark - Setter Methods + +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { + [self.mutableApiKey setValue:apiKey forKey:identifier]; +} + +- (void) removeApiKey:(NSString *)identifier { + [self.mutableApiKey removeObjectForKey:identifier]; +} + +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { + [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; +} + +- (void) removeApiKeyPrefix:(NSString *)identifier { + [self.mutableApiKeyPrefix removeObjectForKey:identifier]; +} + +#pragma mark - Getter Methods + +- (NSDictionary *) apiKey { + return [NSDictionary dictionaryWithDictionary:self.mutableApiKey]; +} + +- (NSDictionary *) apiKeyPrefix { + return [NSDictionary dictionaryWithDictionary:self.mutableApiKeyPrefix]; +} + +#pragma mark - + +- (NSDictionary *) authSettings { + return @{ + @"api_key": + @{ + @"type": @"api_key", + @"in": @"header", + @"key": @"api_key */ ' " =end \r\n \n \r", + @"value": [self getApiKeyWithPrefix:@"api_key */ ' " =end \r\n \n \r"] + }, + @"petstore_auth": + @{ + @"type": @"oauth", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getAccessToken] + }, + }; +} + +-(BOOL)debug { + return self.logger.isEnabled; +} + +-(void)setDebug:(BOOL)debug { + self.logger.enabled = debug; +} + + + +- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { + if(!value) { + [self.mutableDefaultHeaders removeObjectForKey:key]; + return; + } + self.mutableDefaultHeaders[key] = value; +} + +-(void) removeDefaultHeaderForKey:(NSString*)key { + [self.mutableDefaultHeaders removeObjectForKey:key]; +} + +- (NSString *)defaultHeaderForKey:(NSString *)key { + return self.mutableDefaultHeaders[key]; +} + +- (NSDictionary *)defaultHeaders { + return [self.mutableDefaultHeaders copy]; +} + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONRequestSerializer.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONRequestSerializer.h new file mode 100644 index 00000000000..dbfe377577e --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONRequestSerializer.h @@ -0,0 +1,29 @@ +#import +#import + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +@interface SWGJSONRequestSerializer : AFJSONRequestSerializer +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m new file mode 100644 index 00000000000..221765e4839 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONRequestSerializer.m @@ -0,0 +1,37 @@ +#import "SWGJSONRequestSerializer.h" + +@implementation SWGJSONRequestSerializer + +/// +/// When customize a request serializer, +/// the serializer must conform the protocol `AFURLRequestSerialization` +/// and implements the protocol method `requestBySerializingRequest:withParameters:error:` +/// +/// @param request The original request. +/// @param parameters The parameters to be encoded. +/// @param error The error that occurred while attempting to encode the request parameters. +/// +/// @return A serialized request. +/// +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + if (!parameters) { + return request; + } + // If the body data which will be serialized isn't NSArray or NSDictionary + // then put the data in the http request body directly. + if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + if([parameters isKindOfClass:[NSData class]]) { + [mutableRequest setHTTPBody:parameters]; + } else { + [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; + } + return mutableRequest; +} + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONResponseSerializer.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONResponseSerializer.h new file mode 100644 index 00000000000..1ee459e4157 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONResponseSerializer.h @@ -0,0 +1,30 @@ +#import +#import + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +@interface SWGJSONResponseSerializer : AFJSONResponseSerializer + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONResponseSerializer.m b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONResponseSerializer.m new file mode 100644 index 00000000000..73c696d341a --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGJSONResponseSerializer.m @@ -0,0 +1,39 @@ +#import "SWGJSONResponseSerializer.h" + +@implementation SWGJSONResponseSerializer + +/// +/// When customize a response serializer, +/// the serializer must conform the protocol `AFURLResponseSerialization` +/// and implements the protocol method `responseObjectForResponse:error:` +/// +/// @param response The response to be processed. +/// @param data The response data to be decoded. +/// @param error The error that occurred while attempting to decode the response data. +/// +/// @return The object decoded from the specified response data. +/// +- (id) responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error { + NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; + + // if response data is not a valid json, return string of data. + if ([self isParseError:*error]) { + *error = nil; + NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + return responseString; + } + + return responseJson; +} + +-(BOOL)isParseError:(NSError *)error { + return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840; +} + ++ (instancetype)serializer { + return [self serializerWithReadingOptions:NSJSONReadingAllowFragments]; +} + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGLogger.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGLogger.h new file mode 100644 index 00000000000..ecf02f24322 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGLogger.h @@ -0,0 +1,72 @@ +#import + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#ifndef SWGDebugLogResponse +#define SWGDebugLogResponse(response, responseObject,request, error) [[SWGLogger sharedLogger] logResponse:response responseObject:responseObject request:request error:error]; +#endif + +/** + * Log debug message macro + */ +#ifndef SWGDebugLog +#define SWGDebugLog(format, ...) [[SWGLogger sharedLogger] debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#endif + +@interface SWGLogger : NSObject + ++(instancetype)sharedLogger; + +/** + * Enabled switch, default NO - default set by SWGConfiguration debug property + */ +@property (nonatomic, assign, getter=isEnabled) BOOL enabled; + +/** + * Debug file location, default log in console + */ +@property (nonatomic, strong) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, strong, readonly) NSFileHandle *loggingFileHandler; + +/** + * Log debug message + */ +-(void)debugLog:(NSString *)method message:(NSString *)format, ...; + +/** + * Logs request and response + * + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. + * @param request The HTTP request. + * @param error The error of the HTTP request. + */ +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error; + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGLogger.m b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGLogger.m new file mode 100644 index 00000000000..322ae9678d7 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGLogger.m @@ -0,0 +1,74 @@ +#import "SWGLogger.h" + +@interface SWGLogger () + +@end + +@implementation SWGLogger + ++ (instancetype) sharedLogger { + static SWGLogger *shardLogger = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardLogger = [[self alloc] init]; + }); + return shardLogger; +} + +#pragma mark - Log Methods + +- (void)debugLog:(NSString *)method + message:(NSString *)format, ... { + if (!self.isEnabled) { + return; + } + + NSMutableString *message = [NSMutableString stringWithCapacity:1]; + + if (method) { + [message appendFormat:@"%@: ", method]; + } + + va_list args; + va_start(args, format); + + [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; + + // If set logging file handler, log into file, + // otherwise log into console. + if (self.loggingFileHandler) { + [self.loggingFileHandler seekToEndOfFile]; + [self.loggingFileHandler writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; + } else { + NSLog(@"%@", message); + } + + va_end(args); +} + +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ + "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], + responseObject]; + + SWGDebugLog(message); +} + +- (void) setLoggingFile:(NSString *)loggingFile { + if(_loggingFile == loggingFile) { + return; + } + // close old file handler + if ([self.loggingFileHandler isKindOfClass:[NSFileHandle class]]) { + [self.loggingFileHandler closeFile]; + } + _loggingFile = loggingFile; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHandler == nil) { + [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; + _loggingFileHandler = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + } +} + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGObject.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGObject.h new file mode 100644 index 00000000000..51443974b74 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGObject.h @@ -0,0 +1,30 @@ +#import +#import + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +@interface SWGObject : JSONModel + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGObject.m b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGObject.m new file mode 100644 index 00000000000..8085c404f7e --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGObject.m @@ -0,0 +1,13 @@ +#import "SWGObject.h" + +@implementation SWGObject + +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGQueryParamCollection.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGQueryParamCollection.h new file mode 100644 index 00000000000..ec702737c97 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGQueryParamCollection.h @@ -0,0 +1,35 @@ +#import + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +@interface SWGQueryParamCollection : NSObject + +@property(nonatomic, readonly) NSArray* values; +@property(nonatomic, readonly) NSString* format; + +- (id) initWithValuesAndFormat: (NSArray*) values + format: (NSString*) format; + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGQueryParamCollection.m b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGQueryParamCollection.m new file mode 100644 index 00000000000..83303045185 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGQueryParamCollection.m @@ -0,0 +1,16 @@ +#import "SWGQueryParamCollection.h" + +@implementation SWGQueryParamCollection + +@synthesize values = _values; +@synthesize format = _format; + +- (id) initWithValuesAndFormat: (NSArray*) values + format: (NSString*) format { + _values = values; + _format = format; + + return self; +} + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGResponseDeserializer.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGResponseDeserializer.h new file mode 100644 index 00000000000..c9fa7e99f1d --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGResponseDeserializer.h @@ -0,0 +1,68 @@ +#import + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/** + * A key for deserialization ErrorDomain + */ +extern NSString *const SWGDeserializationErrorDomainKey; + +/** + * Code for deserialization type mismatch error + */ +extern NSInteger const SWGTypeMismatchErrorCode; + +/** + * Code for deserialization empty value error + */ +extern NSInteger const SWGEmptyValueOccurredErrorCode; + +/** + * Error code for unknown response + */ +extern NSInteger const SWGUnknownResponseObjectErrorCode; + +@protocol SWGResponseDeserializer + +/** + * Deserializes the given data to Objective-C object. + * + * @param data The data will be deserialized. + * @param class The type of objective-c object. + * @param error The error + */ +- (id) deserialize:(id) data class:(NSString *) className error:(NSError**)error; + +@end + +@interface SWGResponseDeserializer : NSObject + +/** + * If an null value occurs in dictionary or array if set to YES whole response will be invalid else will be ignored + * @default NO + */ +@property (nonatomic, assign) BOOL treatNullAsError; + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGResponseDeserializer.m b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGResponseDeserializer.m new file mode 100644 index 00000000000..a0efd1d5927 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGResponseDeserializer.m @@ -0,0 +1,231 @@ +#import "SWGResponseDeserializer.h" +#import +#import + +NSString *const SWGDeserializationErrorDomainKey = @"SWGDeserializationErrorDomainKey"; + +NSInteger const SWGTypeMismatchErrorCode = 143553; + +NSInteger const SWGEmptyValueOccurredErrorCode = 143509; + +NSInteger const SWGUnknownResponseObjectErrorCode = 143528; + + +@interface SWGResponseDeserializer () + +@property (nonatomic, strong) NSNumberFormatter* numberFormatter; +@property (nonatomic, strong) NSArray *primitiveTypes; +@property (nonatomic, strong) NSArray *basicReturnTypes; + +@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression; +@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression; +@property (nonatomic, strong) NSRegularExpression* dictPatExpression; +@property (nonatomic, strong) NSRegularExpression* dictModelsPatExpression; + +@end + +@implementation SWGResponseDeserializer + +- (instancetype)init { + self = [super init]; + if (self) { + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + formatter.numberStyle = NSNumberFormatterDecimalStyle; + _numberFormatter = formatter; + _primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; + _basicReturnTypes = @[@"NSObject", @"id", @"NSData"]; + _arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _arrayOfPrimitivesPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray\\* /\\* (.+) \\*/" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _dictPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\* /\\* (.+?), (.+) \\*/" + options:NSRegularExpressionCaseInsensitive + error:nil]; + _dictModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSDictionary\\<(.+?), (.+)*\\>" + options:NSRegularExpressionCaseInsensitive + error:nil]; + } + return self; +} + +#pragma mark - Deserialize methods + +- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error { + // return nil if data is nil or className is nil + if (!data || !className || [data isKindOfClass:[NSNull class]]) { + return nil; + } + + // remove "*" from className, if ends with "*" + if ([className hasSuffix:@"*"]) { + className = [className substringToIndex:[className length] - 1]; + } + // pure object + if ([self.basicReturnTypes containsObject:className]) { + return data; + } + + // primitives + if ([self.primitiveTypes containsObject:className]) { + return [self deserializePrimitiveValue:data class:className error:error]; + } + + NSTextCheckingResult *match = nil; + NSRange range = NSMakeRange(0, [className length]); + // list of models + match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; + return [self deserializeArrayValue:data innerType:innerType error:error]; + } + + // list of primitives + match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; + return [self deserializeArrayValue:data innerType:innerType error:error]; + } + + // map + match = [self.dictPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; + return [self deserializeDictionaryValue:data valueType:valueType error:error]; + } + + match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range]; + if (match) { + NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; + return [self deserializeDictionaryValue:data valueType:valueType error:error]; + } + + // model + Class ModelClass = NSClassFromString(className); + if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { + return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error]; + } + + if(error) { + *error = [self unknownResponseErrorWithExpectedType:className data:data]; + } + return nil; +} + +- (id) deserializeDictionaryValue:(id) data valueType:(NSString *) valueType error:(NSError**)error { + if(![data isKindOfClass: [NSDictionary class]]) { + if(error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDictionary class]) data:data]; + } + return nil; + } + __block NSMutableDictionary *resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + for (id key in [data allKeys]) { + id obj = [data valueForKey:key]; + id dicObj = [self deserialize:obj class:valueType error:error]; + if(dicObj) { + [resultDict setValue:dicObj forKey:key]; + } else if([obj isKindOfClass:[NSNull class]]) { + if(self.treatNullAsError) { + if (error) { + *error = [self emptyValueOccurredError]; + } + resultDict = nil; + break; + } + } else { + resultDict = nil; + break; + } + } + return resultDict; +} + +- (id) deserializeArrayValue:(id) data innerType:(NSString *) innerType error:(NSError**)error { + if(![data isKindOfClass: [NSArray class]]) { + if(error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSArray class]) data:data]; + } + return nil; + } + NSMutableArray* resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + for (id obj in data) { + id arrObj = [self deserialize:obj class:innerType error:error]; + if(arrObj) { + [resultArray addObject:arrObj]; + } else if([obj isKindOfClass:[NSNull class]]) { + if(self.treatNullAsError) { + if (error) { + *error = [self emptyValueOccurredError]; + } + resultArray = nil; + break; + } + } else { + resultArray = nil; + break; + } + } + return resultArray; +}; + +- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error { + if ([className isEqualToString:@"NSString"]) { + return [NSString stringWithString:data]; + } + else if ([className isEqualToString:@"NSDate"]) { + return [self deserializeDateValue:data error:error]; + } + else if ([className isEqualToString:@"NSNumber"]) { + // NSNumber from NSNumber + if ([data isKindOfClass:[NSNumber class]]) { + return data; + } + else if ([data isKindOfClass:[NSString class]]) { + // NSNumber (NSCFBoolean) from NSString + if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { + return @([data boolValue]); + // NSNumber from NSString + } else { + NSNumber* formattedValue = [self.numberFormatter numberFromString:data]; + if(!formattedValue && [data length] > 0 && error) { + *error = [self typeMismatchErrorWithExpectedType:className data:data]; + } + return formattedValue; + } + } + } + if(error) { + *error = [self typeMismatchErrorWithExpectedType:className data:data]; + } + return nil; +} + +- (id) deserializeDateValue:(id) data error:(NSError**)error { + NSDate *date =[NSDate dateWithISO8601String:data]; + if(!date && [data length] > 0 && error) { + *error = [self typeMismatchErrorWithExpectedType:NSStringFromClass([NSDate class]) data:data]; + } + return date; +}; + +-(NSError *)typeMismatchErrorWithExpectedType:(NSString *)expected data:(id)data { + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Received response [%@] is not an object of type %@",nil),data, expected]; + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGTypeMismatchErrorCode userInfo:userInfo]; +} + +-(NSError *)emptyValueOccurredError { + NSString * message = NSLocalizedString(@"Received response contains null value in dictionary or array response",nil); + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGEmptyValueOccurredErrorCode userInfo:userInfo]; +} + +-(NSError *)unknownResponseErrorWithExpectedType:(NSString *)expected data:(id)data { + NSString * message = [NSString stringWithFormat:NSLocalizedString(@"Unknown response expected type %@ [reponse: %@]",nil),expected,data]; + NSDictionary * userInfo = @{NSLocalizedDescriptionKey : message}; + return [NSError errorWithDomain:SWGDeserializationErrorDomainKey code:SWGUnknownResponseObjectErrorCode userInfo:userInfo]; +} + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGSanitizer.h b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGSanitizer.h new file mode 100644 index 00000000000..f968b13c885 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGSanitizer.h @@ -0,0 +1,67 @@ +#import + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +extern NSString * SWGPercentEscapedStringFromString(NSString *string); + +@protocol SWGSanitizer + +/** + * Sanitize object for request + * + * @param object The query/path/header/form/body param to be sanitized. + */ +- (id) sanitizeForSerialization:(id) object; + +/** + * Convert parameter to NSString + */ +- (NSString *) parameterToString: (id) param; + +/** + * Detects Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header + */ +-(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detects Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header + */ +-(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + +@end + +@interface SWGSanitizer : NSObject + + + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGSanitizer.m b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGSanitizer.m new file mode 100644 index 00000000000..a74f72afbe3 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Core/SWGSanitizer.m @@ -0,0 +1,168 @@ +#import "SWGSanitizer.h" +#import "SWGObject.h" +#import "SWGQueryParamCollection.h" +#import + +NSString * SWGPercentEscapedStringFromString(NSString *string) { + static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@"; + static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;="; + + NSMutableCharacterSet * allowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; + [allowedCharacterSet removeCharactersInString:[kSWGCharactersGeneralDelimitersToEncode stringByAppendingString:kSWGCharactersSubDelimitersToEncode]]; + + static NSUInteger const batchSize = 50; + + NSUInteger index = 0; + NSMutableString *escaped = @"".mutableCopy; + + while (index < string.length) { + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wgnu" + NSUInteger length = MIN(string.length - index, batchSize); + #pragma GCC diagnostic pop + NSRange range = NSMakeRange(index, length); + + // To avoid breaking up character sequences such as 👴🏻👮🏽 + range = [string rangeOfComposedCharacterSequencesForRange:range]; + + NSString *substring = [string substringWithRange:range]; + NSString *encoded = [substring stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacterSet]; + [escaped appendString:encoded]; + + index += range.length; + } + + return escaped; +} + +@interface SWGSanitizer () + +@property (nonatomic, strong) NSRegularExpression* jsonHeaderTypeExpression; + +@end + +@implementation SWGSanitizer + +static NSString * kApplicationJSONType = @"application/json"; + +-(instancetype)init { + self = [super init]; + if ( !self ) { + return nil; + } + _jsonHeaderTypeExpression = [NSRegularExpression regularExpressionWithPattern:@"(.*)application(.*)json(.*)" options:NSRegularExpressionCaseInsensitive error:nil]; + return self; +} + + +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { + return nil; + } + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { + return object; + } + else if ([object isKindOfClass:[NSDate class]]) { + return [self dateParameterToString:object]; + } + else if ([object isKindOfClass:[NSArray class]]) { + NSArray *objectArray = object; + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + [sanitizedObjs addObject:sanitizedObj]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[NSDictionary class]]) { + NSDictionary *objectDict = object; + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + id sanitizedObj = [self sanitizeForSerialization:obj]; + if (sanitizedObj) { + sanitizedObjs[key] = sanitizedObj; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[SWGObject class]]) { + return [object toDictionary]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; + } +} + +- (NSString *) parameterToString:(id)param { + if ([param isKindOfClass:[NSString class]]) { + return param; + } + else if ([param isKindOfClass:[NSNumber class]]) { + return [param stringValue]; + } + else if ([param isKindOfClass:[NSDate class]]) { + return [self dateParameterToString:param]; + } + else if ([param isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableParam = [NSMutableArray array]; + [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [mutableParam addObject:[self parameterToString:obj]]; + }]; + return [mutableParam componentsJoinedByString:@","]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] + userInfo:nil]; + @throw e; + } +} + +- (NSString *)dateParameterToString:(id)param { + return [param ISO8601String]; +} + +#pragma mark - Utility Methods + +/* + * Detect `Accept` from accepts + */ +- (NSString *) selectHeaderAccept:(NSArray *)accepts { + if (accepts.count == 0) { + return @""; + } + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + for (NSString *string in accepts) { + if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { + return kApplicationJSONType; + } + [lowerAccepts addObject:[string lowercaseString]]; + } + return [lowerAccepts componentsJoinedByString:@", "]; +} + +/* + * Detect `Content-Type` from contentTypes + */ +- (NSString *) selectHeaderContentType:(NSArray *)contentTypes { + if (contentTypes.count == 0) { + return kApplicationJSONType; + } + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + for (NSString *string in contentTypes) { + if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ + return kApplicationJSONType; + } + [lowerContentTypes addObject:[string lowercaseString]]; + } + return [lowerContentTypes firstObject]; +} + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Model/SWGReturn.h b/samples/client/petstore-security-test/objc/SwaggerClient/Model/SWGReturn.h new file mode 100644 index 00000000000..d05ae2fc866 --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Model/SWGReturn.h @@ -0,0 +1,39 @@ +#import +#import "SWGObject.h" + +/** +* Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r +* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end +* +* OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +* Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + + +@protocol SWGReturn +@end + +@interface SWGReturn : SWGObject + +/* property description *_/ ' \" =end \\r\\n \\n \\r [optional] + */ +@property(nonatomic) NSNumber* _return; + +@end diff --git a/samples/client/petstore-security-test/objc/SwaggerClient/Model/SWGReturn.m b/samples/client/petstore-security-test/objc/SwaggerClient/Model/SWGReturn.m new file mode 100644 index 00000000000..90ad222590a --- /dev/null +++ b/samples/client/petstore-security-test/objc/SwaggerClient/Model/SWGReturn.m @@ -0,0 +1,34 @@ +#import "SWGReturn.h" + +@implementation SWGReturn + +- (instancetype)init { + self = [super init]; + if (self) { + // initialize property's default value, if any + + } + return self; +} + + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ ++ (JSONKeyMapper *)keyMapper { + return [[JSONKeyMapper alloc] initWithDictionary:@{ @"return": @"_return" }]; +} + +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ ++ (BOOL)propertyIsOptional:(NSString *)propertyName { + + NSArray *optionalProperties = @[@"_return"]; + return [optionalProperties containsObject:propertyName]; +} + +@end diff --git a/samples/client/petstore-security-test/objc/docs/SWGFakeApi.md b/samples/client/petstore-security-test/objc/docs/SWGFakeApi.md new file mode 100644 index 00000000000..76c62cd4fbf --- /dev/null +++ b/samples/client/petstore-security-test/objc/docs/SWGFakeApi.md @@ -0,0 +1,58 @@ +# SWGFakeApi + +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testCodeInjectEndRnNR**](SWGFakeApi.md#testcodeinjectendrnnr) | **PUT** /fake | To test code injection *_/ ' \" =end \\r\\n \\n \\r + + +# **testCodeInjectEndRnNR** +```objc +-(NSNumber*) testCodeInjectEndRnNRWithTestCodeInjectEndRnNR: (NSString*) testCodeInjectEndRnNR + completionHandler: (void (^)(NSError* error)) handler; +``` + +To test code injection *_/ ' \" =end \\r\\n \\n \\r + +### Example +```objc + +NSString* testCodeInjectEndRnNR = @"testCodeInjectEndRnNR_example"; // To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + +SWGFakeApi*apiInstance = [[SWGFakeApi alloc] init]; + +// To test code injection *_/ ' \" =end \\r\\n \\n \\r +[apiInstance testCodeInjectEndRnNRWithTestCodeInjectEndRnNR:testCodeInjectEndRnNR + completionHandler: ^(NSError* error) { + if (error) { + NSLog(@"Error calling SWGFakeApi->testCodeInjectEndRnNR: %@", error); + } + }]; +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **testCodeInjectEndRnNR** | **NSString***| To test code injection *_/ ' \" =end \\r\\n \\n \\r | [optional] + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json, */ ' =end + + + - **Accept**: application/json, */ ' =end + + + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore-security-test/objc/docs/SWGReturn.md b/samples/client/petstore-security-test/objc/docs/SWGReturn.md new file mode 100644 index 00000000000..fc4fc036c84 --- /dev/null +++ b/samples/client/petstore-security-test/objc/docs/SWGReturn.md @@ -0,0 +1,10 @@ +# SWGReturn + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **NSNumber*** | property description *_/ ' \" =end \\r\\n \\n \\r | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore-security-test/objc/git_push.sh b/samples/client/petstore-security-test/objc/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/objc/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md index 12d2d176c62..ea36f234aa7 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/README.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/README.md @@ -1,10 +1,10 @@ # SwaggerClient-php -This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end This PHP package is automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen) project: -- API version: 1.0.0 */ ' " =end -- Build date: 2016-07-06T12:09:22.895-07:00 +- API version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r +- Build date: 2016-07-12T18:29:31.200+08:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -58,12 +58,12 @@ Please follow the [installation procedure](#installation--usage) and then run th require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Swagger\Client\Api\FakeApi(); -$test_code_inject____end = "test_code_inject____end_example"; // string | To test code injection */ ' \" =end +$test_code_inject____end_rn_n_r = "test_code_inject____end_rn_n_r_example"; // string | To test code injection *_/ ' \" =end \\r\\n \\n \\r try { - $api_instance->testCodeInjectEnd($test_code_inject____end); + $api_instance->testCodeInjectEndRnNR($test_code_inject____end_rn_n_r); } catch (Exception $e) { - echo 'Exception when calling FakeApi->testCodeInjectEnd: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling FakeApi->testCodeInjectEndRnNR: ', $e->getMessage(), PHP_EOL; } ?> @@ -71,11 +71,11 @@ try { ## Documentation for API Endpoints -All URIs are relative to *https://petstore.swagger.io */ ' " =end/v2 */ ' " =end* +All URIs are relative to *https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*FakeApi* | [**testCodeInjectEnd**](docs/Api/FakeApi.md#testcodeinjectend) | **PUT** /fake | To test code injection */ ' \" =end +*FakeApi* | [**testCodeInjectEndRnNR**](docs/Api/FakeApi.md#testcodeinjectendrnnr) | **PUT** /fake | To test code injection *_/ ' \" =end \\r\\n \\n \\r ## Documentation For Models @@ -86,24 +86,24 @@ Class | Method | HTTP request | Description ## Documentation For Authorization +## api_key + +- **Type**: API key +- **API key parameter name**: api_key */ ' " =end \r\n \n \r +- **Location**: HTTP header + ## petstore_auth - **Type**: OAuth - **Flow**: implicit - **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog - **Scopes**: - - **write:pets**: modify pets in your account */ ' " =end - - **read:pets**: read your pets */ ' " =end - -## api_key - -- **Type**: API key -- **API key parameter name**: api_key */ ' " =end -- **Location**: HTTP header + - **write:pets**: modify pets in your account */ ' " =end \r\n \n \r + - **read:pets**: read your pets */ ' " =end \r\n \n \r ## Author -apiteam@swagger.io */ ' " =end +apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php b/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php index 2b57a0e3dae..5d845a7a2ad 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/autoload.php @@ -1,12 +1,12 @@ testCodeInjectEnd($test_code_inject____end) +# **testCodeInjectEndRnNR** +> testCodeInjectEndRnNR($test_code_inject____end_rn_n_r) -To test code injection */ ' \" =end +To test code injection *_/ ' \" =end \\r\\n \\n \\r ### Example ```php @@ -18,12 +18,12 @@ To test code injection */ ' \" =end require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Swagger\Client\Api\FakeApi(); -$test_code_inject____end = "test_code_inject____end_example"; // string | To test code injection */ ' \" =end +$test_code_inject____end_rn_n_r = "test_code_inject____end_rn_n_r_example"; // string | To test code injection *_/ ' \" =end \\r\\n \\n \\r try { - $api_instance->testCodeInjectEnd($test_code_inject____end); + $api_instance->testCodeInjectEndRnNR($test_code_inject____end_rn_n_r); } catch (Exception $e) { - echo 'Exception when calling FakeApi->testCodeInjectEnd: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling FakeApi->testCodeInjectEndRnNR: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -32,7 +32,7 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **test_code_inject____end** | **string**| To test code injection */ ' \" =end | [optional] + **test_code_inject____end_rn_n_r** | **string**| To test code injection *_/ ' \" =end \\r\\n \\n \\r | [optional] ### Return type @@ -44,8 +44,8 @@ No authorization required ### HTTP request headers - - **Content-Type**: application/json, */ ' " =end - - **Accept**: application/json, */ ' " =end + - **Content-Type**: application/json, *_/ \" =end + - **Accept**: application/json, *_/ \" =end [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Model/ModelReturn.md b/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Model/ModelReturn.md index ec3cb241037..0e3e582e4bf 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Model/ModelReturn.md +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/docs/Model/ModelReturn.md @@ -3,7 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**return** | **int** | property description */ ' \" =end | [optional] +**return** | **int** | property description *_/ ' \" =end \\r\\n \\n \\r | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php index fb8134bb8ef..33942e022ea 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -11,12 +11,12 @@ */ /** - * Swagger Petstore */ ' " =end + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end * - * OpenAPI spec version: 1.0.0 */ ' " =end - * Contact: apiteam@swagger.io */ ' " =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -73,7 +73,7 @@ class FakeApi { if ($apiClient == null) { $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('https://petstore.swagger.io */ ' " =end/v2 */ ' " =end'); + $apiClient->getConfig()->setHost('https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'); } $this->apiClient = $apiClient; @@ -103,30 +103,30 @@ class FakeApi } /** - * Operation testCodeInjectEnd + * Operation testCodeInjectEndRnNR * - * To test code injection */ ' \" =end + * To test code injection *_/ ' \" =end \\r\\n \\n \\r * - * @param string $test_code_inject____end To test code injection */ ' \" =end (optional) + * @param string $test_code_inject____end_rn_n_r To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function testCodeInjectEnd($test_code_inject____end = null) + public function testCodeInjectEndRnNR($test_code_inject____end_rn_n_r = null) { - list($response) = $this->testCodeInjectEndWithHttpInfo($test_code_inject____end); + list($response) = $this->testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end_rn_n_r); return $response; } /** - * Operation testCodeInjectEndWithHttpInfo + * Operation testCodeInjectEndRnNRWithHttpInfo * - * To test code injection */ ' \" =end + * To test code injection *_/ ' \" =end \\r\\n \\n \\r * - * @param string $test_code_inject____end To test code injection */ ' \" =end (optional) + * @param string $test_code_inject____end_rn_n_r To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) * @return Array of null, HTTP status code, HTTP response headers (array of strings) * @throws \Swagger\Client\ApiException on non-2xx response */ - public function testCodeInjectEndWithHttpInfo($test_code_inject____end = null) + public function testCodeInjectEndRnNRWithHttpInfo($test_code_inject____end_rn_n_r = null) { // parse inputs $resourcePath = "/fake"; @@ -134,18 +134,18 @@ class FakeApi $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', '*/ ' " =end')); + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', '*_/ \" =end')); if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','*/ ' " =end')); + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','*_/ \" =end')); // default format to json $resourcePath = str_replace("{format}", "json", $resourcePath); // form params - if ($test_code_inject____end !== null) { - $formParams['test code inject */ ' " =end'] = $this->apiClient->getSerializer()->toFormValue($test_code_inject____end); + if ($test_code_inject____end_rn_n_r !== null) { + $formParams['test code inject */ ' " =end \r\n \n \r'] = $this->apiClient->getSerializer()->toFormValue($test_code_inject____end_rn_n_r); } // for model (json/xml) diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php index eed39f53c7e..46654c2d6f1 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiClient.php @@ -12,12 +12,12 @@ */ /** - * Swagger Petstore */ ' " =end + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end * - * OpenAPI spec version: 1.0.0 */ ' " =end - * Contact: apiteam@swagger.io */ ' " =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php index 34492fb063d..c0647bf2d7b 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ApiException.php @@ -11,12 +11,12 @@ */ /** - * Swagger Petstore */ ' " =end + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end * - * OpenAPI spec version: 1.0.0 */ ' " =end - * Contact: apiteam@swagger.io */ ' " =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php index 3819200d19e..e50e5f6fc23 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Configuration.php @@ -11,12 +11,12 @@ */ /** - * Swagger Petstore */ ' " =end + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end * - * OpenAPI spec version: 1.0.0 */ ' " =end - * Contact: apiteam@swagger.io */ ' " =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -102,7 +102,7 @@ class Configuration * * @var string */ - protected $host = 'https://petstore.swagger.io */ ' " =end/v2 */ ' " =end'; + protected $host = 'https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'; /** * Timeout (second) of the HTTP request, by default set to 0, no timeout @@ -522,7 +522,7 @@ class Configuration $report = 'PHP SDK (Swagger\Client) Debug Report:' . PHP_EOL; $report .= ' OS: ' . php_uname() . PHP_EOL; $report .= ' PHP Version: ' . phpversion() . PHP_EOL; - $report .= ' OpenAPI Spec Version: 1.0.0 */ ' " =end' . PHP_EOL; + $report .= ' OpenAPI Spec Version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r' . PHP_EOL; $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; return $report; diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php index 8981f0dcd87..096464fdeba 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/Model/ModelReturn.php @@ -12,12 +12,12 @@ */ /** - * Swagger Petstore */ ' " =end + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end * - * OpenAPI spec version: 1.0.0 */ ' " =end - * Contact: apiteam@swagger.io */ ' " =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -47,7 +47,7 @@ use \ArrayAccess; * ModelReturn Class Doc Comment * * @category Class */ - // @description Model for testing reserved words */ ' \" =end + // @description Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen @@ -167,7 +167,7 @@ class ModelReturn implements ArrayAccess /** * Sets return - * @param int $return property description */ ' \" =end + * @param int $return property description *_/ ' \" =end \\r\\n \\n \\r * @return $this */ public function setReturn($return) diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php index 53663a58e38..da912830378 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -12,12 +12,12 @@ */ /** - * Swagger Petstore */ ' " =end + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ */ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end * - * OpenAPI spec version: 1.0.0 */ ' " =end - * Contact: apiteam@swagger.io */ ' " =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -264,7 +264,7 @@ class ObjectSerializer } else { return null; } - } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { + } elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) { settype($data, $class); return $data; } elseif ($class === '\SplFileObject') { diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/test/Api/FakeApiTest.php b/samples/client/petstore-security-test/php/SwaggerClient-php/test/Api/FakeApiTest.php index ccacf0be96b..6e96b079929 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/test/Api/FakeApiTest.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/test/Api/FakeApiTest.php @@ -11,12 +11,12 @@ */ /** - * Swagger Petstore ' \" =end + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -90,12 +90,12 @@ class FakeApiTest extends \PHPUnit_Framework_TestCase } /** - * Test case for testCodeInjectEnd + * Test case for testCodeInjectEndRnNR * - * To test code injection ' \" =end. + * To test code injection *_/ ' \" =end \\r\\n \\n \\r. * */ - public function testTestCodeInjectEnd() + public function testTestCodeInjectEndRnNR() { } diff --git a/samples/client/petstore-security-test/php/SwaggerClient-php/test/Model/ModelReturnTest.php b/samples/client/petstore-security-test/php/SwaggerClient-php/test/Model/ModelReturnTest.php index b662a59969f..a97d6a39873 100644 --- a/samples/client/petstore-security-test/php/SwaggerClient-php/test/Model/ModelReturnTest.php +++ b/samples/client/petstore-security-test/php/SwaggerClient-php/test/Model/ModelReturnTest.php @@ -12,12 +12,12 @@ */ /** - * Swagger Petstore ' \" =end + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r * - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ ' \" =end + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end * - * OpenAPI spec version: 1.0.0 ' \" =end - * Contact: apiteam@swagger.io ' \" =end + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); @@ -45,7 +45,7 @@ namespace Swagger\Client; * ModelReturnTest Class Doc Comment * * @category Class */ -// * @description Model for testing reserved words ' \" =end +// * @description Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r /** * @package Swagger\Client * @author http://github.com/swagger-api/swagger-codegen diff --git a/samples/client/petstore-security-test/qt5cpp/.swagger-codegen-ignore b/samples/client/petstore-security-test/qt5cpp/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/qt5cpp/LICENSE b/samples/client/petstore-security-test/qt5cpp/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/qt5cpp/client/SWGFakeApi.cpp b/samples/client/petstore-security-test/qt5cpp/client/SWGFakeApi.cpp new file mode 100644 index 00000000000..b7ade52546a --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/client/SWGFakeApi.cpp @@ -0,0 +1,84 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "SWGFakeApi.h" +#include "SWGHelpers.h" +#include "SWGModelFactory.h" + +#include +#include + +namespace Swagger { +SWGFakeApi::SWGFakeApi() {} + +SWGFakeApi::~SWGFakeApi() {} + +SWGFakeApi::SWGFakeApi(QString host, QString basePath) { + this->host = host; + this->basePath = basePath; +} + +void +SWGFakeApi::testCodeInject */ ' " =end \r\n \n \r(QString* test code inject */ ' " =end \r\n \n \r) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/fake"); + + + + HttpRequestWorker *worker = new HttpRequestWorker(); + HttpRequestInput input(fullPath, "PUT"); + + if (test code inject */ ' " =end \r\n \n \r != NULL) { + input.add_var("test code inject */ ' " =end \r\n \n \r", *test code inject */ ' " =end \r\n \n \r); + } + + + + + connect(worker, + &HttpRequestWorker::on_execution_finished, + this, + &SWGFakeApi::testCodeInject */ ' " =end \r\n \n \rCallback); + + worker->execute(&input); +} + +void +SWGFakeApi::testCodeInject */ ' " =end \r\n \n \rCallback(HttpRequestWorker * worker) { + QString msg; + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + + + + worker->deleteLater(); + + + emit testCodeInject */ ' " =end \r\n \n \rSignal(); +} +} /* namespace Swagger */ diff --git a/samples/client/petstore-security-test/qt5cpp/client/SWGFakeApi.h b/samples/client/petstore-security-test/qt5cpp/client/SWGFakeApi.h new file mode 100644 index 00000000000..4ffb6c79e18 --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/client/SWGFakeApi.h @@ -0,0 +1,57 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _SWG_SWGFakeApi_H_ +#define _SWG_SWGFakeApi_H_ + +#include "SWGHttpRequest.h" + +#include + +#include + +namespace Swagger { + +class SWGFakeApi: public QObject { + Q_OBJECT + +public: + SWGFakeApi(); + SWGFakeApi(QString host, QString basePath); + ~SWGFakeApi(); + + QString host; + QString basePath; + + void testCodeInject */ ' " =end \r\n \n \r(QString* test code inject */ ' " =end \r\n \n \r); + +private: + void testCodeInject */ ' " =end \r\n \n \rCallback (HttpRequestWorker * worker); + +signals: + void testCodeInject */ ' " =end \r\n \n \rSignal(); + +}; +} +#endif diff --git a/samples/client/petstore-security-test/qt5cpp/client/SWGHelpers.cpp b/samples/client/petstore-security-test/qt5cpp/client/SWGHelpers.cpp new file mode 100644 index 00000000000..09914f30647 --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/client/SWGHelpers.cpp @@ -0,0 +1,279 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "SWGHelpers.h" +#include "SWGModelFactory.h" +#include "SWGObject.h" +#include +#include +#include + +namespace Swagger { + +void +setValue(void* value, QJsonValue obj, QString type, QString complexType) { + if(value == NULL) { + // can't set value with a null pointer + return; + } + if(QStringLiteral("bool").compare(type) == 0) { + bool * val = static_cast(value); + *val = obj.toBool(); + } + else if(QStringLiteral("qint32").compare(type) == 0) { + qint32 *val = static_cast(value); + *val = obj.toInt(); + } + else if(QStringLiteral("qint64").compare(type) == 0) { + qint64 *val = static_cast(value); + *val = obj.toVariant().toLongLong(); + } + else if(QStringLiteral("float").compare(type) == 0) { + float *val = static_cast(value); + *val = obj.toDouble(); + } + else if(QStringLiteral("double").compare(type) == 0) { + double *val = static_cast(value); + *val = obj.toDouble(); + } + else if (QStringLiteral("QString").compare(type) == 0) { + QString **val = static_cast(value); + + if(val != NULL) { + if(!obj.isNull()) { + // create a new value and return + delete *val; + *val = new QString(obj.toString()); + return; + } + else { + // set target to NULL + delete *val; + *val = NULL; + } + } + else { + qDebug() << "Can't set value because the target pointer is NULL"; + } + } + else if (QStringLiteral("QDateTime").compare(type) == 0) { + QDateTime **val = static_cast(value); + + if(val != NULL) { + if(!obj.isNull()) { + // create a new value and return + delete *val; + *val = new QDateTime(QDateTime::fromString(obj.toString(), Qt::ISODate)); + return; + } + else { + // set target to NULL + delete *val; + *val = NULL; + } + } + else { + qDebug() << "Can't set value because the target pointer is NULL"; + } + } + else if (QStringLiteral("QDate").compare(type) == 0) { + QDate **val = static_cast(value); + + if(val != NULL) { + if(!obj.isNull()) { + // create a new value and return + delete *val; + *val = new QDate(QDate::fromString(obj.toString(), Qt::ISODate)); + return; + } + else { + // set target to NULL + delete *val; + *val = NULL; + } + } + else { + qDebug() << "Can't set value because the target pointer is NULL"; + } + } + else if(type.startsWith("SWG") && obj.isObject()) { + // complex type + QJsonObject jsonObj = obj.toObject(); + SWGObject * so = (SWGObject*)Swagger::create(type); + if(so != NULL) { + so->fromJsonObject(jsonObj); + SWGObject **val = static_cast(value); + delete *val; + *val = so; + } + } + else if(type.startsWith("QList") && QString("").compare(complexType) != 0 && obj.isArray()) { + // list of values + QList* output = new QList(); + QJsonArray arr = obj.toArray(); + foreach (const QJsonValue & jval, arr) { + if(complexType.startsWith("SWG")) { + // it's an object + SWGObject * val = (SWGObject*)create(complexType); + QJsonObject t = jval.toObject(); + + val->fromJsonObject(t); + output->append(val); + } + else { + // primitives + if(QStringLiteral("qint32").compare(complexType) == 0) { + qint32 val; + setValue(&val, jval, QStringLiteral("qint32"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("qint64").compare(complexType) == 0) { + qint64 val; + setValue(&val, jval, QStringLiteral("qint64"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("bool").compare(complexType) == 0) { + bool val; + setValue(&val, jval, QStringLiteral("bool"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("float").compare(complexType) == 0) { + float val; + setValue(&val, jval, QStringLiteral("float"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("double").compare(complexType) == 0) { + double val; + setValue(&val, jval, QStringLiteral("double"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("QString").compare(complexType) == 0) { + QString val; + setValue(&val, jval, QStringLiteral("QString"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("QDate").compare(complexType) == 0) { + QDate val; + setValue(&val, jval, QStringLiteral("QDate"), QStringLiteral("")); + output->append((void*)&val); + } + else if(QStringLiteral("QDateTime").compare(complexType) == 0) { + QDateTime val; + setValue(&val, jval, QStringLiteral("QDateTime"), QStringLiteral("")); + output->append((void*)&val); + } + } + } + QList **val = static_cast**>(value); + delete *val; + *val = output; + } +} + +void +toJsonValue(QString name, void* value, QJsonObject* output, QString type) { + if(value == NULL) { + return; + } + if(type.startsWith("SWG")) { + SWGObject *swgObject = reinterpret_cast(value); + if(swgObject != NULL) { + QJsonObject* o = (*swgObject).asJsonObject(); + if(name != NULL) { + output->insert(name, *o); + delete o; + } + else { + output->empty(); + foreach(QString key, o->keys()) { + output->insert(key, o->value(key)); + } + } + } + } + else if(QStringLiteral("QString").compare(type) == 0) { + QString* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("qint32").compare(type) == 0) { + qint32* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("qint64").compare(type) == 0) { + qint64* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("bool").compare(type) == 0) { + bool* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("float").compare(type) == 0) { + float* str = static_cast(value); + output->insert(name, QJsonValue((double)*str)); + } + else if(QStringLiteral("double").compare(type) == 0) { + double* str = static_cast(value); + output->insert(name, QJsonValue(*str)); + } + else if(QStringLiteral("QDate").compare(type) == 0) { + QDate* date = static_cast(value); + output->insert(name, QJsonValue(date->toString(Qt::ISODate))); + } + else if(QStringLiteral("QDateTime").compare(type) == 0) { + QDateTime* datetime = static_cast(value); + output->insert(name, QJsonValue(datetime->toString(Qt::ISODate))); + } +} + +void +toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType) { + foreach(void* obj, *value) { + QJsonObject element; + + toJsonValue(NULL, obj, &element, innerType); + output->append(element); + } +} + +QString +stringValue(QString* value) { + QString* str = static_cast(value); + return QString(*str); +} + +QString +stringValue(qint32 value) { + return QString::number(value); +} + +QString +stringValue(qint64 value) { + return QString::number(value); +} + +QString +stringValue(bool value) { + return QString(value ? "true" : "false"); +} +} /* namespace Swagger */ diff --git a/samples/client/petstore-security-test/qt5cpp/client/SWGHelpers.h b/samples/client/petstore-security-test/qt5cpp/client/SWGHelpers.h new file mode 100644 index 00000000000..7d9c16a23fc --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/client/SWGHelpers.h @@ -0,0 +1,41 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef SWGHELPERS_H +#define SWGHELPERS_H + +#include + +namespace Swagger { + void setValue(void* value, QJsonValue obj, QString type, QString complexType); + void toJsonArray(QList* value, QJsonArray* output, QString innerName, QString innerType); + void toJsonValue(QString name, void* value, QJsonObject* output, QString type); + bool isCompatibleJsonValue(QString type); + QString stringValue(QString* value); + QString stringValue(qint32 value); + QString stringValue(qint64 value); + QString stringValue(bool value); +} + +#endif // SWGHELPERS_H diff --git a/samples/client/petstore-security-test/qt5cpp/client/SWGHttpRequest.cpp b/samples/client/petstore-security-test/qt5cpp/client/SWGHttpRequest.cpp new file mode 100644 index 00000000000..f58635446d4 --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/client/SWGHttpRequest.cpp @@ -0,0 +1,323 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "SWGHttpRequest.h" +#include +#include +#include +#include + + +HttpRequestInput::HttpRequestInput() { + initialize(); +} + +HttpRequestInput::HttpRequestInput(QString v_url_str, QString v_http_method) { + initialize(); + url_str = v_url_str; + http_method = v_http_method; +} + +void HttpRequestInput::initialize() { + var_layout = NOT_SET; + url_str = ""; + http_method = "GET"; +} + +void HttpRequestInput::add_var(QString key, QString value) { + vars[key] = value; +} + +void HttpRequestInput::add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type) { + SWGHttpRequestInputFileElement file; + file.variable_name = variable_name; + file.local_filename = local_filename; + file.request_filename = request_filename; + file.mime_type = mime_type; + files.append(file); +} + + +HttpRequestWorker::HttpRequestWorker(QObject *parent) + : QObject(parent), manager(NULL) +{ + qsrand(QDateTime::currentDateTime().toTime_t()); + + manager = new QNetworkAccessManager(this); + connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(on_manager_finished(QNetworkReply*))); +} + +HttpRequestWorker::~HttpRequestWorker() { +} + +QString HttpRequestWorker::http_attribute_encode(QString attribute_name, QString input) { + // result structure follows RFC 5987 + bool need_utf_encoding = false; + QString result = ""; + QByteArray input_c = input.toLocal8Bit(); + char c; + for (int i = 0; i < input_c.length(); i++) { + c = input_c.at(i); + if (c == '\\' || c == '/' || c == '\0' || c < ' ' || c > '~') { + // ignore and request utf-8 version + need_utf_encoding = true; + } + else if (c == '"') { + result += "\\\""; + } + else { + result += c; + } + } + + if (result.length() == 0) { + need_utf_encoding = true; + } + + if (!need_utf_encoding) { + // return simple version + return QString("%1=\"%2\"").arg(attribute_name, result); + } + + QString result_utf8 = ""; + for (int i = 0; i < input_c.length(); i++) { + c = input_c.at(i); + if ( + (c >= '0' && c <= '9') + || (c >= 'A' && c <= 'Z') + || (c >= 'a' && c <= 'z') + ) { + result_utf8 += c; + } + else { + result_utf8 += "%" + QString::number(static_cast(input_c.at(i)), 16).toUpper(); + } + } + + // return enhanced version with UTF-8 support + return QString("%1=\"%2\"; %1*=utf-8''%3").arg(attribute_name, result, result_utf8); +} + +void HttpRequestWorker::execute(HttpRequestInput *input) { + + // reset variables + + QByteArray request_content = ""; + response = ""; + error_type = QNetworkReply::NoError; + error_str = ""; + bool isFormData = false; + + + // decide on the variable layout + + if (input->files.length() > 0) { + input->var_layout = MULTIPART; + } + if (input->var_layout == NOT_SET) { + input->var_layout = input->http_method == "GET" || input->http_method == "HEAD" ? ADDRESS : URL_ENCODED; + } + + + // prepare request content + + QString boundary = ""; + + if (input->var_layout == ADDRESS || input->var_layout == URL_ENCODED) { + // variable layout is ADDRESS or URL_ENCODED + + if (input->vars.count() > 0) { + bool first = true; + isFormData = true; + foreach (QString key, input->vars.keys()) { + if (!first) { + request_content.append("&"); + } + first = false; + + request_content.append(QUrl::toPercentEncoding(key)); + request_content.append("="); + request_content.append(QUrl::toPercentEncoding(input->vars.value(key))); + } + + if (input->var_layout == ADDRESS) { + input->url_str += "?" + request_content; + request_content = ""; + } + } + } + else { + // variable layout is MULTIPART + + boundary = "__-----------------------" + + QString::number(QDateTime::currentDateTime().toTime_t()) + + QString::number(qrand()); + QString boundary_delimiter = "--"; + QString new_line = "\r\n"; + + // add variables + foreach (QString key, input->vars.keys()) { + // add boundary + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(new_line); + + // add header + request_content.append("Content-Disposition: form-data; "); + request_content.append(http_attribute_encode("name", key)); + request_content.append(new_line); + request_content.append("Content-Type: text/plain"); + request_content.append(new_line); + + // add header to body splitter + request_content.append(new_line); + + // add variable content + request_content.append(input->vars.value(key)); + request_content.append(new_line); + } + + // add files + for (QList::iterator file_info = input->files.begin(); file_info != input->files.end(); file_info++) { + QFileInfo fi(file_info->local_filename); + + // ensure necessary variables are available + if ( + file_info->local_filename == NULL || file_info->local_filename.isEmpty() + || file_info->variable_name == NULL || file_info->variable_name.isEmpty() + || !fi.exists() || !fi.isFile() || !fi.isReadable() + ) { + // silent abort for the current file + continue; + } + + QFile file(file_info->local_filename); + if (!file.open(QIODevice::ReadOnly)) { + // silent abort for the current file + continue; + } + + // ensure filename for the request + if (file_info->request_filename == NULL || file_info->request_filename.isEmpty()) { + file_info->request_filename = fi.fileName(); + if (file_info->request_filename.isEmpty()) { + file_info->request_filename = "file"; + } + } + + // add boundary + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(new_line); + + // add header + request_content.append(QString("Content-Disposition: form-data; %1; %2").arg( + http_attribute_encode("name", file_info->variable_name), + http_attribute_encode("filename", file_info->request_filename) + )); + request_content.append(new_line); + + if (file_info->mime_type != NULL && !file_info->mime_type.isEmpty()) { + request_content.append("Content-Type: "); + request_content.append(file_info->mime_type); + request_content.append(new_line); + } + + request_content.append("Content-Transfer-Encoding: binary"); + request_content.append(new_line); + + // add header to body splitter + request_content.append(new_line); + + // add file content + request_content.append(file.readAll()); + request_content.append(new_line); + + file.close(); + } + + // add end of body + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(boundary_delimiter); + } + + if(input->request_body.size() > 0) { + qDebug() << "got a request body"; + request_content.clear(); + request_content.append(input->request_body); + } + // prepare connection + + QNetworkRequest request = QNetworkRequest(QUrl(input->url_str)); + request.setRawHeader("User-Agent", "Swagger-Client"); + foreach(QString key, input->headers.keys()) { + request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); + } + + if (request_content.size() > 0 && !isFormData) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); + } + else if (input->var_layout == URL_ENCODED) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + } + else if (input->var_layout == MULTIPART) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + boundary); + } + + if (input->http_method == "GET") { + manager->get(request); + } + else if (input->http_method == "POST") { + manager->post(request, request_content); + } + else if (input->http_method == "PUT") { + manager->put(request, request_content); + } + else if (input->http_method == "HEAD") { + manager->head(request); + } + else if (input->http_method == "DELETE") { + manager->deleteResource(request); + } + else { + QBuffer buff(&request_content); + manager->sendCustomRequest(request, input->http_method.toLatin1(), &buff); + } + +} + +void HttpRequestWorker::on_manager_finished(QNetworkReply *reply) { + error_type = reply->error(); + if (error_type == QNetworkReply::NoError) { + response = reply->readAll(); + } + else { + error_str = reply->errorString(); + } + + reply->deleteLater(); + + emit on_execution_finished(this); +} diff --git a/samples/client/petstore-security-test/qt5cpp/client/SWGHttpRequest.h b/samples/client/petstore-security-test/qt5cpp/client/SWGHttpRequest.h new file mode 100644 index 00000000000..bc694750a3b --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/client/SWGHttpRequest.h @@ -0,0 +1,99 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Based on http://www.creativepulse.gr/en/blog/2014/restful-api-requests-using-qt-cpp-for-linux-mac-osx-ms-windows + * By Alex Stylianos + * + **/ + +#ifndef HTTPREQUESTWORKER_H +#define HTTPREQUESTWORKER_H + +#include +#include +#include +#include +#include + +enum HttpRequestVarLayout {NOT_SET, ADDRESS, URL_ENCODED, MULTIPART}; + + +class SWGHttpRequestInputFileElement { + +public: + QString variable_name; + QString local_filename; + QString request_filename; + QString mime_type; + +}; + + +class HttpRequestInput { + +public: + QString url_str; + QString http_method; + HttpRequestVarLayout var_layout; + QMap vars; + QMap headers; + QList files; + QByteArray request_body; + + HttpRequestInput(); + HttpRequestInput(QString v_url_str, QString v_http_method); + void initialize(); + void add_var(QString key, QString value); + void add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type); + +}; + + +class HttpRequestWorker : public QObject { + Q_OBJECT + +public: + QByteArray response; + QNetworkReply::NetworkError error_type; + QString error_str; + + explicit HttpRequestWorker(QObject *parent = 0); + virtual ~HttpRequestWorker(); + + QString http_attribute_encode(QString attribute_name, QString input); + void execute(HttpRequestInput *input); + +signals: + void on_execution_finished(HttpRequestWorker *worker); + +private: + QNetworkAccessManager *manager; + +private slots: + void on_manager_finished(QNetworkReply *reply); + +}; + +#endif // HTTPREQUESTWORKER_H diff --git a/samples/client/petstore-security-test/qt5cpp/client/SWGModelFactory.h b/samples/client/petstore-security-test/qt5cpp/client/SWGModelFactory.h new file mode 100644 index 00000000000..85e774057b5 --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/client/SWGModelFactory.h @@ -0,0 +1,53 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ModelFactory_H_ +#define ModelFactory_H_ + + +#include "SWGReturn.h" + +namespace Swagger { + inline void* create(QString type) { + if(QString("SWGReturn").compare(type) == 0) { + return new SWGReturn(); + } + + return NULL; + } + + inline void* create(QString json, QString type) { + void* val = create(type); + if(val != NULL) { + SWGObject* obj = static_cast(val); + return obj->fromJson(json); + } + if(type.startsWith("QString")) { + return new QString(); + } + return NULL; + } +} /* namespace Swagger */ + +#endif /* ModelFactory_H_ */ diff --git a/samples/client/petstore-security-test/qt5cpp/client/SWGObject.h b/samples/client/petstore-security-test/qt5cpp/client/SWGObject.h new file mode 100644 index 00000000000..c6b545ad96a --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/client/SWGObject.h @@ -0,0 +1,48 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _SWG_OBJECT_H_ +#define _SWG_OBJECT_H_ + +#include + +class SWGObject { + public: + virtual QJsonObject* asJsonObject() { + return NULL; + } + virtual ~SWGObject() {} + virtual SWGObject* fromJson(QString &jsonString) { + Q_UNUSED(jsonString); + return NULL; + } + virtual void fromJsonObject(QJsonObject &json) { + Q_UNUSED(json); + } + virtual QString asJson() { + return QString(""); + } +}; + +#endif /* _SWG_OBJECT_H_ */ diff --git a/samples/client/petstore-security-test/qt5cpp/client/SWGReturn.cpp b/samples/client/petstore-security-test/qt5cpp/client/SWGReturn.cpp new file mode 100644 index 00000000000..af690499b9b --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/client/SWGReturn.cpp @@ -0,0 +1,105 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include "SWGReturn.h" + +#include "SWGHelpers.h" + +#include +#include +#include +#include + +namespace Swagger { + + +SWGReturn::SWGReturn(QString* json) { + init(); + this->fromJson(*json); +} + +SWGReturn::SWGReturn() { + init(); +} + +SWGReturn::~SWGReturn() { + this->cleanup(); +} + +void +SWGReturn::init() { + return = 0; +} + +void +SWGReturn::cleanup() { + +} + +SWGReturn* +SWGReturn::fromJson(QString &json) { + QByteArray array (json.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); + return this; +} + +void +SWGReturn::fromJsonObject(QJsonObject &pJson) { + setValue(&return, pJson["return"], "qint32", ""); +} + +QString +SWGReturn::asJson () +{ + QJsonObject* obj = this->asJsonObject(); + + QJsonDocument doc(*obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject* +SWGReturn::asJsonObject() { + QJsonObject* obj = new QJsonObject(); + obj->insert("return", QJsonValue(return)); + + return obj; +} + +qint32 +SWGReturn::getReturn() { + return return; +} +void +SWGReturn::setReturn(qint32 return) { + this->return = return; +} + + + +} /* namespace Swagger */ + diff --git a/samples/client/petstore-security-test/qt5cpp/client/SWGReturn.h b/samples/client/petstore-security-test/qt5cpp/client/SWGReturn.h new file mode 100644 index 00000000000..8d9f4f66b05 --- /dev/null +++ b/samples/client/petstore-security-test/qt5cpp/client/SWGReturn.h @@ -0,0 +1,65 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * SWGReturn.h + * + * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + */ + +#ifndef SWGReturn_H_ +#define SWGReturn_H_ + +#include + + + +#include "SWGObject.h" + + +namespace Swagger { + +class SWGReturn: public SWGObject { +public: + SWGReturn(); + SWGReturn(QString* json); + virtual ~SWGReturn(); + void init(); + void cleanup(); + + QString asJson (); + QJsonObject* asJsonObject(); + void fromJsonObject(QJsonObject &json); + SWGReturn* fromJson(QString &jsonString); + + qint32 getReturn(); + void setReturn(qint32 return); + +private: + qint32 return; +}; + +} /* namespace Swagger */ + +#endif /* SWGReturn_H_ */ diff --git a/samples/client/petstore-security-test/scala/.gitignore b/samples/client/petstore-security-test/scala/.gitignore new file mode 100644 index 00000000000..c58d83b3189 --- /dev/null +++ b/samples/client/petstore-security-test/scala/.gitignore @@ -0,0 +1,17 @@ +*.class +*.log + +# sbt specific +.cache +.history +.lib/ +dist/* +target/ +lib_managed/ +src_managed/ +project/boot/ +project/plugins/project/ + +# Scala-IDE specific +.scala_dependencies +.worksheet diff --git a/samples/client/petstore-security-test/scala/.swagger-codegen-ignore b/samples/client/petstore-security-test/scala/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/scala/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/scala/LICENSE b/samples/client/petstore-security-test/scala/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/scala/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/scala/build.gradle b/samples/client/petstore-security-test/scala/build.gradle new file mode 100644 index 00000000000..979db7783c4 --- /dev/null +++ b/samples/client/petstore-security-test/scala/build.gradle @@ -0,0 +1,120 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'scala' + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-scala-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + scala_version = "2.10.4" + joda_version = "1.2" + jodatime_version = "2.2" + jersey_version = "1.19" + swagger_core_version = "1.5.8" + jersey_async_version = "1.0.5" + jackson_version = "2.4.2" + junit_version = "4.8.1" + scala_test_version = "2.2.4" +} + +dependencies { + compile "com.fasterxml.jackson.module:jackson-module-scala_2.10:$jackson_version" + compile "com.sun.jersey:jersey-client:$jersey_version" + compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" + compile "org.jfarcand:jersey-ahc-client:$jersey_async_version" + compile "org.scala-lang:scala-library:$scala_version" + compile "io.swagger:swagger-core:$swagger_core_version" + testCompile "org.scalatest:scalatest_2.10:$scala_test_version" + testCompile "junit:junit:$junit_version" + compile "joda-time:joda-time:$jodatime_version" + compile "org.joda:joda-convert:$joda_version" +} diff --git a/samples/client/petstore-security-test/scala/build.sbt b/samples/client/petstore-security-test/scala/build.sbt new file mode 100644 index 00000000000..063b2b0d490 --- /dev/null +++ b/samples/client/petstore-security-test/scala/build.sbt @@ -0,0 +1,33 @@ +lazy val root = (project in file(".")). + settings( + version := "1.0.0", + name := "swagger-scala-client", + organization := "io.swagger", + scalaVersion := "2.11.8", + + libraryDependencies ++= Seq( + "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.4.2", + "com.sun.jersey" % "jersey-core" % "1.19", + "com.sun.jersey" % "jersey-client" % "1.19", + "com.sun.jersey.contribs" % "jersey-multipart" % "1.19", + "org.jfarcand" % "jersey-ahc-client" % "1.0.5", + "io.swagger" % "swagger-core" % "1.5.8", + "joda-time" % "joda-time" % "2.2", + "org.joda" % "joda-convert" % "1.2", + "org.scalatest" %% "scalatest" % "2.2.4" % "test", + "junit" % "junit" % "4.8.1" % "test" + ), + + resolvers ++= Seq( + Resolver.jcenterRepo, + Resolver.mavenLocal + ), + + scalacOptions := Seq( + "-unchecked", + "-deprecation", + "-feature" + ), + + publishArtifact in (Compile, packageDoc) := false + ) \ No newline at end of file diff --git a/samples/client/petstore-security-test/scala/git_push.sh b/samples/client/petstore-security-test/scala/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/scala/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore-security-test/scala/gradle.properties b/samples/client/petstore-security-test/scala/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore-security-test/scala/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore-security-test/scala/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore-security-test/scala/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..2c6137b8789 Binary files /dev/null and b/samples/client/petstore-security-test/scala/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore-security-test/scala/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore-security-test/scala/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..b7a36473955 --- /dev/null +++ b/samples/client/petstore-security-test/scala/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Tue May 17 23:08:05 CST 2016 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-2.6-bin.zip diff --git a/samples/client/petstore-security-test/scala/gradlew b/samples/client/petstore-security-test/scala/gradlew new file mode 100644 index 00000000000..9d82f789151 --- /dev/null +++ b/samples/client/petstore-security-test/scala/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/samples/client/petstore-security-test/scala/gradlew.bat b/samples/client/petstore-security-test/scala/gradlew.bat new file mode 100644 index 00000000000..72d362dafd8 --- /dev/null +++ b/samples/client/petstore-security-test/scala/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore-security-test/scala/pom.xml b/samples/client/petstore-security-test/scala/pom.xml new file mode 100644 index 00000000000..5b036cd8fc1 --- /dev/null +++ b/samples/client/petstore-security-test/scala/pom.xml @@ -0,0 +1,224 @@ + + 4.0.0 + io.swagger + swagger-scala-client + jar + swagger-scala-client + 1.0.0 + + 2.2.0 + + + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + http://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + com.fasterxml.jackson.module + jackson-module-scala_2.10 + ${jackson-version} + + + com.sun.jersey + jersey-client + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + org.jfarcand + jersey-ahc-client + ${jersey-async-version} + compile + + + org.scala-lang + scala-library + ${scala-version} + + + io.swagger + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + + 2.10.4 + 1.2 + 2.2 + 1.19 + 1.5.8 + 1.0.5 + 1.0.0 + 2.4.2 + + 4.8.1 + 3.1.5 + 2.2.4 + + UTF-8 + + diff --git a/samples/client/petstore-security-test/scala/settings.gradle b/samples/client/petstore-security-test/scala/settings.gradle new file mode 100644 index 00000000000..5452c701c0e --- /dev/null +++ b/samples/client/petstore-security-test/scala/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-scala-client" \ No newline at end of file diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala new file mode 100644 index 00000000000..22f3dac7cf8 --- /dev/null +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/ApiInvoker.scala @@ -0,0 +1,226 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client + +import com.sun.jersey.api.client.Client +import com.sun.jersey.api.client.ClientResponse +import com.sun.jersey.api.client.config.ClientConfig +import com.sun.jersey.api.client.config.DefaultClientConfig +import com.sun.jersey.api.client.filter.LoggingFilter + +import com.sun.jersey.core.util.MultivaluedMapImpl +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import java.io.File +import java.net.URLEncoder +import javax.ws.rs.core.MediaType + +import scala.collection.JavaConverters._ +import scala.collection.mutable.HashMap + +import com.fasterxml.jackson.module.scala.DefaultScalaModule +import com.fasterxml.jackson.datatype.joda.JodaModule +import com.fasterxml.jackson.core.JsonGenerator.Feature +import com.fasterxml.jackson.databind._ +import com.fasterxml.jackson.annotation._ +import com.fasterxml.jackson.databind.annotation.JsonSerialize + +object ScalaJsonUtil { + def getJsonMapper = { + val mapper = new ObjectMapper() + mapper.registerModule(new DefaultScalaModule()) + mapper.registerModule(new JodaModule()); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT) + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY) + mapper + } +} + +class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, + httpHeaders: HashMap[String, String] = HashMap(), + hostMap: HashMap[String, Client] = HashMap(), + asyncHttpClient: Boolean = false, + authScheme: String = "", + authPreemptive: Boolean = false) { + + var defaultHeaders: HashMap[String, String] = httpHeaders + + def escape(value: String): String = { + URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") + } + + def escape(value: Long): String = value.toString + def escape(value: Double): String = value.toString + def escape(value: Float): String = value.toString + + def deserialize(json: String, containerType: String, cls: Class[_]) = { + if (cls == classOf[String]) { + json match { + case s: String => { + if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 1) + else s + } + case _ => null + } + } else { + containerType.toLowerCase match { + case "array" => { + val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + } + case "list" => { + val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + } + case _ => { + json match { + case e: String if ("\"\"" == e) => null + case _ => mapper.readValue(json, cls) + } + } + } + } + } + + def serialize(obj: AnyRef): String = { + if (obj != null) { + obj match { + case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava) + case _ => mapper.writeValueAsString(obj) + } + } else null + } + + def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], formParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { + val client = getClient(host) + + val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "") + val builder = client.resource(host + path + querystring).accept(contentType) + headerParams.map(p => builder.header(p._1, p._2)) + defaultHeaders.map(p => { + headerParams.contains(p._1) match { + case true => // override default with supplied header + case false => if (p._2 != null) builder.header(p._1, p._2) + } + }) + var formData: MultivaluedMapImpl = null + if(contentType == "application/x-www-form-urlencoded") { + formData = new MultivaluedMapImpl() + formParams.map(p => formData.add(p._1, p._2)) + } + + val response: ClientResponse = method match { + case "GET" => { + builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] + } + case "POST" => { + if(formData != null) builder.post(classOf[ClientResponse], formData) + else if(body != null && body.isInstanceOf[File]) { + val file = body.asInstanceOf[File] + val form = new FormDataMultiPart() + form.field("filename", file.getName()) + form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) + builder.post(classOf[ClientResponse], form) + } + else { + if(body == null) builder.post(classOf[ClientResponse], serialize(body)) + else builder.`type`(contentType).post(classOf[ClientResponse], serialize(body)) + } + } + case "PUT" => { + if(formData != null) builder.post(classOf[ClientResponse], formData) + else if(body == null) builder.put(classOf[ClientResponse], null) + else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) + } + case "DELETE" => { + builder.delete(classOf[ClientResponse]) + } + case _ => null + } + response.getStatusInfo().getStatusCode() match { + case 204 => "" + case code: Int if (Range(200, 299).contains(code)) => { + response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "" + } + } + case _ => { + val entity = response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "no data" + } + throw new ApiException( + response.getStatusInfo().getStatusCode(), + entity) + } + } + } + + def getClient(host: String): Client = { + hostMap.contains(host) match { + case true => hostMap(host) + case false => { + val client = newClient(host) + // client.addFilter(new LoggingFilter()) + hostMap += host -> client + client + } + } + } + + def newClient(host: String): Client = asyncHttpClient match { + case true => { + import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig + import org.sonatype.spice.jersey.client.ahc.AhcHttpClient + import com.ning.http.client.Realm + + val config: DefaultAhcConfig = new DefaultAhcConfig() + if (!authScheme.isEmpty) { + val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) + config.getAsyncHttpClientConfigBuilder + .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) + .setUsePreemptiveAuth(authPreemptive).build) + } + AhcHttpClient.create(config) + } + case _ => Client.create() + } +} + +object ApiInvoker extends ApiInvoker(mapper = ScalaJsonUtil.getJsonMapper, + httpHeaders = HashMap(), + hostMap = HashMap(), + asyncHttpClient = false, + authScheme = "", + authPreemptive = false) + +class ApiException(val code: Int, msg: String) extends RuntimeException(msg) diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala new file mode 100644 index 00000000000..ce6f4eee77f --- /dev/null +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/api/FakeApi.scala @@ -0,0 +1,92 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client.api + +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import javax.ws.rs.core.MediaType + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class FakeApi(val defBasePath: String = "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param testCodeInjectEndRnNR To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + * @return void + */ + def testCodeInject * ' " =end rn n r (testCodeInjectEndRnNR: String) = { + // create path and map variables + val path = "/fake".replaceAll("\\{format\\}","json") + val contentTypes = List("application/json", "*/ ' =end + + ", "application/json") + val contentType = contentTypes(0) + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + val formParams = new HashMap[String, String] + + + + var postBody: AnyRef = null + + if(contentType.startsWith("multipart/form-data")) { + val mp = new FormDataMultiPart() + + mp.field("test code inject */ ' " =end \r\n \n \r", testCodeInjectEndRnNR.toString(), MediaType.MULTIPART_FORM_DATA_TYPE) + + postBody = mp + } + else { + formParams += "test code inject */ ' " =end \r\n \n \r" -> testCodeInjectEndRnNR.toString() + } + + try { + apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, formParams.toMap, postBody, headerParams.toMap, contentType) match { + case s: String => + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala new file mode 100644 index 00000000000..08aaff0573a --- /dev/null +++ b/samples/client/petstore-security-test/scala/src/main/scala/io/swagger/client/model/ModelReturn.scala @@ -0,0 +1,32 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.client.model + + + + +case class ModelReturn ( + /* property description *_/ ' \" =end \\r\\n \\n \\r */ + _return: Integer) diff --git a/samples/client/petstore-security-test/swift/.gitignore b/samples/client/petstore-security-test/swift/.gitignore new file mode 100644 index 00000000000..5e5d5cebcf4 --- /dev/null +++ b/samples/client/petstore-security-test/swift/.gitignore @@ -0,0 +1,63 @@ +# 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 +*.xccheckout +*.moved-aside +*.xcuserstate +*.xcscmblueprint + +## Obj-C/Swift specific +*.hmap +*.ipa + +## 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/ +.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://github.com/fastlane/fastlane/blob/master/docs/Gitignore.md + +fastlane/report.xml +fastlane/screenshots diff --git a/samples/client/petstore-security-test/swift/.swagger-codegen-ignore b/samples/client/petstore-security-test/swift/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/swift/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/swift/Cartfile b/samples/client/petstore-security-test/swift/Cartfile new file mode 100644 index 00000000000..3d90db16891 --- /dev/null +++ b/samples/client/petstore-security-test/swift/Cartfile @@ -0,0 +1 @@ +github "Alamofire/Alamofire" >= 3.1.0 diff --git a/samples/client/petstore-security-test/swift/LICENSE b/samples/client/petstore-security-test/swift/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/swift/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/swift/SwaggerClient.podspec b/samples/client/petstore-security-test/swift/SwaggerClient.podspec new file mode 100644 index 00000000000..4786bf4084e --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient.podspec @@ -0,0 +1,10 @@ +Pod::Spec.new do |s| + s.name = 'SwaggerClient' + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.license = 'Apache License, Version 2.0' + s.source_files = 'SwaggerClient/Classes/Swaggers/**/*.swift' + s.dependency 'Alamofire', '~> 3.1.5' +end diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 00000000000..23e727b6b54 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,40 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +class APIHelper { + static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? { + var destination = [String:AnyObject]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + static func convertBoolToString(source: [String: AnyObject]?) -> [String:AnyObject]? { + guard let source = source else { + return nil + } + var destination = [String:AnyObject]() + let theTrue = NSNumber(bool: true) + let theFalse = NSNumber(bool: false) + for (key, value) in source { + switch value { + case let x where x === theTrue || x === theFalse: + destination[key] = "\(value as! Bool)" + default: + destination[key] = value + } + } + return destination + } + +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs.swift new file mode 100644 index 00000000000..afc7afbc094 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs.swift @@ -0,0 +1,73 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +public class SwaggerClientAPI { + public static var basePath = "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r" + public static var credential: NSURLCredential? + public static var customHeaders: [String:String] = [:] + static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +public class APIBase { + func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? { + let encoded: AnyObject? = encodable?.encodeToJSON() + + if encoded! is [AnyObject] { + var dictionary = [String:AnyObject]() + for (index, item) in (encoded as! [AnyObject]).enumerate() { + dictionary["\(index)"] = item + } + return dictionary + } else { + return encoded as? [String:AnyObject] + } + } +} + +public class RequestBuilder { + var credential: NSURLCredential? + var headers: [String:String] = [:] + let parameters: [String:AnyObject]? + let isBody: Bool + let method: String + let URLString: String + + required public init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + + addHeaders(SwaggerClientAPI.customHeaders) + } + + public func addHeaders(aHeaders:[String:String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + public func execute(completion: (response: Response?, error: ErrorType?) -> Void) { } + + public func addHeader(name name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + public func addCredential() -> Self { + self.credential = SwaggerClientAPI.credential + return self + } +} + +protocol RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type +} + diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs/FakeAPI.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs/FakeAPI.swift new file mode 100644 index 00000000000..0d35a764773 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/APIs/FakeAPI.swift @@ -0,0 +1,51 @@ +// +// FakeAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + + + +public class FakeAPI: APIBase { + /** + To test code injection *_/ ' \" =end \\r\\n \\n \\r + + - parameter testCodeInjectEndRnNR: (form) To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + - parameter completion: completion handler to receive the data and the error objects + */ + public class func testCodeInjectEndRnNR(testCodeInjectEndRnNR testCodeInjectEndRnNR: String? = nil, completion: ((error: ErrorType?) -> Void)) { + testCodeInjectEndRnNRWithRequestBuilder(testCodeInjectEndRnNR: testCodeInjectEndRnNR).execute { (response, error) -> Void in + completion(error: error); + } + } + + + /** + To test code injection *_/ ' \" =end \\r\\n \\n \\r + - PUT /fake + + - parameter testCodeInjectEndRnNR: (form) To test code injection *_/ ' \" =end \\r\\n \\n \\r (optional) + + - returns: RequestBuilder + */ + public class func testCodeInjectEndRnNRWithRequestBuilder(testCodeInjectEndRnNR testCodeInjectEndRnNR: String? = nil) -> RequestBuilder { + let path = "/fake" + let URLString = SwaggerClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "test code inject */ ' " =end \r\n \n \r": testCodeInjectEndRnNR + ] + + let parameters = APIHelper.rejectNil(nillableParameters) + + let convertedParameters = APIHelper.convertBoolToString(parameters) + + let requestBuilder: RequestBuilder.Type = SwaggerClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder.init(method: "PUT", URLString: URLString, parameters: convertedParameters, isBody: false) + } + +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/AlamofireImplementations.swift new file mode 100644 index 00000000000..2faa0a6f24d --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/AlamofireImplementations.swift @@ -0,0 +1,112 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore: [String: Alamofire.Manager] = [:] + +class AlamofireRequestBuilder: RequestBuilder { + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + } + + override func execute(completion: (response: Response?, error: ErrorType?) -> Void) { + let managerId = NSUUID().UUIDString + // Create a new manager for each request to customize its request header + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = buildHeaders() + let manager = Alamofire.Manager(configuration: configuration) + managerStore[managerId] = manager + + let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL + let xMethod = Alamofire.Method(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + self.processRequest(upload, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, error: encodingError) + } + } + ) + } else { + processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, error: ErrorType?) -> Void) { + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + request.validate().responseJSON(options: .AllowFragments) { response in + managerStore.removeValueForKey(managerId) + + if response.result.isFailure { + completion(response: nil, error: response.result.error) + return + } + + if () is T { + completion(response: Response(response: response.response!, body: () as! T), error: nil) + return + } + if let json: AnyObject = response.result.value { + let body = Decoders.decode(clazz: T.self, source: json) + completion(response: Response(response: response.response!, body: body), error: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + completion(response: Response(response: response.response!, body: "" as! T), error: nil) + return + } + + completion(response: nil, error: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + } + } + + private func buildHeaders() -> [String: AnyObject] { + var httpHeaders = Manager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Extensions.swift new file mode 100644 index 00000000000..fed87969388 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Extensions.swift @@ -0,0 +1,74 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire + +extension Bool: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int32: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(int: self) } +} + +extension Int64: JSONEncodable { + func encodeToJSON() -> AnyObject { return NSNumber(longLong: self) } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension String: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +private func encodeIfPossible(object: T) -> AnyObject { + if object is JSONEncodable { + return (object as! JSONEncodable).encodeToJSON() + } else { + return object as! AnyObject + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> AnyObject { + var dictionary = [NSObject:AnyObject]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary + } +} + + +private let dateFormatter: NSDateFormatter = { + let dateFormatter = NSDateFormatter() + dateFormatter.dateFormat = "yyyy-MM-dd" + return dateFormatter +}() + +extension NSDate: JSONEncodable { + func encodeToJSON() -> AnyObject { + return dateFormatter.stringFromDate(self) + } +} + + diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models.swift new file mode 100644 index 00000000000..3f70e2a1c5e --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models.swift @@ -0,0 +1,147 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> AnyObject +} + +public class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T + + public init(statusCode: Int, header: [String: String], body: T) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + public convenience init(response: NSHTTPURLResponse, body: T) { + let rawHeader = response.allHeaderFields + var header = [String:String]() + for (key, value) in rawHeader { + header[key as! String] = value as? String + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} + +private var once = dispatch_once_t() +class Decoders { + static private var decoders = Dictionary AnyObject)>() + + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { + let key = "\(T.self)" + decoders[key] = { decoder($0) as! AnyObject } + } + + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { + let array = source as! [AnyObject] + return array.map { Decoders.decode(clazz: T.self, source: $0) } + } + + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { + let sourceDictionary = source as! [Key: AnyObject] + var dictionary = [Key:T]() + for (key, value) in sourceDictionary { + dictionary[key] = Decoders.decode(clazz: T.self, source: value) + } + return dictionary + } + + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { + initialize() + if T.self is Int32.Type && source is NSNumber { + return source.intValue as! T; + } + if T.self is Int64.Type && source is NSNumber { + return source.longLongValue as! T; + } + if source is T { + return source as! T + } + + let key = "\(T.self)" + if let decoder = decoders[key] { + return decoder(source) as! T + } else { + fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient") + } + } + + static func decodeOptional(clazz clazz: T.Type, source: AnyObject?) -> T? { + if source is NSNull { + return nil + } + return source.map { (source: AnyObject) -> T in + Decoders.decode(clazz: clazz, source: source) + } + } + + static func decodeOptional(clazz clazz: [T].Type, source: AnyObject?) -> [T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static func decodeOptional(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [Key:T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static private func initialize() { + dispatch_once(&once) { + let formatters = [ + "yyyy-MM-dd", + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss'Z'", + "yyyy-MM-dd'T'HH:mm:ss.SSS" + ].map { (format: String) -> NSDateFormatter in + let formatter = NSDateFormatter() + formatter.dateFormat = format + return formatter + } + // Decoder for NSDate + Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in + if let sourceString = source as? String { + for formatter in formatters { + if let date = formatter.dateFromString(sourceString) { + return date + } + } + + } + if let sourceInt = source as? Int { + // treat as a java date + return NSDate(timeIntervalSince1970: Double(sourceInt / 1000) ) + } + fatalError("formatter failed to parse \(source)") + } + + // Decoder for [Return] + Decoders.addDecoder(clazz: [Return].self) { (source: AnyObject) -> [Return] in + return Decoders.decode(clazz: [Return].self, source: source) + } + // Decoder for Return + Decoders.addDecoder(clazz: Return.self) { (source: AnyObject) -> Return in + let sourceDictionary = source as! [NSObject:AnyObject] + let instance = Return() + instance._return = Decoders.decodeOptional(clazz: Int32.self, source: sourceDictionary["return"]) + return instance + } + } + } +} diff --git a/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models/Return.swift b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models/Return.swift new file mode 100644 index 00000000000..30c76776b83 --- /dev/null +++ b/samples/client/petstore-security-test/swift/SwaggerClient/Classes/Swaggers/Models/Return.swift @@ -0,0 +1,25 @@ +// +// Return.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +/** Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r */ +public class Return: JSONEncodable { + /** property description *_/ ' \" =end \\r\\n \\n \\r */ + public var _return: Int32? + + public init() {} + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["return"] = self._return?.encodeToJSON() + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore-security-test/swift/git_push.sh b/samples/client/petstore-security-test/swift/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/swift/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore-security-test/typescript-angular/.gitignore b/samples/client/petstore-security-test/typescript-angular/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-angular/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-angular/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-angular/API/Client/FakeApi.ts b/samples/client/petstore-security-test/typescript-angular/API/Client/FakeApi.ts new file mode 100644 index 00000000000..7e22ee8d0ed --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/API/Client/FakeApi.ts @@ -0,0 +1,85 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// + +/* tslint:disable:no-unused-variable member-ordering */ + +namespace API.Client { + 'use strict'; + + export class FakeApi { + protected basePath = 'https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'; + public defaultHeaders : any = {}; + + static $inject: string[] = ['$http', '$httpParamSerializer', 'basePath']; + + constructor(protected $http: ng.IHttpService, protected $httpParamSerializer?: (d: any) => any, basePath?: string) { + if (basePath !== undefined) { + this.basePath = basePath; + } + } + + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + public testCodeInjectEndRnNR (test code inject * ' " =end rn n r?: string, extraHttpRequestParams?: any ) : ng.IHttpPromise<{}> { + const localVarPath = this.basePath + '/fake'; + + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['test code inject */ ' " =end \r\n \n \r'] = test code inject * ' " =end rn n r; + + let httpRequestParams: any = { + method: 'PUT', + url: localVarPath, + json: false, + data: this.$httpParamSerializer(formParams), + params: queryParameters, + headers: headerParams + }; + + if (extraHttpRequestParams) { + httpRequestParams = this.extendObj(httpRequestParams, extraHttpRequestParams); + } + + return this.$http(httpRequestParams); + } + } +} diff --git a/samples/client/petstore-security-test/typescript-angular/API/Client/ModelReturn.ts b/samples/client/petstore-security-test/typescript-angular/API/Client/ModelReturn.ts new file mode 100644 index 00000000000..7509de72a30 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/API/Client/ModelReturn.ts @@ -0,0 +1,41 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/// + +namespace API.Client { + 'use strict'; + + /** + * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + */ + export interface ModelReturn { + + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + "return"?: number; + } + +} diff --git a/samples/client/petstore-security-test/typescript-angular/API/Client/api.d.ts b/samples/client/petstore-security-test/typescript-angular/API/Client/api.d.ts new file mode 100644 index 00000000000..258d4403228 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/API/Client/api.d.ts @@ -0,0 +1,3 @@ +/// + +/// diff --git a/samples/client/petstore-security-test/typescript-angular/LICENSE b/samples/client/petstore-security-test/typescript-angular/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-angular/git_push.sh b/samples/client/petstore-security-test/typescript-angular/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore-security-test/typescript-angular2/.gitignore b/samples/client/petstore-security-test/typescript-angular2/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-angular2/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-angular2/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-angular2/LICENSE b/samples/client/petstore-security-test/typescript-angular2/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts b/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts new file mode 100644 index 00000000000..88b8e7a6562 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/api/FakeApi.ts @@ -0,0 +1,79 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import {Http, Headers, RequestOptionsArgs, Response, URLSearchParams} from '@angular/http'; +import {Injectable, Optional} from '@angular/core'; +import {Observable} from 'rxjs/Observable'; +import * as models from '../model/models'; +import 'rxjs/Rx'; + +/* tslint:disable:no-unused-variable member-ordering */ + +'use strict'; + +@Injectable() +export class FakeApi { + protected basePath = 'https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'; + public defaultHeaders : Headers = new Headers(); + + constructor(protected http: Http, @Optional() basePath: string) { + if (basePath) { + this.basePath = basePath; + } + } + + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + public testCodeInjectEndRnNR (test code inject * ' " =end rn n r?: string, extraHttpRequestParams?: any ) : Observable<{}> { + const path = this.basePath + '/fake'; + + let queryParameters = new URLSearchParams(); + let headerParams = this.defaultHeaders; + let formParams = new URLSearchParams(); + + headerParams.set('Content-Type', 'application/x-www-form-urlencoded'); + + formParams['test code inject */ ' " =end \r\n \n \r'] = test code inject * ' " =end rn n r; + + let requestOptions: RequestOptionsArgs = { + method: 'PUT', + headers: headerParams, + search: queryParameters + }; + requestOptions.body = formParams.toString(); + + return this.http.request(path, requestOptions) + .map((response: Response) => { + if (response.status === 204) { + return undefined; + } else { + return response.json(); + } + }); + } + +} diff --git a/samples/client/petstore-security-test/typescript-angular2/api/api.ts b/samples/client/petstore-security-test/typescript-angular2/api/api.ts new file mode 100644 index 00000000000..9525ab85127 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/api/api.ts @@ -0,0 +1 @@ +export * from './FakeApi'; diff --git a/samples/client/petstore-security-test/typescript-angular2/git_push.sh b/samples/client/petstore-security-test/typescript-angular2/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore-security-test/typescript-angular2/index.ts b/samples/client/petstore-security-test/typescript-angular2/index.ts new file mode 100644 index 00000000000..557365516ad --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/index.ts @@ -0,0 +1,2 @@ +export * from './api/api'; +export * from './model/models'; \ No newline at end of file diff --git a/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts b/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts new file mode 100644 index 00000000000..23c982f6888 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/model/ModelReturn.ts @@ -0,0 +1,38 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +'use strict'; +import * as models from './models'; + +/** + * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + */ +export interface ModelReturn { + + + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + return?: number; +} diff --git a/samples/client/petstore-security-test/typescript-angular2/model/models.ts b/samples/client/petstore-security-test/typescript-angular2/model/models.ts new file mode 100644 index 00000000000..df8a2d48008 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-angular2/model/models.ts @@ -0,0 +1 @@ +export * from './ModelReturn'; diff --git a/samples/client/petstore-security-test/typescript-fetch/.gitignore b/samples/client/petstore-security-test/typescript-fetch/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-fetch/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-fetch/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-fetch/LICENSE b/samples/client/petstore-security-test/typescript-fetch/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-fetch/README.md b/samples/client/petstore-security-test/typescript-fetch/README.md new file mode 100644 index 00000000000..db2dfccec36 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/README.md @@ -0,0 +1,54 @@ +# TypeScript-Fetch + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Installation ### + +`swagger-codegen` does not generate JavaScript directly. The generated Node module comes with `package.json` that bundles `typescript` and `typings` so it can self-compile during `prepublish` stage. The should be run automatically during `npm install` or `npm publish`. + +CAVEAT: Due to [privilege implications](https://docs.npmjs.com/misc/scripts#user), `npm` would skip all scripts if the user is `root`. You would need to manually run it with `npm run prepublish` or run `npm install --unsafe-perm`. + +#### NPM #### +You may publish the module to NPM. In this case, you would be able to install the module as any other NPM module. It maybe useful to use [scoped packages](https://docs.npmjs.com/misc/scope). + +You can also use `npm link` to link the module. However, this would not modify `package.json` of the installing project, as such you would need to relink everytime you deploy that project. + +You can also directly install the module using `npm install file_path`. If you do `npm install file_path --save`, NPM will save relative path to `package.json`. In this case, `npm install` and `npm shrinkwrap` may misbehave. You would need to manually edit `package.json` and replace it with absolute path. + +Regardless of which method you deployed your NPM module, the ES6 module syntaxes are as follows: +``` +import * as localName from 'npmName'; +import {operationId} from 'npmName'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('npmName'); +``` + +#### Direct copy/symlink #### +You may also simply copy or symlink the generated module into a directory under your project. The syntax of this is as follows: + +With ES6 module syntax, the following syntaxes are supported: +``` +import * as localName from './symlinkDir'; +import {operationId} from './symlinkDir'; +``` +The CommonJS syntax is as follows: +``` +import localName = require('./symlinkDir')'; +``` diff --git a/samples/client/petstore-security-test/typescript-fetch/api.ts b/samples/client/petstore-security-test/typescript-fetch/api.ts new file mode 100644 index 00000000000..b439ec1d8ed --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/api.ts @@ -0,0 +1,125 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as querystring from "querystring"; +import * as url from "url"; + +import * as isomorphicFetch from "isomorphic-fetch"; +import * as assign from "core-js/library/fn/object/assign"; + +interface Dictionary { [index: string]: T; } +export interface FetchAPI { (url: string, init?: any): Promise; } + +const BASE_PATH = "https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r"; + +export interface FetchArgs { + url: string; + options: any; +} + +export class BaseAPI { + basePath: string; + fetch: FetchAPI; + + constructor(fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) { + this.basePath = basePath; + this.fetch = fetch; + } +} + +/** + * Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r + */ +export interface ModelReturn { + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + "return"?: number; +} + + + +/** + * FakeApi - fetch parameter creator + */ +export const FakeApiFetchParamCreactor = { + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }): FetchArgs { + const baseUrl = `/fake`; + let urlObj = url.parse(baseUrl, true); + let fetchOptions: RequestInit = { method: "PUT" }; + + let contentTypeHeader: Dictionary; + contentTypeHeader = { "Content-Type": "application/x-www-form-urlencoded" }; + fetchOptions.body = querystring.stringify({ + "test code inject */ ' " =end \r\n \n \r": params.test code inject * ' " =end rn n r, + }); + if (contentTypeHeader) { + fetchOptions.headers = contentTypeHeader; + } + return { + url: url.format(urlObj), + options: fetchOptions, + }; + }, +} + +/** + * FakeApi - functional programming interface + */ +export const FakeApiFp = { + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }): (fetch: FetchAPI, basePath?: string) => Promise { + const fetchArgs = FakeApiFetchParamCreactor.testCodeInjectEndRnNR(params); + return (fetch: FetchAPI = isomorphicFetch, basePath: string = BASE_PATH) => { + return fetch(basePath + fetchArgs.url, fetchArgs.options).then((response) => { + if (response.status >= 200 && response.status < 300) { + return response; + } else { + throw response; + } + }); + }; + }, +}; + +/** + * FakeApi - object-oriented interface + */ +export class FakeApi extends BaseAPI { + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + testCodeInjectEndRnNR(params: { test code inject * ' " =end rn n r?: string; }) { + return FakeApiFp.testCodeInjectEndRnNR(params)(this.fetch, this.basePath); + } +} + diff --git a/samples/client/petstore-security-test/typescript-fetch/git_push.sh b/samples/client/petstore-security-test/typescript-fetch/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore-security-test/typescript-fetch/package.json b/samples/client/petstore-security-test/typescript-fetch/package.json new file mode 100644 index 00000000000..97e572353a3 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/package.json @@ -0,0 +1,19 @@ +{ + "name": "typescript-fetch-api", + "version": "0.0.0", + "license": "Apache-2.0", + "main": "./dist/api.js", + "browser": "./dist/api.js", + "typings": "./dist/api.d.ts", + "dependencies": { + "core-js": "^2.4.0", + "isomorphic-fetch": "^2.2.1" + }, + "scripts" : { + "prepublish" : "typings install && tsc" + }, + "devDependencies": { + "typescript": "^1.8.10", + "typings": "^1.0.4" + } +} diff --git a/samples/client/petstore-security-test/typescript-fetch/tsconfig.json b/samples/client/petstore-security-test/typescript-fetch/tsconfig.json new file mode 100644 index 00000000000..72ff2567206 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es5", + "module": "commonjs", + "noImplicitAny": true, + "outDir": "dist", + "rootDir": "." + }, + "exclude": [ + "dist", + "node_modules", + "typings/browser", + "typings/main", + "typings/main.d.ts" + ] +} diff --git a/samples/client/petstore-security-test/typescript-fetch/typings.json b/samples/client/petstore-security-test/typescript-fetch/typings.json new file mode 100644 index 00000000000..a82ea152b4a --- /dev/null +++ b/samples/client/petstore-security-test/typescript-fetch/typings.json @@ -0,0 +1,9 @@ +{ + "version": false, + "dependencies": {}, + "globalDependencies": { + "core-js": "registry:dt/core-js#0.0.0+20160317120654", + "node": "registry:dt/node#4.0.0+20160423143914", + "isomorphic-fetch": "registry:dt/isomorphic-fetch#0.0.0+20160505171433" + } +} diff --git a/samples/client/petstore-security-test/typescript-node/.gitignore b/samples/client/petstore-security-test/typescript-node/.gitignore new file mode 100644 index 00000000000..35e2fb2b02e --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/.gitignore @@ -0,0 +1,3 @@ +wwwroot/*.js +node_modules +typings diff --git a/samples/client/petstore-security-test/typescript-node/.swagger-codegen-ignore b/samples/client/petstore-security-test/typescript-node/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore-security-test/typescript-node/LICENSE b/samples/client/petstore-security-test/typescript-node/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/client/petstore-security-test/typescript-node/api.ts b/samples/client/petstore-security-test/typescript-node/api.ts new file mode 100644 index 00000000000..4afd3239aa3 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/api.ts @@ -0,0 +1,193 @@ +/** + * Swagger Petstore *_/ ' \" =end \\r\\n \\n \\r + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ *_/ ' \" =end + * + * OpenAPI spec version: 1.0.0 *_/ ' \" =end \\r\\n \\n \\r + * Contact: apiteam@swagger.io *_/ ' \" =end \\r\\n \\n \\r + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import request = require('request'); +import http = require('http'); +import Promise = require('bluebird'); + +let defaultBasePath = 'https://petstore.swagger.io *_/ ' \" =end \\r\\n \\n \\r/v2 *_/ ' \" =end \\r\\n \\n \\r'; + +// =============================================== +// This file is autogenerated - Please do not edit +// =============================================== + +/* tslint:disable:no-unused-variable */ + +/** +* Model for testing reserved words *_/ ' \" =end \\r\\n \\n \\r +*/ +export class ModelReturn { + /** + * property description *_/ ' \" =end \\r\\n \\n \\r + */ + 'return': number; +} + + +export interface Authentication { + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: request.Options): void; +} + +export class HttpBasicAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + requestOptions.auth = { + username: this.username, password: this.password + } + } +} + +export class ApiKeyAuth implements Authentication { + public apiKey: string; + + constructor(private location: string, private paramName: string) { + } + + applyToRequest(requestOptions: request.Options): void { + if (this.location == "query") { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if (this.location == "header") { + requestOptions.headers[this.paramName] = this.apiKey; + } + } +} + +export class OAuth implements Authentication { + public accessToken: string; + + applyToRequest(requestOptions: request.Options): void { + requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; + } +} + +export class VoidAuth implements Authentication { + public username: string; + public password: string; + applyToRequest(requestOptions: request.Options): void { + // Do nothing + } +} + +export enum FakeApiApiKeys { + api_key, +} + +export class FakeApi { + protected basePath = defaultBasePath; + protected defaultHeaders : any = {}; + protected _useQuerystring : boolean = false; + + protected authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key */ ' " =end \r\n \n \r'), + 'petstore_auth': new OAuth(), + } + + constructor(basePath?: string); + constructor(basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } + + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + + public setApiKey(key: FakeApiApiKeys, value: string) { + this.authentications[FakeApiApiKeys[key]].apiKey = value; + } + + set accessToken(token: string) { + this.authentications.petstore_auth.accessToken = token; + } + private extendObj(objA: T1, objB: T2) { + for(let key in objB){ + if(objB.hasOwnProperty(key)){ + objA[key] = objB[key]; + } + } + return objA; + } + /** + * To test code injection *_/ ' \" =end \\r\\n \\n \\r + * + * @param test code inject * ' " =end rn n r To test code injection *_/ ' \" =end \\r\\n \\n \\r + */ + public testCodeInjectEndRnNR (test code inject * ' " =end rn n r?: string) : Promise<{ response: http.ClientResponse; body?: any; }> { + const localVarPath = this.basePath + '/fake'; + let queryParameters: any = {}; + let headerParams: any = this.extendObj({}, this.defaultHeaders); + let formParams: any = {}; + + + let useFormData = false; + + if (test code inject * ' " =end rn n r !== undefined) { + formParams['test code inject */ ' " =end \r\n \n \r'] = test code inject * ' " =end rn n r; + } + + let requestOptions: request.Options = { + method: 'PUT', + qs: queryParameters, + headers: headerParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + this.authentications.default.applyToRequest(requestOptions); + + if (Object.keys(formParams).length) { + if (useFormData) { + (requestOptions).formData = formParams; + } else { + requestOptions.form = formParams; + } + } + return new Promise<{ response: http.ClientResponse; body?: any; }>((resolve, reject) => { + request(requestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + if (response.statusCode >= 200 && response.statusCode <= 299) { + resolve({ response: response, body: body }); + } else { + reject({ response: response, body: body }); + } + } + }); + }); + } +} diff --git a/samples/client/petstore-security-test/typescript-node/git_push.sh b/samples/client/petstore-security-test/typescript-node/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore-security-test/typescript-node/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' +