diff --git a/.gitignore b/.gitignore index ae4c9e53c36d..b17bf46aa108 100644 --- a/.gitignore +++ b/.gitignore @@ -28,4 +28,3 @@ target .lib atlassian-ide-plugin.xml .DS_Store -*~ diff --git a/.travis.yml b/.travis.yml index 6651d4dd98ef..85a33a2d847e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,4 @@ -language: scala -scala: - - 2.10.0 +language: java +script: mvn verify +jdk: + - oraclejdk7 diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 9f93e067e8e1..000000000000 --- a/LICENSE +++ /dev/null @@ -1,11 +0,0 @@ -Copyright 2014 Reverb Technologies, Inc. - -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 [apache.org/licenses/LICENSE-2.0](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/README.md b/README.md index bdb8d2bed9ab..cf28a5c38de5 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,7 @@ [![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.png)](https://travis-ci.org/swagger-api/swagger-codegen) ## Overview -This is the swagger codegen project, which allows generation of client libraries automatically from a -Swagger-compliant server. +This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server. ## What's Swagger? @@ -15,127 +14,84 @@ Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additi ## Compatibility -The Swagger Specification has undergone 3 revisions since initial creation in 2010. Compatibility between swagger-codegen and the Swagger specification is as follows: +The Swagger Specification has undergone 3 revisions since initial creation in 2010. The swagger-codegen project has the following compatibilities with the swagger specification: -Swagger Codegen Version | Release Date | Swagger Spec compatibility | Notes +Swagger Codegen Version | Release Date | Swagger Spec compatability | Notes ----------------------- | ------------ | -------------------------- | ----- -2.1.0 (in development) | n/a | 1.0, 1.1, 1.2, 2.0 | [branch develop_2.0](https://github.com/swagger-api/swagger-codegen/tree/develop_2.0) -2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/2.0.17) +2.1.2-M1 (master) | 2015-02-23 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.0-M1](https://github.com/swagger-api/swagger-codegen) +2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) 1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) ### Prerequisites You need the following installed and available in your $PATH: -* [Java 1.7](http://java.oracle.com) - -Note! Some folks have had issues with OOM errors with java version "1.6.0_51". It's strongly suggested that you upgrade to 1.7! +* [Java 7](http://java.oracle.com) * [Apache maven 3.0.3 or greater](http://maven.apache.org/) -* [Scala 2.10.4](http://www.scala-lang.org) - -* [sbt (only download if you're building on Windows)](http://www.scala-sbt.org/) - -You also need to add the scala binary to your PATH. - -After cloning the project, you need to build it from source with this command: +After cloning the project, you can build it from source with this command: ``` -./sbt assembly +mvn package ``` -or for Windows... - -``` -sbt assembly -``` - - ### To generate a sample client library -You can build a client against Wordnik's [petstore](http://petstore.swagger.wordnik.com) API as follows: +You can build a client against the swagger sample [petstore](http://petstore.swagger.io) API as follows: ``` -./bin/scala-petstore.sh +./bin/java-petstore.sh ``` -This will run the script in [samples/client/petstore/ScalaPetstoreCodegen.scala](https://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/scala/ScalaPetstoreCodegen.scala) and create the client. You can then -compile and run the client, as well as unit tests against it: +This will run the generator with this command: ``` -cd samples/client/petstore/scala +java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.2-M1.jar \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l java \ + -o samples/client/petstore/java +``` + +With a number of options. You can get the options with the -h flag: +``` +usage: Codegen + -a,--auth addes authorization headers when fetching the + swagger definitions remotely. Pass in a + URL-encoded string of name:header with a comma + separating multiple values + -d,--debug-info prints additional info for debugging + -h,--help shows this message + -i,--input-spec location of the swagger spec, as URL or file + -l,--lang client language to generate. + Available languages include: + [android, java, jaxrs, nodejs, objc, scalatra, + scala, dynamic-html, html, swagger, tizen, php, + python] + -o,--output where to write the generated files + -t,--template-dir folder containing the template files + ``` + +You can then compile and run the client, as well as unit tests against it: + +``` +cd samples/client/petstore/java mvn package ``` Other languages have petstore samples, too: ``` -./bin/flash-petstore.sh +./bin/android-petstore.sh ./bin/java-petstore.sh ./bin/objc-petstore.sh -./bin/php-petstore.sh -./bin/python-petstore.sh -./bin/python3-petstore.sh -./bin/ruby-petstore.sh ``` ### Generating libraries from your server -It's just as easy--you can either run the default generators: - -``` -./bin/runscala.sh com.wordnik.swagger.codegen.BasicScalaGenerator http://petstore.swagger.wordnik.com/api/api-docs special-key -``` - -Replace `Scala` with `Flash`, `Java`, `Objc`, `PHP`, `Python`, `Python3`, `Ruby`. - -You will probably want to override some of the defaults--like packages, etc. For doing this, just create a scala -script with the overrides you want. Follow [ScalaPetstoreCodegen](https://github.com/swagger-api/swagger-codegen/blob/master/samples/client/petstore/scala/ScalaPetstoreCodegen.scala) as an example: - -For example, create `src/main/scala/MyCodegen.scala` with these contents: - -```scala -import com.wordnik.swagger.codegen.BasicScalaGenerator - -object MyCodegen extends BasicScalaGenerator { - def main(args: Array[String]) = generateClient(args) - - // location of templates - override def templateDir = "scala" - - // where to write generated code - override def destinationDir = "client/scala/src/main/scala" - - // api invoker package - override def invokerPackage = "com.myapi.client" - - // package for models - override def modelPackage = Some("com.myapi.client.model") - - // package for api classes - override def apiPackage = Some("com.myapi.client.api") - - // supporting classes - override def supportingFiles = List( - ("apiInvoker.mustache", destinationDir + java.io.File.separator + packageName.replaceAll("\\.", java.io.File.separator), "ApiInvoker.scala"), - ("pom.mustache", destinationDir, "pom.xml") - ) -} -``` - -Now you can generate your client like this: - -``` -./bin/runscala.sh src/main/scala/MyCodegen.scala http://my.api.com/resources.json super-secret-key -``` - -w00t! Thanks to the scala interpretor, you didn't even need to recompile. +It's just as easy--just use the `-i` flag to point to either a server or file. ### Modifying the client library format -Don't like the default swagger client syntax? Want a different language supported? No problem! Swagger codegen -processes mustache templates with the [scalate](http://scalate.fusesource.org/) engine. You can modify our templates or -make your own. +Don't like the default swagger client syntax? Want a different language supported? No problem! Swagger codegen processes mustache templates with the [jmustache](https://github.com/samskivert/jmustache) engine. You can modify our templates or make your own. -You can look at `src/main/resources/${your-language}` for examples. To make your own templates, create your own files -and override the `templateDir` in your script to point to the right place. It actually is that easy. +You can look at `modules/swagger-codegen/src/main/resources/${your-language}` for examples. To make your own templates, create your own files and use the `-t` flag to specify your tempalte folder. It actually is that easy. ### Where is Javascript??? See our [javascript library](http://github.com/swagger-api/swagger-js)--it's completely dynamic and doesn't require @@ -148,102 +104,132 @@ If you don't want to call your server, you can save the swagger spec files into to the code generator like this: ``` --DfileMap=/path/to/resource-listing +-i ./modules/swagger-codegen/src/test/resources/2_0/petstore.json ``` -Or for example: +Great for creating libraries on your ci server, from the [Swagger Editor](http://editor.swagger.io)... or while coding on an airplane. + +### Customizing the generator + +There are different aspects of customizing the code generator beyond just creating or modifying templates. Each language has a supporting configuration file to handle different type mappings, etc: + ``` -./bin/java-petstore-filemap.sh +$ ls -1 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ +AndroidClientCodegen.java +JavaClientCodegen.java +JaxRSServerCodegen.java +NodeJSServerCodegen.java +ObjcClientCodegen.java +PhpClientCodegen.java +PythonClientCodegen.java +ScalaClientCodegen.java +ScalatraServerCodegen.java +StaticDocCodegen.java +StaticHtmlGenerator.java +SwaggerGenerator.java +TizenClientCodegen.java ``` -Which simple passes `-DfileMap=src/test/resources/petstore` as an argument. Great for creating libraries on your -ci server... or while coding on an airplane. +Each of these files creates reasonable defaults so you can get running quickly. But if you want to configure package names, prefixes, model folders, etc., you may want to extend these. + +To change, for example, the prefix for the Objective-C generated files, simply subclass the ObjcClientCodegen.java: + +``` +package com.mycompany.swagger.codegen; + +import com.wordnik.swagger.codegen.languages.*; + +public class MyObjcCodegen extends ObjcClientCodegen { + static { + PREFIX = "HELO"; + } +} +``` + +and specify the `classname` when running the generator: + +``` +-i com.mycompany.swagger.codegen.MyObjcCodegen +``` + +Your subclass will now be loaded and overrides the `PREFIX` value in the superclass. ### Validating your swagger spec -You can use the validation tool to see that your server is creating a proper spec file. If you want to learn -more about the spec file and format, please see [swagger-spec](https://github.com/swagger-api/swagger-spec). This -tool will read the server and generate a report of any violations of the spec. If there are violations, the -client codegen and ui may not work correctly. -To validate an api and write output to ./swagger-errors.html: +You have options. The easiest is to use our [online validator](https://github.com/swagger-api/validator-badge) which not only will let you validate your spec, but with the debug flag, you can see what's wrong with your spec. For example: + +http://online.swagger.io/validator/debug?url=http://petstore.swagger.io/v2/swagger.json + +### Generating dynamic html api documentation + +To do so, just use the `-l dynamic-html` flag when reading a spec file. This creates HTML documentation that is available as a single-page application with AJAX. To view the documentation: ``` -./bin/validate.sh http://petstore.swagger.wordnik.com/api/api-docs "specia-key" ./swagger-errors.html +cd samples/dynamic-html/ +npm install +node . ``` -### Generating static api documentation -If you need to make static pages or don't want the sandbox of the swagger-ui, you can use the codegen to build them. Remember, the engine is just using mustache templates--the output format is your call. +Which launches a node.js server so the AJAX calls have a place to go. + + +### Generating static html api documentation + +To do so, just use the `-l html` flag when reading a spec file. This creates a single, simple HTML file with embedded css so you can ship it as an email attachment, or load it from your filesystem: ``` -./bin/static-docs.sh +cd samples/html/ +open index.html ``` -Will produce the output here: - -``` -https://github.com/swagger-api/swagger-codegen/tree/master/samples/swagger-static-docs/docs -``` - -which is based on these templates: - -``` -https://github.com/swagger-api/swagger-codegen/tree/master/src/main/resources/swagger-static -``` - -and looks like this - -![Image](https://raw.github.com/swagger-api/swagger-codegen/master/samples/docs/swagger-static-docs/static-docs.png) ### To build a server stub You can also use the codegen to generate a server for a couple different frameworks. Take a look here: -* [javascript node.js Server generator](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/node) - -* [ruby sinatra generator](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/sinatra) - -* [scala scalatra generator](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) - -* [java jax-rs generator](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/java-jaxrs) - - -### Migrating from Swagger 1.1 to 1.2 format - -If you've spent time hand-crafting your swagger spec files, you can use the [SpecConverter](https://github.com/swagger-api/swagger-codegen/blob/master/src/main/scala/com/wordnik/swagger/codegen/SpecConverter.scala) to do the dirty work. For example: - -```bash -$ ./bin/update-spec.sh http://developer.wordnik.com/v4/resources.json wordnik-developer -writing file wordnik-developer/api-docs -calling: http://developer.wordnik.com/v4/account.json -calling: http://developer.wordnik.com/v4/word.json -calling: http://developer.wordnik.com/v4/words.json -calling: http://developer.wordnik.com/v4/wordList.json -calling: http://developer.wordnik.com/v4/wordLists.json -writing file wordnik-developer/account -writing file wordnik-developer/word -writing file wordnik-developer/words -writing file wordnik-developer/wordList -writing file wordnik-developer/wordLists +### node.js +``` +java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.2-M1.jar \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l nodejs \ + -o samples/server/petstore/nodejs ``` -Will read the 1.1 spec from wordnik developer and write it into the folder called `wordnik-developer`. +### rails-grape +#### Not yet migrated to this branch +### scala scalatra +``` +java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.2-M1.jar \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l scalatra \ + -o samples/server/petstore/scalatra +``` + +### java jax-rs + +``` +java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.2-M1.jar \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l jaxrs \ + -o samples/server/petstore/jaxrs +``` + ### To build the codegen library This will create the swagger-codegen library from source. ``` -./sbt assembly +mvn package ``` -Note! The templates are included in the library generated. If you want to modify the templates, you'll need to -either repackage the library OR modify your codegen script to use a file path! +Note! The templates are included in the library generated. If you want to modify the templates, you'll need to either repackage the library OR specify a path to your scripts License ------- -Copyright 2014 Reverb Technologies, Inc. +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/bin/Version.scala b/bin/Version.scala deleted file mode 100644 index a269af181179..000000000000 --- a/bin/Version.scala +++ /dev/null @@ -1,6 +0,0 @@ -val version = scala.util.Properties.scalaPropOrElse("version.number", "unknown").toString match { - case s if s startsWith "2.10" => "2.10" - case s if s startsWith "2.11" => "2.11" - case e: String => e -} -println(version) diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 716db5bae155..af3da09a8cde 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -18,20 +18,14 @@ if [ ! -d "${APP_DIR}" ]; then fi cd $APP_DIR -./bin/java-wordnik-api.sh -./bin/php-wordnik-api.sh -./bin/python3-wordnik-api.sh -./bin/objc-wordnik-api.sh -./bin/python-wordnik-api.sh -./bin/scala-wordnik-api.sh - ./bin/android-java-petstore.sh -./bin/csharp-petstore.sh -./bin/flash-petstore.sh +./bin/dynamic-html.sh +./bin/html.sh +./bin/jaxrs-petstore-server.sh +./bin/java-petstore-filemap.sh ./bin/java-petstore.sh -./bin/objc-petstore.sh ./bin/php-petstore.sh ./bin/python-petstore.sh -./bin/python3-petstore.sh -./bin/ruby-petstore.sh +./bin/objc-petstore.sh ./bin/scala-petstore.sh +./bin/tizen-petstore.sh diff --git a/bin/all-wordnik.sh b/bin/all-wordnik.sh new file mode 100755 index 000000000000..95f71f10ab08 --- /dev/null +++ b/bin/all-wordnik.sh @@ -0,0 +1,24 @@ +#!/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 + +cd $APP_DIR +./bin/android-java-wordnik-api.sh +./bin/java-wordnik-api.sh +./bin/objc-wordnik-api.sh +./bin/scala-wordnik-api.sh diff --git a/bin/android-java-petstore.sh b/bin/android-java-petstore.sh index edde6205216f..5747ff495319 100755 --- a/bin/android-java-petstore.sh +++ b/bin/android-java-petstore.sh @@ -17,16 +17,20 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -cd $APP_DIR -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) +root=./modules/swagger-codegen-distribution/pom.xml +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" +ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android-java" -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/android-java-wordnik-api.sh b/bin/android-java-wordnik-api.sh index aba96fb90968..3f2654a1685f 100755 --- a/bin/android-java-wordnik-api.sh +++ b/bin/android-java-wordnik-api.sh @@ -1,7 +1,6 @@ #!/bin/sh SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -18,15 +17,20 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -cd $APP_DIR +root=./modules/swagger-codegen-distribution/pom.xml +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" +ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l android -o samples/client/wordnik/android-java" -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/csharp-petstore.sh b/bin/csharp-petstore.sh deleted file mode 100755 index 0b38c046ce01..000000000000 --- a/bin/csharp-petstore.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# 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="$@ samples/client/petstore/csharp/CsharpPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/dynamic-html.sh b/bin/dynamic-html.sh new file mode 100755 index 000000000000..b19a18cfb965 --- /dev/null +++ b/bin/dynamic-html.sh @@ -0,0 +1,36 @@ +#!/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 + +root=./modules/swagger-codegen-distribution/pom.xml + +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l dynamic-html -o samples/dynamic-html" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/flash-petstore.sh b/bin/flash-petstore.sh deleted file mode 100755 index 37a591a9554e..000000000000 --- a/bin/flash-petstore.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# 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="$@ samples/client/petstore/flash/FlashPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/html-petstore.sh b/bin/html-petstore.sh new file mode 100755 index 000000000000..00ce8c174b94 --- /dev/null +++ b/bin/html-petstore.sh @@ -0,0 +1,36 @@ +#!/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 + +root=./modules/swagger-codegen-distribution/pom.xml + +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l html -o samples/html" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore-filemap.sh b/bin/java-petstore-filemap.sh deleted file mode 100755 index b8b71151f2b1..000000000000 --- a/bin/java-petstore-filemap.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DfileMap=src/test/resources/petstore-1.2/api-docs -DloggerPath=conf/log4j.properties" -ags="$@ samples/client/petstore/java/JavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/java-petstore.sh b/bin/java-petstore.sh index fee35e8df4a9..04345b346ab7 100755 --- a/bin/java-petstore.sh +++ b/bin/java-petstore.sh @@ -1,7 +1,6 @@ #!/bin/sh SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -18,15 +17,20 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -cd $APP_DIR +root=./modules/swagger-codegen-distribution/pom.xml +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ samples/client/petstore/java/JavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" +ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -o samples/client/petstore/java" -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-wordnik-api.sh b/bin/java-wordnik-api.sh index 1277e4560097..b4cae8590bc2 100755 --- a/bin/java-wordnik-api.sh +++ b/bin/java-wordnik-api.sh @@ -1,7 +1,6 @@ #!/bin/sh SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -18,15 +17,20 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -cd $APP_DIR +root=./modules/swagger-codegen-distribution/pom.xml +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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 -DfileMap=samples/client/wordnik-api/spec-files/resources.json" -ags="$@ samples/client/wordnik-api/java/JavaWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l java -o samples/client/wordnik/java" -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-petstore-server.sh b/bin/jaxrs-petstore-server.sh new file mode 100755 index 000000000000..be8f17502f7c --- /dev/null +++ b/bin/jaxrs-petstore-server.sh @@ -0,0 +1,36 @@ +#!/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 + +root=./modules/swagger-codegen-distribution/pom.xml + +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs -o samples/server/petstore/jaxrs" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/nodejs-petstore-server.sh b/bin/nodejs-petstore-server.sh new file mode 100755 index 000000000000..c8492838ee36 --- /dev/null +++ b/bin/nodejs-petstore-server.sh @@ -0,0 +1,36 @@ +#!/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 + +root=./modules/swagger-codegen-distribution/pom.xml + +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l nodejs -o samples/server/petstore/nodejs" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/objc-petstore.sh b/bin/objc-petstore.sh index ad1c8dcdc373..0e4da6eb4b3b 100755 --- a/bin/objc-petstore.sh +++ b/bin/objc-petstore.sh @@ -1,9 +1,6 @@ #!/bin/sh SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -version="$(scala ./bin/Version.scala)" while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -20,15 +17,20 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -cd $APP_DIR +root=./modules/swagger-codegen-distribution/pom.xml +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ samples/client/petstore/objc/ObjcPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" +ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l objc -o samples/client/petstore/objc" -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/objc-wordnik-api.sh b/bin/objc-wordnik-api.sh index bd380dcea926..68eb1b8226de 100755 --- a/bin/objc-wordnik-api.sh +++ b/bin/objc-wordnik-api.sh @@ -1,7 +1,6 @@ #!/bin/sh SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -18,15 +17,20 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -cd $APP_DIR +root=./modules/swagger-codegen-distribution/pom.xml +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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 -DfileMap=samples/client/wordnik-api/spec-files/resources.json" -ags="$@ samples/client/wordnik-api/objc/ObjcWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l objc -o samples/client/wordnik/objc" -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/php-petstore.sh b/bin/php-petstore.sh index 07887a0775ce..fe210b2de24a 100755 --- a/bin/php-petstore.sh +++ b/bin/php-petstore.sh @@ -1,7 +1,6 @@ #!/bin/sh SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -18,15 +17,20 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -cd $APP_DIR +root=./modules/swagger-codegen-distribution/pom.xml +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ samples/client/petstore/php/PHPPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" +ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l php -o samples/client/petstore/php" -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/php-wordnik-api.sh b/bin/php-wordnik-api.sh deleted file mode 100755 index d03bfe04990f..000000000000 --- a/bin/php-wordnik-api.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# 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 -DfileMap=samples/client/wordnik-api/spec-files/resources.json" -ags="$@ samples/client/wordnik-api/php/PHPWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/python-petstore.sh b/bin/python-petstore.sh index 370b7f429808..2ef1f44ad7ef 100755 --- a/bin/python-petstore.sh +++ b/bin/python-petstore.sh @@ -1,7 +1,6 @@ #!/bin/sh SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -18,15 +17,20 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -cd $APP_DIR +root=./modules/swagger-codegen-distribution/pom.xml +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ samples/client/petstore/python/PythonPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" +ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l python -o samples/client/petstore/python" -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/python-wordnik-api.sh b/bin/python-wordnik-api.sh deleted file mode 100755 index 3af48e9675cc..000000000000 --- a/bin/python-wordnik-api.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# 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 -DfileMap=samples/client/wordnik-api/spec-files/resources.json" -ags="$@ samples/client/wordnik-api/python/PythonWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/python3-petstore.sh b/bin/python3-petstore.sh deleted file mode 100755 index a9fb758d9b7f..000000000000 --- a/bin/python3-petstore.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# 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="$@ samples/client/petstore/python3/Python3PetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/python3-wordnik-api.sh b/bin/python3-wordnik-api.sh deleted file mode 100755 index 77ae679bcf95..000000000000 --- a/bin/python3-wordnik-api.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# 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 -DfileMap=samples/client/wordnik-api/spec-files/resources.json" -ags="$@ samples/client/wordnik-api/python3/Python3WordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/ruby-petstore.sh b/bin/ruby-petstore.sh deleted file mode 100755 index a0f3fb742760..000000000000 --- a/bin/ruby-petstore.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# 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="$@ samples/client/petstore/ruby/RubyPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/runscala.sh b/bin/runscala.sh deleted file mode 100755 index 7e8572a6c5aa..000000000000 --- a/bin/runscala.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/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 - -cd $APP_DIR -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - - -# 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="$@" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/scala-async-petstore.sh b/bin/scala-async-petstore.sh new file mode 100755 index 000000000000..108f40f82e1f --- /dev/null +++ b/bin/scala-async-petstore.sh @@ -0,0 +1,36 @@ +#!/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 + +root=./modules/swagger-codegen-distribution/pom.xml + +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l async-scala -o samples/client/petstore/async-scala" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/scala-async.sh b/bin/scala-async.sh deleted file mode 100755 index d9618767a20f..000000000000 --- a/bin/scala-async.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=2.10 #$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# if you've executed sbt assembly previously it will use that instead. -ags="com.wordnik.swagger.codegen.ScalaAsyncClientGenerator $@" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - java -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/scala-petstore.sh b/bin/scala-petstore.sh index bb5a9b2afee7..55e54b6c74dc 100755 --- a/bin/scala-petstore.sh +++ b/bin/scala-petstore.sh @@ -1,7 +1,6 @@ #!/bin/sh SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -18,15 +17,20 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -cd $APP_DIR +root=./modules/swagger-codegen-distribution/pom.xml +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ samples/client/petstore/scala/ScalaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" +ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l scala -o samples/client/petstore/scala" -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/scala-wordnik-api.sh b/bin/scala-wordnik-api.sh index 2c1703507b24..73c1f8e7dece 100755 --- a/bin/scala-wordnik-api.sh +++ b/bin/scala-wordnik-api.sh @@ -1,7 +1,6 @@ #!/bin/sh SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -18,15 +17,20 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -cd $APP_DIR +root=./modules/swagger-codegen-distribution/pom.xml +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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 -DfileMap=samples/client/wordnik-api/spec-files/resources.json" -ags="$@ samples/client/wordnik-api/scala/ScalaWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l scala -o samples/client/wordnik/scala" -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/scalatra-petstore-server.sh b/bin/scalatra-petstore-server.sh new file mode 100755 index 000000000000..c84f0e2f4e0f --- /dev/null +++ b/bin/scalatra-petstore-server.sh @@ -0,0 +1,36 @@ +#!/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 + +root=./modules/swagger-codegen-distribution/pom.xml + +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l scalatra -o samples/server/petstore/scalatra" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/static-docs.sh b/bin/static-docs.sh deleted file mode 100755 index af769fa79a8c..000000000000 --- a/bin/static-docs.sh +++ /dev/null @@ -1,32 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# 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="$@ com.wordnik.swagger.codegen.SwaggerDocGenerator http://petstore.swagger.wordnik.com/api/api-docs" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/tizen-petstore.sh b/bin/tizen-petstore.sh new file mode 100755 index 000000000000..a0b1b4bdd96f --- /dev/null +++ b/bin/tizen-petstore.sh @@ -0,0 +1,36 @@ +#!/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 + +root=./modules/swagger-codegen-distribution/pom.xml + +# gets version of swagger-codegen +version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') + +executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.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="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l tizen -o samples/client/petstore/tizen" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/update-spec.sh b/bin/update-spec.sh deleted file mode 100755 index 5f5ea4ba78da..000000000000 --- a/bin/update-spec.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# if you've executed sbt assembly previously it will use that instead. -ags="com.wordnik.swagger.codegen.SpecConverter $@" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/validate.sh b/bin/validate.sh deleted file mode 100755 index efa4a6cee83e..000000000000 --- a/bin/validate.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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 - -cd $APP_DIR - - -# if you've executed sbt assembly previously it will use that instead. -ags="com.wordnik.swagger.codegen.spec.Validator $@" - -if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/*assembly*.jar $ags -else - echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" -fi diff --git a/bin/yml2swagger.js b/bin/yml2swagger.js deleted file mode 100644 index 2f4cce90a71e..000000000000 --- a/bin/yml2swagger.js +++ /dev/null @@ -1,56 +0,0 @@ -fs = require('fs') -yaml = require('js-yaml') - -var args = process.argv.splice(2); - -if(args.length == 0) { - process.exit(1); -} - -var arg0 = args[0]; -var outputdir = "."; - -if(args.length > 1) { - outputdir = args[1]; -} - -var file = fs.lstatSync(arg0); - -if(file.isFile()) { - convert(arg0, outputdir); -} -else if (file.isDirectory()) { - var files = fs.readdirSync(arg0); - files.map(function(item) { - var filename = arg0 + "/" + item; - var file = fs.lstatSync(filename); - if(file.isFile()) { - convert(filename, outputdir); - } - }); -} - -function convert(filename, outputdir) { - console.log("converting " + filename); - fs.readFile(filename, "utf8", function (err, data) { - if(err) { - console.log(err); - } - else { - try { - var js = yaml.load(data); - var prettyJs = JSON.stringify(js, undefined, 2); - var outputFilename = outputdir + "/" + filename.split("/").pop().replace(".yml", "") + ".json"; - console.log("writing to " + outputFilename); - fs.writeFile(outputFilename, prettyJs, function(err) { - if(err) { - console.log(err); - } - }); - } - catch (err) { - console.log(err); - } - } - }); -} diff --git a/build.sbt b/build.sbt deleted file mode 100644 index bcc9df96b823..000000000000 --- a/build.sbt +++ /dev/null @@ -1,137 +0,0 @@ -import xml.Group -import AssemblyKeys._ - -organization := "com.wordnik" - -name := "swagger-codegen" - -version := "2.0.18-SNAPSHOT" - -crossVersion := CrossVersion.full - -javacOptions ++= Seq("-target", "1.6", "-source", "1.6", "-Xlint:unchecked", "-Xlint:deprecation") - -scalacOptions ++= Seq("-optimize", "-unchecked", "-deprecation", "-Xcheckinit", "-encoding", "utf8") - -crossScalaVersions := Seq("2.10.0", "2.10.1", "2.10.2", "2.10.3", "2.10.4", "2.11.0", "2.11.1") - -scalaVersion := "2.10.4" - -libraryDependencies ++= Seq( - "org.json4s" %% "json4s-jackson" % "3.2.10", - "io.backchat.inflector" %% "scala-inflector" % "1.3.5", - "commons-io" % "commons-io" % "2.3", - "net.iharder" % "base64" % "2.3.8", - "ch.qos.logback" % "logback-classic" % "1.0.13" % "provided", - "org.rogach" %% "scallop" % "0.9.5", - "junit" % "junit" % "4.11" % "test", - "org.scalatest" %% "scalatest" % "2.1.7" % "test" -) - -libraryDependencies <+= scalaVersion { - case v if v.startsWith("2.9") => - "org.fusesource.scalate" % "scalate-core_2.9" % "1.6.1" - case v if v.startsWith("2.10") => - "org.scalatra.scalate" %% "scalate-core" % "1.7.0" - case v if v.startsWith("2.11") => - "org.scalatra.scalate" %% "scalate-core" % "1.7.0" -} - -libraryDependencies ++= { - scalaVersion.toString match { - case v if v.startsWith("2.10") || v.startsWith("2.11") => Seq("org.scala-lang" % "scala-reflect" % v) - case _ => Seq() - } -} - -resolvers += "Typesafe releases" at "http://repo.typesafe.com/typesafe/releases" - -packageOptions <+= (name, version, organization) map { - (title, version, vendor) => - Package.ManifestAttributes( - "Created-By" -> "Simple Build Tool", - "Built-By" -> System.getProperty("user.name"), - "Build-Jdk" -> System.getProperty("java.version"), - "Specification-Title" -> title, - "Specification-Version" -> version, - "Specification-Vendor" -> vendor, - "Implementation-Title" -> title, - "Implementation-Version" -> version, - "Implementation-Vendor-Id" -> vendor, - "Implementation-Vendor" -> vendor - ) -} - -publishTo <<= (version) { version: String => - if (version.trim.endsWith("SNAPSHOT")) - Some("Sonatype Nexus Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots") - else - Some("Sonatype Nexus Releases" at "https://oss.sonatype.org/service/local/staging/deploy/maven2") -} - -// publishTo := Some(Resolver.file("file", new File(Path.userHome.absolutePath+"/.m2/repository"))) - -artifact in (Compile, assembly) ~= { art => - art.copy(`classifier` = Some("assembly")) -} - -addArtifact(artifact in (Compile, assembly), assembly) - -publishMavenStyle := true - -publishArtifact in Test := false - -pomIncludeRepository := { x => false } - -credentials += Credentials(Path.userHome / ".ivy2" / ".credentials") - -homepage := Some(new URL("https://github.com/wordnik/swagger-codegen")) - -parallelExecution in Test := false - -startYear := Some(2009) - -licenses := Seq(("Apache License 2.0", new URL("http://www.apache.org/licenses/LICENSE-2.0.html"))) - -pomExtra <<= (pomExtra, name, description) {(pom, name, desc) => pom ++ Group( - - scm:git:git@github.com:wordnik/swagger-codegen.git - scm:git:git@github.com:wordnik/swagger-codegen.git - https://github.com/wordnik/swagger-codegen - - - github - https://github.com/wordnik/swagger-codegen/issues - - - - rpidikiti - Ramesh Pidikiti - ramesh@wordnik.com - - - ayush - Ayush Gupta - ayush@glugbot.com - - - fehguy - Tony Tam - fehguy@gmail.com - - - casualjim - Ivan Porto Carrero - http://flanders.co.nz/ - - - radius314 - Danny Gershman - danny.gershman@gmail.com - - -)} - -assemblySettings - -// jarName in assembly := "swagger-codegen.jar" diff --git a/distro/pom.xml.disabled b/distro/pom.xml.disabled deleted file mode 100644 index e547df07cf6a..000000000000 --- a/distro/pom.xml.disabled +++ /dev/null @@ -1,124 +0,0 @@ - - 4.0.0 - - org.sonatype.oss - oss-parent - 5 - - com.wordnik - swagger-codegen-distribution - jar - 2.0.2-SNAPSHOT - swagger-codegen-distribution - https://github.com/wordnik/swagger-codegen - - scm:git:git@github.com:wordnik/swagger-codegen.git - scm:git:git@github.com:wordnik/swagger-codegen.git - https://github.com/wordnik/swagger-codegen - - - 2.2.0 - - - - fehguy - Tony Tam - fehguy@gmail.com - - - - github - https://github.com/wordnik/swagger-codegen/issues - - - - wordnik-api - https://groups.google.com/forum/#!forum/wordnik-api - - - - - Apache License 2.0 - http://www.apache.org/licenses/LICENSE-2.0.html - repo - - - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - - - maven-failsafe-plugin - 2.6 - - - - integration-test - verify - - - - - - - - distro-assembly - package - - single - - - - maven-assembly-plugin - 2.3 - - - src/main/assembly/distribution.xml - - - - - org.apache.maven.plugins - maven-dependency-plugin - 2.4 - - - src-dependencies - package - - unpack-dependencies - - - com.wordnik - text-data - ${project.build.directory} - - - - - - - - - com.wordnik - swagger-codegen_2.9.1 - ${swagger.codegen.version} - compile - - - - 2.0.2-SNAPSHOT - - diff --git a/distro/src/main/assembly/distribution.xml b/distro/src/main/assembly/distribution.xml deleted file mode 100644 index 77d0fcb53104..000000000000 --- a/distro/src/main/assembly/distribution.xml +++ /dev/null @@ -1,29 +0,0 @@ - - distribution - swagger-codegen - false - - zip - - - - compile - target/lib - - *:jar:* - - - - - - ../bin - - *.* - - bin - - - diff --git a/modules/swagger-codegen-distribution/pom.xml b/modules/swagger-codegen-distribution/pom.xml new file mode 100644 index 000000000000..a91d5d0cc8e6 --- /dev/null +++ b/modules/swagger-codegen-distribution/pom.xml @@ -0,0 +1,80 @@ + + + com.wordnik + swagger-codegen-project + 2.1.2-M1 + ../.. + + 4.0.0 + com.wordnik + swagger-codegen-distribution + jar + swagger-codegen (executable) + 2.1.2-M1 + + src/test/scala + target/classes + target/test-classes + install + target + ${project.artifactId}-${project.version} + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.wordnik.swagger.codegen.Codegen + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.3 + + + package + + shade + + + false + true + + ${java.io.tmpdir}/dependency-reduced-pom.xml + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.3 + + + package + + shade + + + + + + + + + + + + + + com.wordnik + swagger-codegen + ${project.parent.version} + + + \ No newline at end of file diff --git a/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/Readme.java b/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/Readme.java new file mode 100644 index 000000000000..b5ce3c7d2997 --- /dev/null +++ b/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/Readme.java @@ -0,0 +1,7 @@ +package com.wordnik.swagger.codegen; + +public class Readme { + public String getInfo() { + return "See the documentation for swagger-codegen"; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen-distribution/src/main/resources/logback.xml b/modules/swagger-codegen-distribution/src/main/resources/logback.xml new file mode 100644 index 000000000000..4e86443d8d31 --- /dev/null +++ b/modules/swagger-codegen-distribution/src/main/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml new file mode 100644 index 000000000000..a11e0a719d14 --- /dev/null +++ b/modules/swagger-codegen/pom.xml @@ -0,0 +1,341 @@ + + + com.wordnik + swagger-codegen-project + 2.1.2-M1 + ../.. + + 4.0.0 + com.wordnik + swagger-codegen + jar + swagger-codegen (core library) + 2.1.2-M1 + + src/main/java + install + + + org.jvnet.wagon-svn + wagon-svn + 1.8 + + + org.apache.maven.wagon + wagon-ssh-external + 1.0-alpha-6 + + + org.apache.maven.wagon + wagon-webdav + 1.0-beta-1 + + + target + ${project.artifactId}-${project.version} + + + org.codehaus.mojo + exec-maven-plugin + 1.3.2 + + + + java + + + + + com.wordnik.swagger.codegen.Codegen + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + net.alchim31.maven + scala-maven-plugin + + + + add-source + compile + testCompile + + + + + + incremental + + + -Xmx384m + + + -target:jvm-1.6 + -deprecation + + + + run-scalatest + org.scalatest.tools.Runner + + -p + ${project.build.testOutputDirectory} + + + -Xmx512m + + + + + + + maven-compiler-plugin + 3.0 + + 1.6 + 1.6 + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + development + ${project.url} + ${project.version} + com.wordnik + + + + + + org.apache.maven.plugins + maven-site-plugin + 2.1 + + + org.apache.maven.plugins + maven-release-plugin + 2.1 + + + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + org.apache.maven.plugins + maven-gpg-plugin + + release + sign + + + + + + + + release-profile + + true + + + + + net.alchim31.maven + scala-maven-plugin + + + + compile + testCompile + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source + prepare-package + + add-source + + + + src/main/scala + + + + + + + + + + release-sign-artifacts + + + performRelease + true + + + + + + org.apache.maven.plugins + maven-gpg-plugin + + + sign-artifacts + verify + + sign + + + + + + + + + + target/site + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9 + + true + true + + http://java.sun.com/javaee/5/docs/api + http://java.sun.com/j2se/1.5.0/docs/api + + + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 + + true + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + project-team + + + + + + + + + io.swagger + swagger-parser + ${swagger-parser-version} + + + io.swagger + swagger-compat-spec-parser + ${swagger-parser-version} + + + ${project.groupId} + swagger-core + ${swagger-core-version} + + + com.samskivert + jmustache + ${jmustache-version} + + + commons-io + commons-io + ${commons-io-version} + + + org.apache.maven + maven-plugin-tools-api + 2.0 + + + org.apache.felix + maven-bundle-plugin + ${felix-version} + + + org.slf4j + slf4j-ext + ${slf4j-version} + + + org.slf4j + slf4j-api + ${slf4j-version} + + + commons-lang + commons-lang + ${commons-lang-version} + + + commons-cli + commons-cli + ${commons-cli-version} + + + org.scalatest + scalatest_2.11 + ${scala-test-version} + test + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java new file mode 100644 index 000000000000..34d6000e303c --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java @@ -0,0 +1,104 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 com.wordnik.swagger.codegen; + +import com.wordnik.swagger.codegen.ClientOpts; +import com.wordnik.swagger.annotations.*; +import com.wordnik.swagger.models.Swagger; +import com.wordnik.swagger.models.auth.AuthorizationValue; + +import java.util.*; +import java.net.URLEncoder; +import java.net.URLDecoder; + +public class ClientOptInput { + private ClientOpts opts; + private Swagger swagger; + private List auths; + protected CodegenConfig config; + + public ClientOptInput swagger(Swagger swagger) { + this.setSwagger(swagger); + return this; + } + public ClientOptInput opts(ClientOpts opts) { + this.setOpts(opts); + return this; + } + + public void setAuth(String urlEncodedAuthString) { + List auths = new ArrayList(); + if(urlEncodedAuthString != null && !"".equals(urlEncodedAuthString)) { + String[] parts = urlEncodedAuthString.split(","); + for(String part : parts) { + String[] kvPair = part.split(":"); + if(kvPair.length == 2) { + auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header")); + } + } + } + this.auths = auths; + } + public String getAuth() { + if(auths != null) { + StringBuilder b = new StringBuilder(); + for(AuthorizationValue v : auths) { + try { + if(b.toString().length() > 0) + b.append(","); + b.append(URLEncoder.encode(v.getKeyName(), "UTF-8")) + .append(":") + .append(URLEncoder.encode(v.getValue(), "UTF-8")); + } + catch (Exception e) { + // continue + e.printStackTrace(); + } + } + return b.toString(); + } + else + return null; + } + public List getAuthorizationValues() { + return auths; + } + + public CodegenConfig getConfig() { + return config; + } + public void setConfig(CodegenConfig config) { + this.config = config; + } + + public void setOpts(ClientOpts opts) { + this.opts = opts; + } + + public ClientOpts getOpts() { + return opts; + } + + public void setSwagger(Swagger swagger) { + this.swagger = swagger; + } + + @ApiModelProperty(dataType="Object") + public Swagger getSwagger() { + return swagger; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOpts.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOpts.java new file mode 100644 index 000000000000..b8d681cc3078 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/ClientOpts.java @@ -0,0 +1,52 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.codegen.auth.*; + +import java.util.*; + +public class ClientOpts { + protected String uri; + protected String target; + protected AuthMethod auth; + protected Map properties = new HashMap(); + protected String outputDirectory; + + public String getUri() { + return uri; + } + public void setUri(String uri) { + this.uri = uri; + } + + public String getTarget() { + return target; + } + public void setTarget(String target) { + this.target = target; + } + + public Map getProperties() { + return properties; + } + public void setProperties(Map properties) { + this.properties = properties; + } + + public String getOutputDirectory() { + return outputDirectory; + } + public void setOutputDirectory(String outputDirectory) { + this.outputDirectory = outputDirectory; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("ClientOpts: {\n"); + sb.append(" uri: ").append(uri).append(","); + sb.append(" auth: ").append(auth).append(","); + sb.append(properties); + sb.append("}"); + return sb.toString(); + } +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Codegen.java new file mode 100644 index 000000000000..082039fc1f4d --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -0,0 +1,138 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.codegen.languages.*; +import com.wordnik.swagger.models.Swagger; +import com.wordnik.swagger.models.auth.AuthorizationValue; +import com.wordnik.swagger.util.*; + +import io.swagger.parser.SwaggerParser; + +import org.apache.commons.cli.*; + +import java.io.File; +import java.util.*; + +public class Codegen extends DefaultGenerator { + static Map configs = new HashMap(); + static String configString; + static { + List extensions = getExtensions(); + StringBuilder sb = new StringBuilder(); + + for(CodegenConfig config : extensions) { + if(sb.toString().length() != 0) + sb.append(", "); + sb.append(config.getName()); + configs.put(config.getName(), config); + configString = sb.toString(); + } + } + + static String debugInfoOptions = "\nThe following additional debug options are available for all codegen targets:" + + "\n -DdebugSwagger prints the swagger specification as interpreted by the codegen" + + "\n -DdebugModels prints models passed to the template engine" + + "\n -DdebugOperations prints operations passed to the template engine" + + "\n -DdebugSupportingFiles prints additional data passed to the template engine"; + public static void main(String[] args) { + + StringBuilder sb = new StringBuilder(); + + Options options = new Options(); + options.addOption("h", "help", false, "shows this message"); + options.addOption("l", "lang", true, "client language to generate.\nAvailable languages include:\n\t[" + configString + "]"); + options.addOption("o", "output", true, "where to write the generated files"); + options.addOption("i", "input-spec", true, "location of the swagger spec, as URL or file"); + options.addOption("t", "template-dir", true, "folder containing the template files"); + options.addOption("d", "debug-info", false, "prints additional info for debugging"); + options.addOption("a", "auth", true, "adds authorization headers when fetching the swagger definitions remotely. Pass in a URL-encoded string of name:header with a comma separating multiple values"); + + ClientOptInput clientOptInput = new ClientOptInput(); + ClientOpts clientOpts = new ClientOpts(); + Swagger swagger = null; + + CommandLine cmd = null; + try { + CommandLineParser parser = new BasicParser(); + CodegenConfig config = null; + + cmd = parser.parse(options, args); + if (cmd.hasOption("d")) { + usage(options); + System.out.println(debugInfoOptions); + return; + } + if (cmd.hasOption("a")) + clientOptInput.setAuth(cmd.getOptionValue("a")); + if (cmd.hasOption("l")) + clientOptInput.setConfig(getConfig(cmd.getOptionValue("l"))); + else { + usage(options); + return; + } + if (cmd.hasOption("o")) + clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o")); + if (cmd.hasOption("h")) { + if(cmd.hasOption("l")) { + config = getConfig(String.valueOf(cmd.getOptionValue("l"))); + if(config != null) { + options.addOption("h", "help", true, config.getHelp()); + usage(options); + return; + } + } + usage(options); + return; + } + if (cmd.hasOption("i")) + swagger = new SwaggerParser().read(cmd.getOptionValue("i"), clientOptInput.getAuthorizationValues(), true); + if (cmd.hasOption("t")) + clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t"))); + } + catch (Exception e) { + usage(options); + return; + } + try{ + clientOptInput + .opts(clientOpts) + .swagger(swagger); + new Codegen().opts(clientOptInput).generate(); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + public static List getExtensions() { + ServiceLoader loader = ServiceLoader.load(CodegenConfig.class); + List output = new ArrayList(); + Iterator itr = loader.iterator(); + while(itr.hasNext()) { + output.add(itr.next()); + } + return output; + } + + static void usage(Options options) { + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp( "Codegen", options ); + } + + public static CodegenConfig getConfig(String name) { + if(configs.containsKey(name)) { + return configs.get(name); + } + else { + // see if it's a class + try { + System.out.println("loading class " + name); + Class customClass = Class.forName(name); + System.out.println("loaded"); + return (CodegenConfig)customClass.newInstance(); + } + catch (Exception e) { + throw new RuntimeException("can't load class " + name); + } + } + } +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java new file mode 100644 index 000000000000..235a9b5ba6bf --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -0,0 +1,54 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; + +public interface CodegenConfig { + CodegenType getTag(); + String getName(); + String getHelp(); + Map additionalProperties(); + String apiPackage(); + String apiFileFolder(); + String fileSuffix(); + String outputFolder(); + String templateDir(); + String modelFileFolder(); + String modelPackage(); + String toApiName(String name); + String toApiVarName(String name); + String toModelName(String name); + String toParamName(String name); + String escapeReservedWord(String name); + String getTypeDeclaration(Property p); + String getTypeDeclaration(String name); + void processOpts(); + + Set reservedWords(); + + List supportingFiles(); + + void setOutputDir(String dir); + String getOutputDir(); + + CodegenModel fromModel(String name, Model model); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation); + Set defaultIncludes(); + Map typeMapping(); + Map instantiationTypes(); + Map importMapping(); + Map apiTemplateFiles(); + Map modelTemplateFiles(); + void processSwagger(Swagger swagger); + + String toApiFilename(String name); + String toModelFilename(String name); + String toModelImport(String name); + String toApiImport(String name); + void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations); + Map postProcessModels(Map objs); + Map postProcessOperations(Map objs); + Map postProcessSupportingFileData(Map objs); +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java new file mode 100644 index 000000000000..169886da22e3 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -0,0 +1,16 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; + +public class CodegenModel { + public String parent; + public String name, classname, description, classVarName, modelJson; + public String defaultValue; + public List vars = new ArrayList(); + public Set imports = new HashSet(); + public Boolean hasVars, emptyVars, hasMoreModels; + public ExternalDocs externalDocs; +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelFactory.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelFactory.java new file mode 100644 index 000000000000..b369623f37c7 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelFactory.java @@ -0,0 +1,38 @@ +package com.wordnik.swagger.codegen; + +import java.util.HashMap; +import java.util.Map; + +public final class CodegenModelFactory { + + private static final Map> typeMapping = new HashMap>(); + + /** + * Configure a different implementation class. + * @param type the type that shall be replaced + * @param implementation the implementation class must extend the default class and must provide a public no-arg constructor + */ + public static void setTypeMapping(CodegenModelType type, Class implementation) { + if (!type.getDefaultImplementation().isAssignableFrom(implementation)) { + throw new IllegalArgumentException(implementation.getSimpleName() + " doesn't extend " + type.getDefaultImplementation().getSimpleName()); + } + try { + implementation.newInstance(); + } catch (Exception e) { + throw new IllegalArgumentException(e); + } + typeMapping.put(type, implementation); + } + + @SuppressWarnings("unchecked") + public static T newInstance(CodegenModelType type) { + Class classType = typeMapping.get(type); + try { + return (T) (classType != null ? classType : type.getDefaultImplementation()).newInstance(); + } catch (InstantiationException e) { + throw new RuntimeException(e); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelType.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelType.java new file mode 100644 index 000000000000..41c877532f07 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModelType.java @@ -0,0 +1,20 @@ +package com.wordnik.swagger.codegen; + +public enum CodegenModelType { + + MODEL(CodegenModel.class), + OPERATION(CodegenOperation.class), + PARAMETER(CodegenParameter.class), + PROPERTY(CodegenProperty.class), + RESPONSE(CodegenResponse.class); + + private final Class defaultImplementation; + + private CodegenModelType(Class defaultImplementation) { + this.defaultImplementation = defaultImplementation; + } + + public Class getDefaultImplementation() { + return defaultImplementation; + } +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java new file mode 100644 index 000000000000..af192e7e98ad --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java @@ -0,0 +1,30 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.*; + +import java.util.*; + +public class CodegenOperation { + public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive, + returnSimpleType, subresourceOperation, isMapContainer, isListContainer; + public String path, operationId, returnType, httpMethod, returnBaseType, + returnContainer, summary, notes, baseName, defaultResponse; + + public List> consumes, produces; + public CodegenParameter bodyParam; + public List allParams = new ArrayList(); + public List bodyParams = new ArrayList(); + public List pathParams = new ArrayList(); + public List queryParams = new ArrayList(); + public List headerParams = new ArrayList(); + public List formParams = new ArrayList(); + public List tags; + public List responses = new ArrayList(); + public final List responseHeaders = new ArrayList(); + public Set imports = new HashSet(); + public List> examples; + public ExternalDocs externalDocs; + + // legacy support + public String nickname; +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java new file mode 100644 index 000000000000..4480c172c322 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java @@ -0,0 +1,37 @@ +package com.wordnik.swagger.codegen; + +public class CodegenParameter { + public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, + isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam; + public String baseName, paramName, dataType, collectionFormat, description, baseType; + /** + * Determines whether this parameter is mandatory. If the parameter is in "path", + * this property is required and its value MUST be true. Otherwise, the property + * MAY be included and its default value is false. + */ + public Boolean required; + + public CodegenParameter copy() { + CodegenParameter output = new CodegenParameter(); + output.isFile = this.isFile; + output.notFile = this.notFile; + output.hasMore = this.hasMore; + output.isContainer = this.isContainer; + output.secondaryParam = this.secondaryParam; + output.baseName = this.baseName; + output.paramName = this.paramName; + output.dataType = this.dataType; + output.collectionFormat = this.collectionFormat; + output.description = this.description; + output.baseType = this.baseType; + output.isFormParam = this.isFormParam; + output.isQueryParam = this.isQueryParam; + output.isPathParam = this.isPathParam; + output.isHeaderParam = this.isHeaderParam; + output.isCookieParam = this.isCookieParam; + output.isBodyParam = this.isBodyParam; + output.required = this.required; + + return output; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java new file mode 100644 index 000000000000..c5ea8a0da4d3 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java @@ -0,0 +1,24 @@ +package com.wordnik.swagger.codegen; + +import java.util.*; + +public class CodegenProperty { + public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum, + name, min, max, defaultValue, baseType, containerType; + + /** maxLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.1 */ + public Integer maxLength; + /** minLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.2 */ + public Integer minLength; + /** pattern validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.3 */ + public String pattern; + /** A free-form property to include an example of an instance for this schema. */ + public String example; + + public Double minimum, maximum, exclusiveMinimum, exclusiveMaximum; + public Boolean hasMore = null, required = null, secondaryParam = null; + public Boolean isPrimitiveType, isContainer, isNotContainer; + public boolean isEnum; + public List _enum; + public Map allowableValues; +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java new file mode 100644 index 000000000000..92b908759b10 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java @@ -0,0 +1,10 @@ +package com.wordnik.swagger.codegen; + +import java.util.*; + +public class CodegenResponse { + public String code, message; + public Boolean hasMore; + public List> examples; + Object schema; +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenType.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenType.java new file mode 100644 index 000000000000..5a39a23fde13 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenType.java @@ -0,0 +1,34 @@ +package com.wordnik.swagger.codegen; + +import com.fasterxml.jackson.annotation.*; + +import java.util.Map; +import java.util.HashMap; + +public enum CodegenType { + CLIENT, SERVER, DOCUMENTATION, OTHER; + + private static Map names = new HashMap(); + + static { + names.put("client", CLIENT); + names.put("server", SERVER); + names.put("documentation", DOCUMENTATION); + names.put("other", OTHER); + } + + @JsonCreator + public static CodegenType forValue(String value) { + return names.get(value.toLowerCase()); + } + + @JsonValue + public String toValue() { + for (Map.Entry entry : names.entrySet()) { + if (entry.getValue() == this) + return entry.getKey(); + } + + return null; // or fail + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java new file mode 100644 index 000000000000..014a595ae169 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -0,0 +1,910 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.parameters.*; +import com.wordnik.swagger.models.properties.*; +import com.wordnik.swagger.util.Json; + +import org.apache.commons.lang.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.*; +import java.io.File; + +public class DefaultCodegen { + Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); + + protected String outputFolder = ""; + protected Set defaultIncludes = new HashSet(); + protected Map typeMapping = new HashMap(); + protected Map instantiationTypes = new HashMap(); + protected Set reservedWords = new HashSet(); + protected Set languageSpecificPrimitives = new HashSet(); + protected Map importMapping = new HashMap(); + protected String modelPackage = "", apiPackage = "", fileSuffix; + protected Map apiTemplateFiles = new HashMap(); + protected Map modelTemplateFiles = new HashMap(); + protected String templateDir; + protected Map additionalProperties = new HashMap(); + protected List supportingFiles = new ArrayList(); + + public void processOpts(){ + if(additionalProperties.containsKey("templateDir")) { + this.setTemplateDir((String)additionalProperties.get("templateDir")); + } + } + + // override with any special post-processing + public Map postProcessModels(Map objs) { + return objs; + } + + // override with any special post-processing + public Map postProcessOperations(Map objs) { + return objs; + } + + // override with any special post-processing + public Map postProcessSupportingFileData(Map objs) { + return objs; + } + + // override with any special handling of the entire swagger spec + public void processSwagger(Swagger swagger) {} + + // override with any special text escaping logic + public String escapeText(String input) { + if(input != null) { + String output = input.replaceAll("\n", " "); + output = output.replace("\"", "\\\""); + return output; + } + return input; + } + + public Set defaultIncludes() { + return defaultIncludes; + } + public Map typeMapping() { + return typeMapping; + } + public Map instantiationTypes() { + return instantiationTypes; + } + public Set reservedWords() { + return reservedWords; + } + public Set languageSpecificPrimitives() { + return languageSpecificPrimitives; + } + public Map importMapping() { + return importMapping; + } + public String modelPackage() { + return modelPackage; + } + public String apiPackage() { + return apiPackage; + } + public String fileSuffix() { + return fileSuffix; + } + public String templateDir() { + return templateDir; + } + public Map apiTemplateFiles() { + return apiTemplateFiles; + } + public Map modelTemplateFiles() { + return modelTemplateFiles; + } + + public String apiFileFolder() { + return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + public Map additionalProperties() { + return additionalProperties; + } + public List supportingFiles() { + return supportingFiles; + } + public String outputFolder() { + return outputFolder; + } + + public void setOutputDir(String dir) { + this.outputFolder = dir; + } + public String getOutputDir() { + return outputFolder(); + } + + public void setTemplateDir(String templateDir) { + this.templateDir = templateDir; + } + + public String toApiFilename(String name) { + return initialCaps(name) + "Api"; + } + + public String toApiVarName(String name) { + return snakeCase(name); + } + + public String toModelFilename(String name) { + return name; + } + + public String toVarName(String name) { + if(reservedWords.contains(name)) + return escapeReservedWord(name); + else + return name; + } + + public String toParamName(String name) { + if(reservedWords.contains(name)) { + return escapeReservedWord(name); + } + return name; + } + + public String escapeReservedWord(String name) { + throw new RuntimeException("reserved word " + name + " not allowed"); + } + + public String toModelImport(String name) { + if("".equals(modelPackage())) + return name; + else + return modelPackage() + "." + name; + } + + public String toApiImport(String name) { + return apiPackage() + "." + name; + } + + public DefaultCodegen() { + defaultIncludes = new HashSet( + Arrays.asList("double", + "int", + "long", + "short", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Void", + "Integer", + "Long", + "Float") + ); + + typeMapping = new HashMap(); + typeMapping.put("array", "List"); + typeMapping.put("map", "Map"); + typeMapping.put("List", "List"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Integer"); + typeMapping.put("float", "Float"); + typeMapping.put("number", "BigDecimal"); + typeMapping.put("DateTime", "Date"); + typeMapping.put("long", "Long"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "String"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Object"); + typeMapping.put("integer", "Integer"); + + instantiationTypes = new HashMap(); + + reservedWords = new HashSet(); + + importMapping = new HashMap(); + importMapping.put("BigDecimal", "java.math.BigDecimal"); + importMapping.put("UUID", "java.util.UUID"); + importMapping.put("File", "java.io.File"); + importMapping.put("Date", "java.util.Date"); + importMapping.put("Timestamp", "java.sql.Timestamp"); + importMapping.put("Map", "java.util.Map"); + importMapping.put("HashMap", "java.util.HashMap"); + importMapping.put("Array", "java.util.List"); + importMapping.put("ArrayList", "java.util.ArrayList"); + importMapping.put("List", "java.util.*"); + importMapping.put("Set", "java.util.*"); + importMapping.put("DateTime", "org.joda.time.*"); + importMapping.put("LocalDateTime", "org.joda.time.*"); + importMapping.put("LocalDate", "org.joda.time.*"); + importMapping.put("LocalTime", "org.joda.time.*"); + } + + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map") + ""; + } + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array") + "<" + inner + ">"; + } + else + return null; + } + + public String toDefaultValue(Property p) { + if(p instanceof StringProperty) + return "null"; + else if (p instanceof BooleanProperty) + return "null"; + else if(p instanceof DateProperty) + return "null"; + else if(p instanceof DateTimeProperty) + return "null"; + else if (p instanceof DoubleProperty) + return "null"; + else if (p instanceof FloatProperty) + return "null"; + else if (p instanceof IntegerProperty) + return "null"; + else if (p instanceof LongProperty) + return "null"; + else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new HashMap() "; + } + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "new ArrayList<" + inner + ">() "; + } + else + return "null"; + } + + /** + * returns the swagger type for the property + **/ + public String getSwaggerType(Property p) { + String datatype = null; + if(p instanceof StringProperty) + datatype = "string"; + else if (p instanceof BooleanProperty) + datatype = "boolean"; + else if(p instanceof DateProperty) + datatype = "date"; + else if(p instanceof DateTimeProperty) + datatype = "DateTime"; + else if (p instanceof DoubleProperty) + datatype = "double"; + else if (p instanceof FloatProperty) + datatype = "float"; + else if (p instanceof IntegerProperty) + datatype = "integer"; + else if (p instanceof LongProperty) + datatype = "long"; + else if (p instanceof MapProperty) + datatype = "map"; + else if (p instanceof DecimalProperty) + datatype = "number"; + else if (p instanceof RefProperty) { + RefProperty r = (RefProperty)p; + datatype = r.get$ref(); + if(datatype.indexOf("#/definitions/") == 0) + datatype = datatype.substring("#/definitions/".length()); + } + else { + if(p != null) datatype = p.getType(); + } + return datatype; + } + + public String snakeCase(String name) { + return Character.toLowerCase(name.charAt(0)) + name.substring(1); + } + + public String initialCaps(String name) { + return Character.toUpperCase(name.charAt(0)) + name.substring(1); + } + + public String getTypeDeclaration(String name) { + return name; + } + + public String getTypeDeclaration(Property p) { + String swaggerType = getSwaggerType(p); + if(typeMapping.containsKey(swaggerType)) + return typeMapping.get(swaggerType); + return swaggerType; + } + + public String toApiName(String name) { + if(name.length() == 0) + return "DefaultApi"; + return initialCaps(name) + "Api"; + } + + public String toModelName(String name) { + return initialCaps(name); + } + + public CodegenModel fromModel(String name, Model model) { + CodegenModel m = CodegenModelFactory.newInstance(CodegenModelType.MODEL); + if(reservedWords.contains(name)) + m.name = escapeReservedWord(name); + else + m.name = name; + m.description = model.getDescription(); + m.classname = toModelName(name); + m.classVarName = toVarName(name); + m.modelJson = Json.pretty(model); + m.externalDocs = model.getExternalDocs(); + int count = 0; + if(model instanceof ArrayModel) { + ArrayModel am = (ArrayModel) model; + ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); + CodegenProperty cp = fromProperty(name, arrayProperty); + if(cp.complexType != null && !defaultIncludes.contains(cp.complexType)) + m.imports.add(cp.complexType); + m.parent = toInstantiationType(arrayProperty); + String containerType = cp.containerType; + if(instantiationTypes.containsKey(containerType)) + m.imports.add(instantiationTypes.get(containerType)); + if(typeMapping.containsKey(containerType)) { + containerType = typeMapping.get(containerType); + cp.containerType = containerType; + m.imports.add(containerType); + } + } + else if (model instanceof RefModel) { + // TODO + } + else { + ModelImpl impl = (ModelImpl) model; + if(impl.getAdditionalProperties() != null) { + MapProperty mapProperty = new MapProperty(impl.getAdditionalProperties()); + CodegenProperty cp = fromProperty(name, mapProperty); + if(cp.complexType != null && !defaultIncludes.contains(cp.complexType)) + m.imports.add(cp.complexType); + m.parent = toInstantiationType(mapProperty); + String containerType = cp.containerType; + if(instantiationTypes.containsKey(containerType)) + m.imports.add(instantiationTypes.get(containerType)); + if(typeMapping.containsKey(containerType)) { + containerType = typeMapping.get(containerType); + cp.containerType = containerType; + m.imports.add(containerType); + } + } + if(impl.getProperties() != null && impl.getProperties().size() > 0) { + m.hasVars = true; + for(String key: impl.getProperties().keySet()) { + Property prop = impl.getProperties().get(key); + + if(prop == null) { + LOGGER.warn("null property for " + key); + } + else { + CodegenProperty cp = fromProperty(key, prop); + cp.required = false; + if(impl.getRequired() != null) { + for(String req : impl.getRequired()) { + if(key.equals(req)) + cp.required = true; + } + } + if(cp.complexType != null && !defaultIncludes.contains(cp.complexType)) { + m.imports.add(cp.complexType); + } + m.vars.add(cp); + count += 1; + if(count != impl.getProperties().keySet().size()) + cp.hasMore = new Boolean(true); + if(cp.isContainer != null) { + String arrayImport = typeMapping.get("array"); + if(arrayImport != null && + !languageSpecificPrimitives.contains(arrayImport) && + !defaultIncludes.contains(arrayImport)) + m.imports.add(arrayImport); + } + + if(cp.complexType != null && + !languageSpecificPrimitives.contains(cp.complexType) && + !defaultIncludes.contains(cp.complexType)) + m.imports.add(cp.complexType); + + if(cp.baseType != null && + !languageSpecificPrimitives.contains(cp.baseType) && + !defaultIncludes.contains(cp.baseType)) + m.imports.add(cp.baseType); + } + } + } + else { + m.emptyVars = true; + } + } + return m; + } + + public CodegenProperty fromProperty(String name, Property p) { + if(p == null) { + LOGGER.error("unexpected missing property for name " + null); + return null; + } + CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); + + property.name = toVarName(name); + property.baseName = name; + property.description = escapeText(p.getDescription()); + property.getter = "get" + initialCaps(name); + property.setter = "set" + initialCaps(name); + property.example = p.getExample(); + property.defaultValue = toDefaultValue(p); + + String type = getSwaggerType(p); + + if(p instanceof AbstractNumericProperty) { + AbstractNumericProperty np = (AbstractNumericProperty) p; + property.minimum = np.getMinimum(); + property.maximum = np.getMaximum(); + property.exclusiveMinimum = np.getExclusiveMinimum(); + property.exclusiveMaximum = np.getExclusiveMaximum(); + + // legacy support + Map allowableValues = new HashMap(); + if(np.getMinimum() != null) + allowableValues.put("min", np.getMinimum()); + if(np.getMaximum() != null) + allowableValues.put("max", np.getMaximum()); + property.allowableValues = allowableValues; + } + + if(p instanceof StringProperty) { + StringProperty sp = (StringProperty) p; + property.maxLength = sp.getMaxLength(); + property.minLength = sp.getMinLength(); + property.pattern = sp.getPattern(); + if(sp.getEnum() != null) { + List _enum = sp.getEnum(); + property._enum = _enum; + property.isEnum = true; + + // legacy support + Map allowableValues = new HashMap(); + allowableValues.put("values", _enum); + property.allowableValues = allowableValues; + } + } + + property.datatype = getTypeDeclaration(p); + + // this can cause issues for clients which don't support enums + if(property.isEnum) + property.datatypeWithEnum = StringUtils.capitalize(property.name) + "Enum"; + else + property.datatypeWithEnum = property.datatype; + + property.baseType = getSwaggerType(p); + + if(p instanceof ArrayProperty) { + property.isContainer = true; + property.containerType = "array"; + ArrayProperty ap = (ArrayProperty) p; + CodegenProperty cp = fromProperty("inner", ap.getItems()); + if(cp == null) { + LOGGER.warn("skipping invalid property " + Json.pretty(p)); + } + else { + property.baseType = getSwaggerType(p); + if(!languageSpecificPrimitives.contains(cp.baseType)) + property.complexType = cp.baseType; + else + property.isPrimitiveType = true; + } + } + else if(p instanceof MapProperty) { + property.isContainer = true; + property.containerType = "map"; + MapProperty ap = (MapProperty) p; + CodegenProperty cp = fromProperty("inner", ap.getAdditionalProperties()); + + property.baseType = getSwaggerType(p); + if(!languageSpecificPrimitives.contains(cp.baseType)) + property.complexType = cp.baseType; + else + property.isPrimitiveType = true; + } + else { + property.isNotContainer = true; + if(languageSpecificPrimitives().contains(type)) + property.isPrimitiveType = true; + else + property.complexType = property.baseType; + } + return property; + } + + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation){ + CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); + Set imports = new HashSet(); + + String operationId = operation.getOperationId(); + if(operationId == null) { + String tmpPath = path; + tmpPath = tmpPath.replaceAll("\\{", ""); + tmpPath = tmpPath.replaceAll("\\}", ""); + String[] parts = (tmpPath + "/" + httpMethod).split("/"); + StringBuilder builder = new StringBuilder(); + if("/".equals(tmpPath)) { + // must be root tmpPath + builder.append("root"); + } + for(int i = 0; i < parts.length; i++) { + String part = parts[i]; + if(part.length() > 0) { + if(builder.toString().length() == 0) + part = Character.toLowerCase(part.charAt(0)) + part.substring(1); + else + part = initialCaps(part); + builder.append(part); + } + } + operationId = builder.toString(); + LOGGER.warn("generated operationId " + operationId); + } + op.path = path; + op.operationId = operationId; + op.summary = escapeText(operation.getSummary()); + op.notes = escapeText(operation.getDescription()); + op.tags = operation.getTags(); + + Response methodResponse = null; + + if(operation.getConsumes() != null && operation.getConsumes().size() > 0) { + List> c = new ArrayList>(); + int count = 0; + for(String key: operation.getConsumes()) { + Map mediaType = new HashMap(); + mediaType.put("mediaType", key); + count += 1; + if (count < operation.getConsumes().size()) + mediaType.put("hasMore", "true"); + c.add(mediaType); + } + op.consumes = c; + op.hasConsumes = true; + } + + if(operation.getProduces() != null && operation.getProduces().size() > 0) { + List> c = new ArrayList>(); + int count = 0; + for(String key: operation.getProduces()) { + Map mediaType = new HashMap(); + mediaType.put("mediaType", key); + count += 1; + if (count < operation.getProduces().size()) + mediaType.put("hasMore", "true"); + c.add(mediaType); + } + op.produces = c; + op.hasProduces = true; + } + + if(operation.getResponses() != null) { + for(String responseCode: new TreeSet(operation.getResponses().keySet())) { + Response response = operation.getResponses().get(responseCode); + if (responseCode.startsWith("2")) { + // use the first, i.e. the smallest 2xx response status as methodResponse + methodResponse = response; + break; + } + } + if(methodResponse == null && operation.getResponses().keySet().contains("default")) { + methodResponse = operation.getResponses().get("default"); + } + for(String responseCode: operation.getResponses().keySet()) { + Response response = operation.getResponses().get(responseCode); + if(response != methodResponse) { + CodegenResponse r = fromResponse(responseCode, response); + op.responses.add(r); + } + for(int i = 0; i < op.responses.size() - 1; i++) { + CodegenResponse r = op.responses.get(i); + r.hasMore = new Boolean(true); + } + } + } + + if(methodResponse != null) { + if (methodResponse.getSchema() != null) { + CodegenProperty cm = fromProperty("response", methodResponse.getSchema()); + + Property responseProperty = methodResponse.getSchema(); + + if(responseProperty instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) responseProperty; + CodegenProperty innerProperty = fromProperty("response", ap.getItems()); + op.returnBaseType = innerProperty.baseType; + } + else { + if(cm.complexType != null) + op.returnBaseType = cm.complexType; + else + op.returnBaseType = cm.baseType; + } + op.examples = toExamples(methodResponse.getExamples()); + op.defaultResponse = toDefaultValue(responseProperty); + op.returnType = cm.datatype; + if(cm.isContainer != null) { + op.returnContainer = cm.containerType; + if("map".equals(cm.containerType)) + op.isMapContainer = Boolean.TRUE; + else if ("list".equalsIgnoreCase(cm.containerType)) + op.isListContainer = Boolean.TRUE; + } + else + op.returnSimpleType = true; + if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null) + op.returnTypeIsPrimitive = true; + } + addHeaders(methodResponse, op.responseHeaders); + } + + if(op.returnBaseType == null) { + op.returnTypeIsPrimitive = true; + op.returnSimpleType = true; + } + + if(op.returnBaseType != null && + !defaultIncludes.contains(op.returnBaseType) && + !languageSpecificPrimitives.contains(op.returnBaseType)) + imports.add(op.returnBaseType); + + List parameters = operation.getParameters(); + CodegenParameter bodyParam = null; + List allParams = new ArrayList(); + List bodyParams = new ArrayList(); + List pathParams = new ArrayList(); + List queryParams = new ArrayList(); + List headerParams = new ArrayList(); + List cookieParams = new ArrayList(); + List formParams = new ArrayList(); + + if(parameters != null) { + for(Parameter param : parameters) { + CodegenParameter p = fromParameter(param, imports); + allParams.add(p); + if(param instanceof QueryParameter) { + p.isQueryParam = new Boolean(true); + queryParams.add(p.copy()); + } + else if(param instanceof PathParameter) { + p.required = true; + p.isPathParam = new Boolean(true); + pathParams.add(p.copy()); + } + else if(param instanceof HeaderParameter) { + p.isHeaderParam = new Boolean(true); + headerParams.add(p.copy()); + } + else if(param instanceof CookieParameter) { + p.isCookieParam = new Boolean(true); + cookieParams.add(p.copy()); + } + else if(param instanceof BodyParameter) { + p.isBodyParam = new Boolean(true); + bodyParam = p; + bodyParams.add(p.copy()); + } + else if(param instanceof FormParameter) { + if("file".equalsIgnoreCase(((FormParameter)param).getType())) + p.isFile = true; + else + p.notFile = true; + p.isFormParam = new Boolean(true); + formParams.add(p.copy()); + } + } + } + for(String i: imports) { + if(!defaultIncludes.contains(i) && !languageSpecificPrimitives.contains(i)){ + op.imports.add(i); + } + } + op.bodyParam = bodyParam; + op.httpMethod = httpMethod.toUpperCase(); + op.allParams = addHasMore(allParams); + op.bodyParams = addHasMore(bodyParams); + op.pathParams = addHasMore(pathParams); + op.queryParams = addHasMore(queryParams); + op.headerParams = addHasMore(headerParams); + // op.cookieParams = cookieParams; + op.formParams = addHasMore(formParams); + // legacy support + op.nickname = operationId; + + if(op.allParams.size() > 0) + op.hasParams = true; + op.externalDocs = operation.getExternalDocs(); + + return op; + } + + public CodegenResponse fromResponse(String responseCode, Response response) { + CodegenResponse r = CodegenModelFactory.newInstance(CodegenModelType.RESPONSE); + if("default".equals(responseCode)) + r.code = "0"; + else + r.code = responseCode; + r.message = response.getDescription(); + r.schema = response.getSchema(); + r.examples = toExamples(response.getExamples()); + return r; + } + + public CodegenParameter fromParameter(Parameter param, Set imports) { + CodegenParameter p = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); + p.baseName = param.getName(); + p.description = param.getDescription(); + p.required = param.getRequired(); + + if(param instanceof SerializableParameter) { + SerializableParameter qp = (SerializableParameter) param; + Property property = null; + String collectionFormat = null; + if("array".equals(qp.getType())) { + Property inner = qp.getItems(); + if(inner == null) { + LOGGER.warn("warning! No inner type supplied for array parameter \"" + qp.getName() + "\", using String"); + inner = new StringProperty().description("//TODO automatically added by swagger-codegen"); + } + property = new ArrayProperty(inner); + collectionFormat = qp.getCollectionFormat(); + CodegenProperty pr = fromProperty("inner", inner); + p.baseType = pr.datatype; + imports.add(pr.baseType); + } + else + property = PropertyBuilder.build(qp.getType(), qp.getFormat(), null); + if(property == null) { + LOGGER.warn("warning! Property type \"" + qp.getType() + "\" not found for parameter \"" + param.getName() + "\", using String"); + property = new StringProperty().description("//TODO automatically added by swagger-codegen. Type was " + qp.getType() + " but not supported"); + } + CodegenProperty model = fromProperty(qp.getName(), property); + p.collectionFormat = collectionFormat; + p.dataType = model.datatype; + p.paramName = toParamName(qp.getName()); + + if(model.complexType != null) { + imports.add(model.complexType); + } + } + else { + BodyParameter bp = (BodyParameter) param; + Model model = bp.getSchema(); + + if(model instanceof ModelImpl) { + ModelImpl impl = (ModelImpl) model; + CodegenModel cm = fromModel(bp.getName(), impl); + if(cm.emptyVars != null && cm.emptyVars == false) { + p.dataType = getTypeDeclaration(cm.classname); + imports.add(p.dataType); + } + else { + // TODO: missing format, so this will not always work + Property prop = PropertyBuilder.build(impl.getType(), null, null); + CodegenProperty cp = fromProperty("property", prop); + if(cp != null) { + p.dataType = cp.datatype; + } + } + } + else if(model instanceof ArrayModel) { + // to use the built-in model parsing, we unwrap the ArrayModel + // and get a single property from it + ArrayModel impl = (ArrayModel) model; + CodegenModel cm = fromModel(bp.getName(), impl); + // get the single property + ArrayProperty ap = new ArrayProperty().items(impl.getItems()); + CodegenProperty cp = fromProperty("inner", ap); + if(cp.complexType != null) { + imports.add(cp.complexType); + } + imports.add(cp.baseType); + p.dataType = cp.datatype; + p.isContainer = true; + } + else{ + Model sub = bp.getSchema(); + if(sub instanceof RefModel) { + String name = ((RefModel)sub).getSimpleRef(); + if(typeMapping.containsKey(name)) + name = typeMapping.get(name); + else { + name = toModelName(name); + if(defaultIncludes.contains(name)) { + imports.add(name); + } + imports.add(name); + name = getTypeDeclaration(name); + } + p.dataType = name; + } + } + p.paramName = toParamName(bp.getName()); + } + return p; + } + + protected List> toExamples(Map examples) { + if(examples == null) + return null; + + List> output = new ArrayList>(); + for(String key: examples.keySet()) { + String value = examples.get(key); + + Map kv = new HashMap(); + kv.put("contentType", key); + kv.put("example", value); + output.add(kv); + } + return output; + } + + private void addHeaders(Response response, List target) { + if (response.getHeaders() != null) { + for (Map.Entry headers : response.getHeaders().entrySet()) { + target.add(fromProperty(headers.getKey(), headers.getValue())); + } + } + } + + private List addHasMore(List objs) { + if(objs != null) { + for(int i = 0; i < objs.size(); i++) { + if(i > 0) + objs.get(i).secondaryParam = new Boolean(true); + if(i < objs.size() - 1) + objs.get(i).hasMore = new Boolean(true); + } + } + return objs; + } + + private Map addHasMore(Map objs) { + if(objs != null) { + for(int i = 0; i < objs.size() - 1; i++) { + if(i > 0) + objs.put("secondaryParam", new Boolean(true)); + if(i < objs.size() - 1) + objs.put("hasMore", true); + } + } + return objs; + } + + + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + List opList = operations.get(tag); + if(opList == null) { + opList = new ArrayList(); + operations.put(tag, opList); + } + opList.add(co); + co.baseName = tag; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java new file mode 100644 index 000000000000..65355d75b1f6 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -0,0 +1,382 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.*; +import com.wordnik.swagger.util.*; +import com.samskivert.mustache.*; + +import org.apache.commons.io.FileUtils; + +import java.util.*; +import java.util.regex.*; +import java.io.*; + +public class DefaultGenerator implements Generator { + protected CodegenConfig config; + protected ClientOptInput opts = null; + protected Swagger swagger = null; + + public Generator opts(ClientOptInput opts) { + this.opts = opts; + + this.swagger = opts.getSwagger(); + ClientOpts clientOpts = opts.getOpts(); + this.config = opts.getConfig(); + this.config.additionalProperties().putAll(clientOpts.getProperties()); + + return this; + } + + public List generate() { + if(swagger == null || config == null) { + throw new RuntimeException("missing swagger input or config!"); + } + if(System.getProperty("debugSwagger") != null) { + Json.prettyPrint(swagger); + } + List files = new ArrayList(); + try { + config.processOpts(); + if(swagger.getInfo() != null) { + Info info = swagger.getInfo(); + if(info.getTitle() != null) + config.additionalProperties().put("appName", info.getTitle()); + if(info.getDescription() != null) + config.additionalProperties().put("appDescription", info.getDescription()); + if(info.getContact() != null) { + Contact contact = info.getContact(); + config.additionalProperties().put("infoUrl", contact.getUrl()); + if(contact.getEmail() != null) + config.additionalProperties().put("infoEmail", contact.getEmail()); + } + if(info.getLicense() != null) { + License license = info.getLicense(); + if(license.getName() != null) + config.additionalProperties().put("licenseInfo", license.getName()); + if(license.getUrl() != null) + config.additionalProperties().put("licenseUrl", license.getUrl()); + } + } + + StringBuilder hostBuilder = new StringBuilder(); + if(swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { + hostBuilder.append(swagger.getSchemes().get(0).toValue()); + hostBuilder.append("://"); + } + else + hostBuilder.append("https://"); + hostBuilder.append(swagger.getHost()).append(swagger.getBasePath()); + String basePath = hostBuilder.toString(); + + List allOperations = new ArrayList(); + List allModels = new ArrayList(); + + // models + Map definitions = swagger.getDefinitions(); + if(definitions != null) { + for(String name: definitions.keySet()) { + Model model = definitions.get(name); + Map modelMap = new HashMap(); + modelMap.put(name, model); + Map models = processModels(config, modelMap); + models.putAll(config.additionalProperties()); + + allModels.add(((List)models.get("models")).get(0)); + + for(String templateName : config.modelTemplateFiles().keySet()) { + String suffix = config.modelTemplateFiles().get(templateName); + String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix; + String template = readTemplate(config.templateDir() + File.separator + templateName); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + public Reader getTemplate (String name) { + return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + }; + }) + .defaultValue("") + .compile(template); + writeToFile(filename, tmpl.execute(models)); + files.add(new File(filename)); + } + } + } + if(System.getProperty("debugModels") != null) { + System.out.println("############ Model info ############"); + Json.prettyPrint(allModels); + } + + // apis + Map> paths = processPaths(swagger.getPaths()); + for(String tag : paths.keySet()) { + List ops = paths.get(tag); + Map operation = processOperations(config, tag, ops); + operation.put("basePath", basePath); + operation.put("baseName", tag); + operation.put("modelPackage", config.modelPackage()); + operation.putAll(config.additionalProperties()); + operation.put("classname", config.toApiName(tag)); + operation.put("classVarName", config.toApiVarName(tag)); + allOperations.add(operation); + for(String templateName : config.apiTemplateFiles().keySet()) { + String suffix = config.apiTemplateFiles().get(templateName); + String filename = config.apiFileFolder() + + File.separator + + config.toApiFilename(tag) + + suffix; + + String template = readTemplate(config.templateDir() + File.separator + templateName); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + public Reader getTemplate (String name) { + return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + }; + }) + .defaultValue("") + .compile(template); + + writeToFile(filename, tmpl.execute(operation)); + files.add(new File(filename)); + } + } + if(System.getProperty("debugOperations") != null) { + System.out.println("############ Operation info ############"); + Json.prettyPrint(allOperations); + } + + // supporting files + Map bundle = new HashMap(); + bundle.putAll(config.additionalProperties()); + bundle.put("apiPackage", config.apiPackage()); + + Map apis = new HashMap(); + apis.put("apis", allOperations); + if(swagger.getBasePath() != null) { + bundle.put("basePath", swagger.getBasePath()); + } + bundle.put("apiInfo", apis); + bundle.put("models", allModels); + bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar)); + bundle.put("modelPackage", config.modelPackage()); + if (swagger.getExternalDocs() != null) { + bundle.put("externalDocs", swagger.getExternalDocs()); + } + for(int i = 0; i < allModels.size() - 1; i++) { + HashMap cm = (HashMap) allModels.get(i); + CodegenModel m = cm.get("model"); + m.hasMoreModels = true; + } + + config.postProcessSupportingFileData(bundle); + + if(System.getProperty("debugSupportingFiles") != null) { + System.out.println("############ Supporting file info ############"); + Json.prettyPrint(bundle); + } + + for(SupportingFile support : config.supportingFiles()) { + String outputFolder = config.outputFolder(); + if(support.folder != null && !"".equals(support.folder)) + outputFolder += File.separator + support.folder; + File of = new File(outputFolder); + if(!of.isDirectory()) + of.mkdirs(); + String outputFilename = outputFolder + File.separator + support.destinationFilename; + + if(support.templateFile.endsWith("mustache")) { + String template = readTemplate(config.templateDir() + File.separator + support.templateFile); + Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + public Reader getTemplate (String name) { + return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + }; + }) + .defaultValue("") + .compile(template); + + writeToFile(outputFilename, tmpl.execute(bundle)); + files.add(new File(outputFilename)); + } + else { + String template = readTemplate(config.templateDir() + File.separator + support.templateFile); + FileUtils.writeStringToFile(new File(outputFilename), template); + System.out.println("copying file to " + outputFilename); + files.add(new File(outputFilename)); + } + } + + config.processSwagger(swagger); + } + catch (Exception e) { + e.printStackTrace(); + } + return files; + } + + public Map> processPaths(Map paths) { + Map> ops = new HashMap>(); + List tags = null; + + for(String resourcePath : paths.keySet()) { + Path path = paths.get(resourcePath); + processOperation(resourcePath, "get", path.getGet(), ops); + processOperation(resourcePath, "put", path.getPut(), ops); + processOperation(resourcePath, "post", path.getPost(), ops); + processOperation(resourcePath, "delete", path.getDelete(), ops); + processOperation(resourcePath, "patch", path.getPatch(), ops); + processOperation(resourcePath, "options", path.getOptions(), ops); + } + return ops; + } + + public void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations) { + if(operation != null) { + List tags = operation.getTags(); + if(tags == null) { + tags = new ArrayList(); + tags.add("default"); + } + + for(String tag : tags) { + CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation); + co.tags = new ArrayList(); + co.tags.add(sanitizeTag(tag)); + + config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); + } + } + } + + protected String sanitizeTag(String tag) { + // remove spaces and make strong case + String [] parts = tag.split(" "); + StringBuffer buf = new StringBuffer(); + for(String part: parts) { + if(!"".equals(part)) { + buf.append(Character.toUpperCase(part.charAt(0))); + if(part.length() > 1) + buf.append(part.substring(1)); + } + } + return buf.toString().replaceAll("[^a-zA-Z ]", ""); + } + + public File writeToFile(String filename, String contents) throws IOException { + System.out.println("writing file " + filename); + File output = new File(filename); + + if(output.getParent() != null && !new File(output.getParent()).exists()) { + File parent = new File(output.getParent()); + parent.mkdirs(); + } + Writer out = new BufferedWriter(new OutputStreamWriter( + new FileOutputStream(output), "UTF-8")); + + out.write(contents); + out.close(); + return output; + } + + public String readTemplate(String name) { + try{ + Reader reader = getTemplateReader(name); + if(reader == null) + throw new RuntimeException("no file found"); + java.util.Scanner s = new java.util.Scanner(reader).useDelimiter("\\A"); + return s.hasNext() ? s.next() : ""; + } + catch(Exception e) { + e.printStackTrace(); + } + throw new RuntimeException("can't load template " + name); + } + + public Reader getTemplateReader(String name) { + try{ + InputStream is = this.getClass().getClassLoader().getResourceAsStream(getCPResourcePath(name)); + if(is == null) + is = new FileInputStream(new File(name)); + if(is == null) + throw new RuntimeException("no file found"); + return new InputStreamReader(is); + } + catch(Exception e) { + e.printStackTrace(); + } + throw new RuntimeException("can't load template " + name); + } + + private String getCPResourcePath(String name) { + if (!"/".equals(File.separator)) + return name.replaceAll(Pattern.quote(File.separator), "/"); + return name; + } + +public Map processOperations(CodegenConfig config, String tag, List ops) { + Map operations = new HashMap(); + Map objs = new HashMap(); + objs.put("classname", config.toApiName(tag)); + objs.put("operation", ops); + operations.put("operations", objs); + operations.put("package", config.apiPackage()); + + Set allImports = new LinkedHashSet(); + for(CodegenOperation op: ops) { + allImports.addAll(op.imports); + } + + List> imports = new ArrayList>(); + for(String i: allImports) { + Map im = new LinkedHashMap(); + String m = config.importMapping().get(i); + if(m == null) + m = config.toModelImport(i); + if(m != null) { + im.put("import", m); + imports.add(im); + } + } + + operations.put("imports", imports); + config.postProcessOperations(operations); + return operations; + } + + public Map processModels(CodegenConfig config, Map definitions) { + Map objs = new HashMap(); + objs.put("package", config.modelPackage()); + List models = new ArrayList(); + List model = new ArrayList(); + Set allImports = new LinkedHashSet(); + for(String key: definitions.keySet()) { + Model mm = definitions.get(key); + CodegenModel cm = config.fromModel(key, mm); + Map mo = new HashMap(); + mo.put("model", cm); + models.add(mo); + allImports.addAll(cm.imports); + } + objs.put("models", models); + + List> imports = new ArrayList>(); + for(String i: allImports) { + Map im = new LinkedHashMap(); + String m = config.importMapping().get(i); + if(m == null) + m = config.toModelImport(i); + if(m != null && !config.defaultIncludes().contains(m)) { + im.put("import", m); + imports.add(im); + } + // add instantiation types + m = config.instantiationTypes().get(i); + if(m != null && !config.defaultIncludes().contains(m)) { + im.put("import", m); + imports.add(im); + } + } + + objs.put("imports", imports); + config.postProcessModels(objs); + + return objs; + } +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Generator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Generator.java new file mode 100644 index 000000000000..0dfbab86a0ae --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/Generator.java @@ -0,0 +1,11 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.Swagger; + +import java.io.File; +import java.util.List; + +public interface Generator { + Generator opts(ClientOptInput opts); + List generate(); +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/SupportingFile.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/SupportingFile.java new file mode 100644 index 000000000000..85f08bfa70c3 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/SupportingFile.java @@ -0,0 +1,13 @@ +package com.wordnik.swagger.codegen; + +public class SupportingFile { + public String templateFile; + public String folder; + public String destinationFilename; + + public SupportingFile(String templateFile, String folder, String destinationFilename) { + this.templateFile = templateFile; + this.folder = folder; + this.destinationFilename = destinationFilename; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/auth/AuthMethod.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/auth/AuthMethod.java new file mode 100644 index 000000000000..7de102ec3501 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/auth/AuthMethod.java @@ -0,0 +1,6 @@ +package com.wordnik.swagger.codegen.auth; + +public interface AuthMethod { + String getType(); + void setType(String type); +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/haproxy.cfg b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/haproxy.cfg new file mode 100644 index 000000000000..9fd8d61f2ce1 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/haproxy.cfg @@ -0,0 +1,86 @@ +#--------------------------------------------------------------------- +# Global settings +#--------------------------------------------------------------------- +global + log 127.0.0.1 local2 + chroot /var/lib/haproxy + pidfile /var/run/haproxy.pid + maxconn 4000 + user haproxy + group haproxy + daemon + +#--------------------------------------------------------------------- +# common defaults that all the 'listen' and 'backend' sections will +# use if not designated in their block +#--------------------------------------------------------------------- +defaults + mode http + log global + option dontlognull + option httpclose + option httplog + option forwardfor + option redispatch + timeout connect 10000 # default 10 second time out if a backend is not found + timeout client 300000 + timeout server 300000 + maxconn 60000 + retries 3 + +#--------------------------------------------------------------------- +# main frontend which proxys to the backends +#--------------------------------------------------------------------- +frontend main *:80 + default_backend app + + acl is_swagger_online hdr_beg(host) -i online.swagger.io + acl is_swagger_io hdr_beg(host) -i swagger.io + acl is_old hdr_beg(host) -i swagger.wordnik.com + acl is_old_editor hdr_beg(host) -i editor.swagger.wordnik.com + acl is_validator_swagger path_beg /swagger.json + + # online spec validator + reqrep ([^\ ]*)\ /validator/(.*) \1\ /validator/validator/\2 if is_swagger_online + + # something that didn't work + reqrep ([^\ ]*)\ /swagger.json(.*) \1\ /validator/swagger.json if is_validator_swagger + + # swagger schema + reqrep ^([^\ :]*)\ /v2/schema.json(.*) \1\ /swagger-api/swagger-spec/master/schemas/v2.0/schema.json\2 + acl is_swagger_spec path_beg /swagger-api/swagger-spec + + # swagger docs + reqrep ^([^\ :]*)\ /swagger-core/documentation/annotations/apidocs/current(.*) \1\ /swagger-core/apidocs/\2 + acl is_swagger_docs path_beg /swagger-core/apidocs + + use_backend github_swagger_io if is_swagger_docs + use_backend validator if is_swagger_online + use_backend validator if is_validator_swagger + use_backend github_swagger_io if is_swagger_io !is_swagger_spec + use_backend github_swagger_spec if is_swagger_spec + + redirect location http://editor.swagger.io if is_old_editor + redirect location http://swagger.io if is_old + +#--------------------------------------------------------------------- +# round robin balancing between the various backends +#--------------------------------------------------------------------- +backend github_swagger_io + balance roundrobin + server gh1 swagger-api.github.io:80 check + +backend github_swagger_spec + http-request set-header Host raw.githubusercontent.com + rspirep ^Content-type:(.*) Content-Type:\ application/json + rspirep ^Access-Control-Allow-Origin:(.*) Access-Control-Allow-Origin:* + balance roundrobin + server gh2 raw.githubusercontent.com:443 check ssl verify none + +backend validator + balance roundrobin + server app1 127.0.0.1:8000 check + +backend app + balance roundrobin + server app1 127.0.0.1:8000 check diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java new file mode 100644 index 000000000000..915ff34c7f19 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java @@ -0,0 +1,110 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/java"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "android"; + } + + public String getHelp() { + return "Generates an Android client library."; + } + + public AndroidClientCodegen() { + super(); + outputFolder = "generated-code/android"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "android-java"; + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.model"; + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java")); + supportingFiles.add(new SupportingFile("httpPatch.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "HttpPatch.java")); + supportingFiles.add(new SupportingFile("jsonUtil.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object") + ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return toModelName(type); + } + else + type = swaggerType; + return toModelName(type); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AsyncScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AsyncScalaClientCodegen.java new file mode 100644 index 000000000000..19b9e0f2c76c --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AsyncScalaClientCodegen.java @@ -0,0 +1,194 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + protected String clientName = "SwaggerClient"; + protected String authScheme = ""; + protected boolean authPreemptive = false; + protected boolean asyncHttpClient = !authScheme.isEmpty(); + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "async-scala"; + } + + public String getHelp() { + return "Generates an Asynchronous Scala client library."; + } + + public AsyncScalaClientCodegen() { + super(); + outputFolder = "generated-code/async-scala"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "asyncscala"; + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.model"; + + reservedWords = new HashSet ( + Arrays.asList( + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("asyncHttpClient", asyncHttpClient); + additionalProperties.put("authScheme", authScheme); + additionalProperties.put("authPreemptive", authPreemptive); + additionalProperties.put("clientName", clientName); + + supportingFiles.add(new SupportingFile("sbt.mustache", "", "build.sbt")); + supportingFiles.add(new SupportingFile("client.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), clientName + ".scala")); + + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + importMapping.put("DateTime", "org.joda.time.DateTime"); + importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer"); + + typeMapping = new HashMap(); + typeMapping.put("enum", "NSString"); + typeMapping.put("array", "List"); + typeMapping.put("set", "Set"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Int"); + typeMapping.put("long", "Long"); + typeMapping.put("float", "Float"); + typeMapping.put("byte", "Byte"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "Char"); + typeMapping.put("long", "Long"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Any"); + typeMapping.put("file", "File"); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Int", + "Long", + "Float", + "Object", + "List", + "Map") + ); + instantiationTypes.put("array", "ListBuffer"); + instantiationTypes.put("map", "HashMap"); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return toModelName(type); + } + else + type = swaggerType; + return toModelName(type); + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map") + "[String, " + inner + "]"; + } + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array") + "[" + inner + "]"; + } + else + return null; + } + + public String toDefaultValue(Property p) { + if(p instanceof StringProperty) + return "null"; + else if (p instanceof BooleanProperty) + return "null"; + else if(p instanceof DateProperty) + return "null"; + else if(p instanceof DateTimeProperty) + return "null"; + else if (p instanceof DoubleProperty) + return "null"; + else if (p instanceof FloatProperty) + return "null"; + else if (p instanceof IntegerProperty) + return "null"; + else if (p instanceof LongProperty) + return "null"; + else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new HashMap[String, " + inner + "]() "; + } + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "new ListBuffer[" + inner + "]() "; + } + else + return "null"; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java new file mode 100644 index 000000000000..1475db64bf68 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -0,0 +1,119 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/java"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "java"; + } + + public String getHelp() { + return "Generates a Java client library."; + } + + public JavaClientCodegen() { + super(); + outputFolder = "generated-code/java"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "Java"; + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.model"; + + reservedWords = new HashSet ( + Arrays.asList( + "abstract", "continue", "for", "new", "switch", "assert", + "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", "byte", "else", + "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", + "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", + "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", + "native", "super", "while") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java")); + supportingFiles.add(new SupportingFile("JsonUtil.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object") + ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return toModelName(type); + } + else + type = swaggerType; + return toModelName(type); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java new file mode 100644 index 000000000000..f4aac0e74ebd --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java @@ -0,0 +1,149 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.models.Operation; +import com.wordnik.swagger.models.Path; +import com.wordnik.swagger.util.Json; +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.api"; + protected String groupId = "io.swagger"; + protected String artifactId = "swagger-server"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/java"; + protected String title = "Swagger Server"; + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "jaxrs"; + } + + public String getHelp() { + return "Generates a Java JAXRS Server application."; + } + + public JaxRSServerCodegen() { + super(); + outputFolder = "generated-code/javaJaxRS"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "JavaJaxRS"; + apiPackage = "io.swagger.api"; + modelPackage = "io.swagger.model"; + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("title", title); + + supportingFiles.clear(); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("ApiException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiException.java")); + supportingFiles.add(new SupportingFile("ApiOriginFilter.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiOriginFilter.java")); + supportingFiles.add(new SupportingFile("ApiResponseMessage.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "ApiResponseMessage.java")); + supportingFiles.add(new SupportingFile("NotFoundException.mustache", + (sourceFolder + File.separator + apiPackage).replace(".", java.io.File.separator), "NotFoundException.java")); + supportingFiles.add(new SupportingFile("web.mustache", + ("src/main/webapp/WEB-INF"), "web.xml")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float") + ); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getTypeDeclaration(inner); + } + return super.getTypeDeclaration(p); + } + + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation co, Map> operations) { + String basePath = resourcePath; + if(basePath.startsWith("/")) + basePath = basePath.substring(1); + int pos = basePath.indexOf("/"); + if(pos > 0) + basePath = basePath.substring(0, pos); + + if(basePath == "") + basePath = "default"; + else { + if(co.path.startsWith("/" + basePath)) + co.path = co.path.substring(("/" + basePath).length()); + co.subresourceOperation = !co.path.isEmpty(); + } + List opList = operations.get(basePath); + if(opList == null) { + opList = new ArrayList(); + operations.put(basePath, opList); + } + opList.add(co); + co.baseName = basePath; + } + + public Map postProcessOperations(Map objs) { + Map operations = (Map)objs.get("operations"); + if(operations != null) { + List ops = (List) operations.get("operation"); + for(CodegenOperation operation : ops) { + if(operation.returnType == null) + operation.returnType = "Void"; + else if(operation.returnType.startsWith("List")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if(end > 0) { + operation.returnType = rt.substring("List<".length(), end); + operation.returnContainer = "List"; + } + } + else if(operation.returnType.startsWith("Map")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if(end > 0) { + operation.returnType = rt.substring("Map<".length(), end); + operation.returnContainer = "Map"; + } + } + else if(operation.returnType.startsWith("Set")) { + String rt = operation.returnType; + int end = rt.lastIndexOf(">"); + if(end > 0) { + operation.returnType = rt.substring("Set<".length(), end); + operation.returnContainer = "Set"; + } + } + } + } + return objs; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java new file mode 100644 index 000000000000..74632b622fc3 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java @@ -0,0 +1,110 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.Model; +import com.wordnik.swagger.models.properties.*; +import com.wordnik.swagger.util.Json; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.*; + +import java.util.*; +import java.io.File; + +public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "com.wordnik.client"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "nodejs"; + } + + public String getHelp() { + return "Generates a node.js server application compatible with the 1.2 swagger specification."; + } + + public NodeJSServerCodegen() { + super(); + outputFolder = "generated-code/nodejs"; + apiTemplateFiles.put("api.mustache", ".js"); + templateDir = "nodejs"; + apiPackage = "app.apis"; + modelPackage = "app"; + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); + supportingFiles.add(new SupportingFile("models.mustache", modelPackage, "models.js")); + supportingFiles.add(new SupportingFile("main.mustache", "", "main.js")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float") + ); + typeMapping.put("array", "array"); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public Map postProcessSupportingFileData(Map objs) { + List> o = (List>)objs.get("models"); + + for(Map modelMap : o) { + try { + CodegenModel m = (CodegenModel) modelMap.get("model"); + ObjectNode on = (ObjectNode) Json.mapper().readTree(m.modelJson); + // inject the id field + on.put("id", m.name); + + // remove the definitions qualifier with this nasty hack + m.modelJson = Json.pretty(on).replaceAll("\"#/definitions/", "\""); + } + catch (Exception e) { + e.printStackTrace(); + // skip conversion + } + } + return objs; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + File.separator + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + return typeMapping.get(swaggerType); + } + else + type = swaggerType; + return toModelName(type); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java new file mode 100644 index 000000000000..f82e863d9944 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -0,0 +1,221 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.util.Json; +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { + protected Set foundationClasses = new HashSet(); + protected String sourceFolder = "client"; + protected static String PREFIX = "SWG"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "objc"; + } + + public String getHelp() { + return "Generates an Objective-C client library."; + } + + public ObjcClientCodegen() { + super(); + outputFolder = "generated-code/objc"; + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-body.mustache", ".m"); + apiTemplateFiles.put("api-header.mustache", ".h"); + apiTemplateFiles.put("api-body.mustache", ".m"); + templateDir = "objc"; + modelPackage = ""; + + additionalProperties.put("projectName", "swaggerClient"); + + defaultIncludes = new HashSet( + Arrays.asList( + "bool", + "int", + "NSString", + "NSObject", + "NSArray", + "NSNumber", + "NSDictionary", + "NSMutableArray", + "NSMutableDictionary") + ); + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "NSNumber", + "NSString", + "NSObject", + "bool") + ); + + reservedWords = new HashSet( + Arrays.asList( + "void", "char", "short", "int", "void", "char", "short", "int", + "long", "float", "double", "signed", "unsigned", "id", "const", + "volatile", "in", "out", "inout", "bycopy", "byref", "oneway", + "self", "super", "description" + )); + + typeMapping = new HashMap(); + typeMapping.put("enum", "NSString"); + typeMapping.put("Date", "SWGDate"); + typeMapping.put("DateTime", "SWGDate"); + // typeMapping.put("Date", "SWGDate"); + typeMapping.put("boolean", "NSNumber"); + typeMapping.put("string", "NSString"); + typeMapping.put("integer", "NSNumber"); + typeMapping.put("int", "NSNumber"); + typeMapping.put("float", "NSNumber"); + typeMapping.put("long", "NSNumber"); + typeMapping.put("double", "NSNumber"); + typeMapping.put("array", "NSArray"); + typeMapping.put("map", "NSDictionary"); + typeMapping.put("number", "NSNumber"); + typeMapping.put("List", "NSArray"); + typeMapping.put("object", "NSObject"); + + importMapping = new HashMap (); + importMapping.put("Date", "SWGDate"); + + foundationClasses = new HashSet ( + Arrays.asList( + "NSNumber", + "NSObject", + "NSString", + "NSDictionary") + ); + + instantiationTypes.put("array", "NSMutableArray"); + instantiationTypes.put("map", "NSMutableDictionary"); + + supportingFiles.add(new SupportingFile("SWGObject.h", sourceFolder, "SWGObject.h")); + supportingFiles.add(new SupportingFile("SWGObject.m", sourceFolder, "SWGObject.m")); + supportingFiles.add(new SupportingFile("SWGApiClient.h", sourceFolder, "SWGApiClient.h")); + supportingFiles.add(new SupportingFile("SWGApiClient.m", sourceFolder, "SWGApiClient.m")); + supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h")); + supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m")); + supportingFiles.add(new SupportingFile("SWGDate.h", sourceFolder, "SWGDate.h")); + supportingFiles.add(new SupportingFile("SWGDate.m", sourceFolder, "SWGDate.m")); + supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile")); + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map"); + } + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array"); + } + else + return null; + } + + @Override + public String getTypeDeclaration(String name) { + if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) + return name; + else + return name + "*"; + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) + return toModelName(type); + } + else + type = swaggerType; + return toModelName(type); + } + + @Override + public String getTypeDeclaration(Property p) { + String swaggerType = getSwaggerType(p); + if(languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) + return toModelName(swaggerType); + else + return swaggerType + "*"; + } + + @Override + public String toModelName(String type) { + if(typeMapping.keySet().contains(type) || + foundationClasses.contains(type) || + importMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { + return Character.toUpperCase(type.charAt(0)) + type.substring(1); + } + else { + return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); + } + } + + @Override + public String toModelImport(String name) { + if("".equals(modelPackage())) + return name; + else + return modelPackage() + "." + name; + } + + @Override + public String toDefaultValue(Property p) { + return null; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder; + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder; + } + + @Override + public String toModelFilename(String name) { + return PREFIX + initialCaps(name); + } + + @Override + public String toApiName(String name) { + return PREFIX + initialCaps(name) + "Api"; + } + + public String toApiFilename(String name) { + return PREFIX + initialCaps(name) + "Api"; + } + + @Override + public String toVarName(String name) { + String paramName = name.replaceAll("[^a-zA-Z0-9_]",""); + if(paramName.startsWith("new") || reservedWords.contains(paramName)) { + return escapeReservedWord(paramName); + } + else + return paramName; + } + + public String escapeReservedWord(String name) { + return "_" + name; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java new file mode 100644 index 000000000000..e7768a2177d4 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java @@ -0,0 +1,114 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.util.Json; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "com.wordnik.client"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "php"; + } + + public String getHelp() { + return "Generates a PHP client library."; + } + + public PhpClientCodegen() { + super(); + modelPackage = "models"; + outputFolder = "generated-code/php"; + modelTemplateFiles.put("model.mustache", ".php"); + apiTemplateFiles.put("api.mustache", ".php"); + templateDir = "php"; + + typeMapping.clear(); + languageSpecificPrimitives.clear(); + + reservedWords = new HashSet ( + Arrays.asList( + "int") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("array"); + languageSpecificPrimitives.add("map"); + languageSpecificPrimitives.add("string"); + languageSpecificPrimitives.add("DateTime"); + + typeMapping.put("long", "int"); + typeMapping.put("integer", "int"); + typeMapping.put("Array", "array"); + typeMapping.put("String", "string"); + typeMapping.put("List", "array"); + typeMapping.put("map", "map"); + + supportingFiles.add(new SupportingFile("Swagger.mustache", "", "Swagger.php")); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) { + return type; + } + } + else + type = swaggerType; + if(type == null) + return null; + return type; + } + + public String toDefaultValue(Property p) { + return "null"; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java new file mode 100755 index 000000000000..962f5ac08487 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java @@ -0,0 +1,109 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.io.File; + +public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { + String module = "client"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "python"; + } + + public String getHelp() { + return "Generates a Python client library."; + } + + public PythonClientCodegen() { + super(); + outputFolder = "generated-code/python"; + modelTemplateFiles.put("model.mustache", ".py"); + apiTemplateFiles.put("api.mustache", ".py"); + templateDir = "python"; + + apiPackage = module; + modelPackage = module + ".models"; + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("int"); + languageSpecificPrimitives.add("float"); + languageSpecificPrimitives.add("long"); + languageSpecificPrimitives.add("list"); + languageSpecificPrimitives.add("bool"); + languageSpecificPrimitives.add("str"); + languageSpecificPrimitives.add("datetime"); + + typeMapping.clear(); + typeMapping.put("integer", "int"); + typeMapping.put("float", "float"); + typeMapping.put("long", "long"); + typeMapping.put("double", "float"); + typeMapping.put("array", "list"); + typeMapping.put("map", "map"); + typeMapping.put("boolean", "bool"); + typeMapping.put("string", "str"); + typeMapping.put("date", "datetime"); + + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("swagger.mustache", module, "swagger.py")); + supportingFiles.add(new SupportingFile("__init__.mustache", module, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__.mustache", modelPackage.replace('.', File.separatorChar), "__init__.py")); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) { + return type; + } + } + else + type = swaggerType; + return type; + } + + public String toDefaultValue(Property p) { + // TODO: Support Python def value + return "null"; + } +} diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalaClientCodegen.java new file mode 100644 index 000000000000..85eeee98b9e8 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalaClientCodegen.java @@ -0,0 +1,192 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.client"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/java"; + protected String authScheme = ""; + protected boolean authPreemptive = false; + protected boolean asyncHttpClient = !authScheme.isEmpty(); + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "scala"; + } + + public String getHelp() { + return "Generates a Scala client library."; + } + + public ScalaClientCodegen() { + super(); + outputFolder = "generated-code/scala"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "scala"; + apiPackage = "io.swagger.client.api"; + modelPackage = "io.swagger.client.model"; + + reservedWords = new HashSet ( + Arrays.asList( + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("asyncHttpClient", asyncHttpClient); + additionalProperties.put("authScheme", authScheme); + additionalProperties.put("authPreemptive", authPreemptive); + + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.scala")); + + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + importMapping.put("DateTime", "org.joda.time.DateTime"); + importMapping.put("ListBuffer", "scala.collections.mutable.ListBuffer"); + + typeMapping = new HashMap(); + typeMapping.put("enum", "NSString"); + typeMapping.put("array", "List"); + typeMapping.put("set", "Set"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Int"); + typeMapping.put("long", "Long"); + typeMapping.put("float", "Float"); + typeMapping.put("byte", "Byte"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "Char"); + typeMapping.put("long", "Long"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Any"); + typeMapping.put("file", "File"); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Int", + "Long", + "Float", + "Object", + "List", + "Map") + ); + instantiationTypes.put("array", "ListBuffer"); + instantiationTypes.put("map", "HashMap"); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return toModelName(type); + } + else + type = swaggerType; + return toModelName(type); + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map") + "[String, " + inner + "]"; + } + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array") + "[" + inner + "]"; + } + else + return null; + } + + public String toDefaultValue(Property p) { + if(p instanceof StringProperty) + return "null"; + else if (p instanceof BooleanProperty) + return "null"; + else if(p instanceof DateProperty) + return "null"; + else if(p instanceof DateTimeProperty) + return "null"; + else if (p instanceof DoubleProperty) + return "null"; + else if (p instanceof FloatProperty) + return "null"; + else if (p instanceof IntegerProperty) + return "null"; + else if (p instanceof LongProperty) + return "null"; + else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new HashMap[String, " + inner + "]() "; + } + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "new ListBuffer[" + inner + "]() "; + } + else + return "null"; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java new file mode 100644 index 000000000000..2434ca10ee16 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java @@ -0,0 +1,178 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; +import com.wordnik.swagger.util.Json; + +import java.util.*; +import java.io.File; + +public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "com.wordnik.client"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "scalatra"; + } + + public String getHelp() { + return "Generates a Scala server application with Scalatra."; + } + + public ScalatraServerCodegen() { + super(); + outputFolder = "generated-code/scalatra"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "scalatra"; + apiPackage = "com.wordnik.client.api"; + modelPackage = "com.wordnik.client.model"; + + reservedWords = new HashSet ( + Arrays.asList( + "abstract", "continue", "for", "new", "switch", "assert", + "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", + "this", "break", "double", "implements", "protected", "throw", "byte", "else", + "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", + "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", + "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", + "native", "super", "while") + ); + + defaultIncludes = new HashSet( + Arrays.asList("double", + "Int", + "Long", + "Float", + "Double", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "List", + "Set", + "Map") + ); + + typeMapping.put("integer", "Int"); + typeMapping.put("long", "Long"); + + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appDescription", "A sample swagger server"); + additionalProperties.put("infoUrl", "http://developers.helloreverb.com"); + additionalProperties.put("infoEmail", "hello@helloreverb.com"); + additionalProperties.put("licenseInfo", "All rights reserved"); + additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); + supportingFiles.add(new SupportingFile("web.xml", "/src/main/webapp/WEB-INF", "web.xml")); + supportingFiles.add(new SupportingFile("JettyMain.scala", sourceFolder, "JettyMain.scala")); + supportingFiles.add(new SupportingFile("Bootstrap.mustache", sourceFolder, "ScalatraBootstrap.scala")); + supportingFiles.add(new SupportingFile("ServletApp.mustache", sourceFolder, "ServletApp.scala")); + supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties")); + supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt")); + supportingFiles.add(new SupportingFile("sbt", "", "sbt")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "Object") + ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); + + importMapping = new HashMap (); + importMapping.put("BigDecimal", "java.math.BigDecimal"); + importMapping.put("UUID", "java.util.UUID"); + importMapping.put("File", "java.io.File"); + importMapping.put("Date", "java.util.Date"); + importMapping.put("Timestamp", "java.sql.Timestamp"); + importMapping.put("Map", "java.util.Map"); + importMapping.put("HashMap", "java.util.HashMap"); + importMapping.put("Array", "java.util.List"); + importMapping.put("ArrayList", "java.util.ArrayList"); + importMapping.put("DateTime", "org.joda.time.DateTime"); + importMapping.put("LocalDateTime", "org.joda.time.LocalDateTime"); + importMapping.put("LocalDate", "org.joda.time.LocalDate"); + importMapping.put("LocalTime", "org.joda.time.LocalTime"); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for(CodegenOperation op: operationList) { + op.httpMethod = op.httpMethod.toLowerCase(); + } + return objs; + } + + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type)) + return toModelName(type); + } + else + type = swaggerType; + return toModelName(type); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticDocCodegen.java new file mode 100644 index 000000000000..f6c24d381bdb --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticDocCodegen.java @@ -0,0 +1,76 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "com.wordnik.client"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "docs"; + + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + public String getName() { + return "dynamic-html"; + } + + public String getHelp() { + return "Generates a dynamic HTML site."; + } + + public StaticDocCodegen() { + super(); + outputFolder = "docs"; + modelTemplateFiles.put("model.mustache", ".html"); + apiTemplateFiles.put("operation.mustache", ".html"); + templateDir = "swagger-static"; + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + supportingFiles.add(new SupportingFile("package.mustache", "", "package.json")); + supportingFiles.add(new SupportingFile("main.mustache", "", "main.js")); + supportingFiles.add(new SupportingFile("assets/css/bootstrap-responsive.css", + outputFolder + "/assets/css", "bootstrap-responsive.css")); + supportingFiles.add(new SupportingFile("assets/css/bootstrap.css", + outputFolder + "/assets/css", "bootstrap.css")); + supportingFiles.add(new SupportingFile("assets/css/style.css", + outputFolder + "/assets/css", "style.css")); + supportingFiles.add(new SupportingFile("assets/images/logo.png", + outputFolder + "/assets/images", "logo.png")); + supportingFiles.add(new SupportingFile("assets/js/bootstrap.js", + outputFolder + "/assets/js", "bootstrap.js")); + supportingFiles.add(new SupportingFile("assets/js/jquery-1.8.3.min.js", + outputFolder + "/assets/js", "jquery-1.8.3.min.js")); + supportingFiles.add(new SupportingFile("assets/js/main.js", + outputFolder + "/assets/js", "main.js")); + supportingFiles.add(new SupportingFile("index.mustache", + outputFolder, "index.html")); + + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + "operations"; + } + + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + "models"; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticHtmlGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticHtmlGenerator.java new file mode 100644 index 000000000000..d5ebe81c16ee --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/StaticHtmlGenerator.java @@ -0,0 +1,85 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; +import com.wordnik.swagger.util.Json; + +import java.util.*; +import java.io.File; + +public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "com.wordnik.client"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + public String getName() { + return "html"; + } + + public String getHelp() { + return "Generates a static HTML file."; + } + + public StaticHtmlGenerator() { + super(); + outputFolder = "docs"; + templateDir = "htmlDocs"; + + defaultIncludes = new HashSet(); + + String partner = "our Partner"; + + if(System.getProperty("partner") != null) + partner = System.getProperty("partner"); + + additionalProperties.put("partner", partner); + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appDescription", "A sample swagger server"); + additionalProperties.put("infoUrl", "https://helloreverb.com"); + additionalProperties.put("infoEmail", "hello@helloreverb.com"); + additionalProperties.put("licenseInfo", "All rights reserved"); + additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + + supportingFiles.add(new SupportingFile("index.mustache", "", "index.html")); + reservedWords = new HashSet(); + + languageSpecificPrimitives = new HashSet(); + importMapping = new HashMap (); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } + else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for(CodegenOperation op: operationList) { + op.httpMethod = op.httpMethod.toLowerCase(); + } + return objs; + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerGenerator.java new file mode 100644 index 000000000000..8ad75ae3e211 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwaggerGenerator.java @@ -0,0 +1,42 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.util.*; +import com.wordnik.swagger.models.Swagger; + +import org.apache.commons.io.FileUtils; + +import java.io.File; + +public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig { + public CodegenType getTag() { + return CodegenType.DOCUMENTATION; + } + + public String getName() { + return "swagger"; + } + + public String getHelp() { + return "Creates a static swagger.json file."; + } + + public SwaggerGenerator() { + super(); + outputFolder = "generated-code/swagger"; + } + + @Override + public void processSwagger(Swagger swagger) { + String swaggerString = Json.pretty(swagger); + + try{ + String outputFile = outputFolder + File.separator + "swagger.json"; + FileUtils.writeStringToFile(new File(outputFile), swaggerString); + System.out.println("wrote file to " + outputFile); + } + catch(Exception e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/TizenClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/TizenClientCodegen.java new file mode 100644 index 000000000000..007a978d36bb --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/TizenClientCodegen.java @@ -0,0 +1,247 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.util.Json; +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig { + protected Set foundationClasses = new HashSet(); + protected String sourceFolder = "client"; + protected static String PREFIX = "Sami"; + protected Map namespaces = new HashMap(); + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "tizen"; + } + + public String getHelp() { + return "Generates a Samsung Tizen C++ client library."; + } + + public TizenClientCodegen() { + super(); + outputFolder = "generated-code/tizen"; + modelTemplateFiles.put("model-header.mustache", ".h"); + modelTemplateFiles.put("model-body.mustache", ".cpp"); + apiTemplateFiles.put("api-header.mustache", ".h"); + apiTemplateFiles.put("api-body.mustache", ".cpp"); + templateDir = "tizen"; + modelPackage = ""; + + defaultIncludes = new HashSet( + Arrays.asList( + "bool", + "int", + "long") + ); + languageSpecificPrimitives = new HashSet(); + + additionalProperties().put("prefix", PREFIX); + + reservedWords = new HashSet( + // VERIFY + Arrays.asList( + "void", "char", "short", "int", "void", "char", "short", "int", + "long", "float", "double", "signed", "unsigned", "id", "const", + "volatile", "in", "out", "inout", "bycopy", "byref", "oneway", + "self", "super" + )); + + super.typeMapping = new HashMap(); + + typeMapping.put("Date", "DateTime"); + typeMapping.put("DateTime", "DateTime"); + typeMapping.put("string", "String"); + typeMapping.put("integer", "Integer"); + typeMapping.put("float", "Float"); + typeMapping.put("long", "Long"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("double", "Double"); + typeMapping.put("array", "IList"); + typeMapping.put("map", "HashMap"); + typeMapping.put("number", "Long"); + typeMapping.put("object", PREFIX + "Object"); + + importMapping = new HashMap(); + + namespaces = new HashMap (); + namespaces.put("DateTime", "Tizen::Base::DateTime"); + namespaces.put("Integer", "Tizen::Base::Integer"); + namespaces.put("Long", "Tizen::Base::Long"); + namespaces.put("Boolean", "Tizen::Base::Boolean"); + namespaces.put("Float", "Tizen::Base::Float"); + namespaces.put("String", "Tizen::Base::String"); + namespaces.put("Double", "Tizen::Base::Double"); + namespaces.put("IList", "Tizen::Base::Collection::IList"); + namespaces.put("HashMap", "Tizen::Base::Collection::HashMap"); + namespaces.put("ArrayList", "Tizen::Base::Collection::ArrayList"); + namespaces.put("JsonNumber", "Tizen::Web::Json"); + namespaces.put("JsonString", "Tizen::Web::Json"); + + foundationClasses = new HashSet ( + Arrays.asList( + "String", + "Integer", + "Float") + ); + supportingFiles.clear(); + supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h")); + supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h")); + supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp")); + supportingFiles.add(new SupportingFile("apiclient-header.mustache", sourceFolder, PREFIX + "ApiClient.h")); + supportingFiles.add(new SupportingFile("apiclient-body.mustache", sourceFolder, PREFIX + "ApiClient.cpp")); + supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h")); + supportingFiles.add(new SupportingFile("error-header.mustache", sourceFolder, PREFIX + "Error.h")); + supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, PREFIX + "Error.cpp")); + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map"); + } + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array"); + } + else + return null; + } + + @Override + public String getTypeDeclaration(String name) { + if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) + return name; + else + return name + "*"; + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if(typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) + return toModelName(type); + } + else + type = swaggerType; + return toModelName(type); + } + + @Override + public String getTypeDeclaration(Property p) { + String swaggerType = getSwaggerType(p); + if(languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) + return toModelName(swaggerType); + else + return swaggerType + "*"; + } + + @Override + public String toModelName(String type) { + if(typeMapping.keySet().contains(type) || + typeMapping.values().contains(type) || + foundationClasses.contains(type) || + importMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { + return type; + } + else { + return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); + } + } + + @Override + public String toModelImport(String name) { + if(namespaces.containsKey(name)) { + return "using " + namespaces.get(name) + ";"; + } + return "#include \"" + name + ".h\""; + } + + @Override + public String toDefaultValue(Property p) { + if(p instanceof StringProperty) + return "new String()"; + else if (p instanceof BooleanProperty) + return "new Boolean(false)"; + else if(p instanceof DateProperty) + return "new DateTime()"; + else if(p instanceof DateTimeProperty) + return "new DateTime()"; + else if (p instanceof DoubleProperty) + return "new Double()"; + else if (p instanceof FloatProperty) + return "new Float()"; + else if (p instanceof IntegerProperty) + return "new Integer()"; + else if (p instanceof LongProperty) + return "new Long()"; + else if (p instanceof DecimalProperty) + return "new Long()"; + else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "new HashMap()"; + } + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "new ArrayList()"; + } + // else + if(p instanceof RefProperty) { + RefProperty rp = (RefProperty) p; + return "new " + toModelName(rp.getSimpleRef()) + "()"; + } + return "null"; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder; + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder; + } + + @Override + public String toModelFilename(String name) { + return PREFIX + initialCaps(name); + } + + @Override + public String toApiName(String name) { + return PREFIX + initialCaps(name) + "Api"; + } + + public String toApiFilename(String name) { + return PREFIX + initialCaps(name) + "Api"; + } + + @Override + public String toVarName(String name) { + String paramName = name.replaceAll("[^a-zA-Z0-9_]",""); + paramName = Character.toUpperCase(paramName.charAt(0)) + paramName.substring(1); + return "p" + paramName; + } + + public String escapeReservedWord(String name) { + return "_" + name; + } +} diff --git a/src/main/resources/Groovy/ApiUtils.mustache b/modules/swagger-codegen/src/main/resources/Groovy/ApiUtils.mustache similarity index 100% rename from src/main/resources/Groovy/ApiUtils.mustache rename to modules/swagger-codegen/src/main/resources/Groovy/ApiUtils.mustache diff --git a/src/main/resources/Groovy/api.mustache b/modules/swagger-codegen/src/main/resources/Groovy/api.mustache similarity index 100% rename from src/main/resources/Groovy/api.mustache rename to modules/swagger-codegen/src/main/resources/Groovy/api.mustache diff --git a/src/main/resources/Groovy/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Groovy/build.gradle.mustache similarity index 100% rename from src/main/resources/Groovy/build.gradle.mustache rename to modules/swagger-codegen/src/main/resources/Groovy/build.gradle.mustache diff --git a/src/main/resources/Groovy/model.mustache b/modules/swagger-codegen/src/main/resources/Groovy/model.mustache similarity index 100% rename from src/main/resources/Groovy/model.mustache rename to modules/swagger-codegen/src/main/resources/Groovy/model.mustache diff --git a/src/main/resources/Java/JsonUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache similarity index 100% rename from src/main/resources/Java/JsonUtil.mustache rename to modules/swagger-codegen/src/main/resources/Java/JsonUtil.mustache diff --git a/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache similarity index 80% rename from src/main/resources/Java/api.mustache rename to modules/swagger-codegen/src/main/resources/Java/api.mustache index 90c7fe62358e..c0a697e40b42 100644 --- a/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -3,6 +3,10 @@ package {{package}}; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiInvoker; +import {{modelPackage}}.*; + +import java.util.*; + {{#imports}}import {{import}}; {{/imports}} @@ -11,7 +15,8 @@ import com.sun.jersey.multipart.FormDataMultiPart; import javax.ws.rs.core.MediaType; import java.io.File; -import java.util.*; +import java.util.Map; +import java.util.HashMap; {{#operations}} public class {{classname}} { @@ -21,25 +26,22 @@ public class {{classname}} { public ApiInvoker getInvoker() { return apiInvoker; } - + public void setBasePath(String basePath) { this.basePath = basePath; } - + public String getBasePath() { return basePath; } {{#operation}} - /* - {{#errorList}} - * error info- code: {{code}} reason: "{{reason}}" model: {{#responseModel}}{{responseModel}} + {{#errorList}} //error info- code: {{code}} reason: "{{reason}}" model: {{#responseModel}}{{responseModel}} {{/responseModel}}{{^responseModel}} {{/responseModel}} {{/errorList}} - */ - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - Object postBody = {{#bodyParam}}{{bodyParam}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#requiredParamCount}} // verify required params are set if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { @@ -48,7 +50,8 @@ public class {{classname}} { {{/requiredParamCount}} // create path and map variables - String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; + String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} + .replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params Map queryParams = new HashMap(); @@ -58,10 +61,8 @@ public class {{classname}} { {{#queryParams}}if(!"null".equals(String.valueOf({{paramName}}))) queryParams.put("{{baseName}}", String.valueOf({{paramName}})); {{/queryParams}} - {{#headerParams}}headerParams.put("{{baseName}}", {{paramName}}); {{/headerParams}} - String[] contentTypes = { {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} }; @@ -71,24 +72,18 @@ public class {{classname}} { if(contentType.startsWith("multipart/form-data")) { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); - {{#formParams}} - {{#notFile}} + {{#formParams}}{{#notFile}} hasFields = true; mp.field("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE); - {{/notFile}} - {{#isFile}} + {{/notFile}}{{#isFile}} hasFields = true; mp.field("{{baseName}}", {{paramName}}, MediaType.MULTIPART_FORM_DATA_TYPE); - {{/isFile}} - {{/formParams}} + {{/isFile}}{{/formParams}} if(hasFields) postBody = mp; } else { - {{#formParams}} - {{#notFile}} - formParams.put("{{baseName}}", String.valueOf({{paramName}})); - {{/notFile}} + {{#formParams}}{{#notFile}}formParams.put("{{baseName}}", {{paramName}});{{/notFile}} {{/formParams}} } diff --git a/src/main/resources/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache similarity index 100% rename from src/main/resources/Java/apiException.mustache rename to modules/swagger-codegen/src/main/resources/Java/apiException.mustache diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/common/ApiInvoker.java b/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache similarity index 93% rename from samples/client/wordnik-api/java/src/main/java/com/wordnik/client/common/ApiInvoker.java rename to modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache index 6f1ea350546e..26379c601058 100644 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/common/ApiInvoker.java +++ b/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache @@ -1,4 +1,4 @@ -package com.wordnik.client.common; +package {{invokerPackage}}; import com.fasterxml.jackson.core.JsonGenerator.Feature; import com.fasterxml.jackson.databind.*; @@ -11,6 +11,7 @@ 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.api.client.WebResource.Builder; +import com.sun.jersey.multipart.FormDataMultiPart; import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; @@ -50,8 +51,11 @@ public class ApiInvoker { } public static Object deserialize(String json, String containerType, Class cls) throws ApiException { + if(null != containerType) { + containerType = containerType.toLowerCase(); + } try{ - if("List".equals(containerType)) { + if("list".equals(containerType) || "array".equals(containerType)) { JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls); List response = (List) JsonUtil.getJsonMapper().readValue(json, typeInfo); return response; @@ -117,7 +121,10 @@ public class ApiInvoker { } else if ("POST".equals(method)) { if(body == null) - response = builder.post(ClientResponse.class, serialize(body)); + response = builder.post(ClientResponse.class, null); + else if(body instanceof FormDataMultiPart) { + response = builder.type(contentType).post(ClientResponse.class, body); + } else response = builder.type(contentType).post(ClientResponse.class, serialize(body)); } @@ -181,4 +188,3 @@ public class ApiInvoker { return hostMap.get(host); } } - diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache new file mode 100644 index 000000000000..48da4b2c7ffa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -0,0 +1,51 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@ApiModel(description = "{{{description}}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { + {{#vars}}{{#isEnum}} + public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} + }; + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty(required = {{required}}, value = "{{{description}}}") + @JsonProperty("{{name}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); + {{/vars}}sb.append("}\n"); + return sb.toString(); + } +} +{{/model}} +{{/models}} diff --git a/src/main/resources/Java/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/pom.mustache similarity index 95% rename from src/main/resources/Java/pom.mustache rename to modules/swagger-codegen/src/main/resources/Java/pom.mustache index 1e2dd35d0691..73d62103e22c 100644 --- a/src/main/resources/Java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pom.mustache @@ -107,35 +107,35 @@ + + com.wordnik + swagger-annotations + ${swagger-annotations-version} + com.sun.jersey jersey-client ${jersey-version} - compile com.sun.jersey.contribs jersey-multipart ${jersey-version} - compile com.fasterxml.jackson.core jackson-core ${jackson-version} - compile com.fasterxml.jackson.core jackson-annotations ${jackson-version} - compile com.fasterxml.jackson.core jackson-databind ${jackson-version} - compile com.fasterxml.jackson.datatype @@ -146,7 +146,6 @@ joda-time joda-time ${jodatime-version} - compile @@ -157,8 +156,8 @@ test - + 1.5.0-M1 1.7 2.1.4 2.3 diff --git a/samples/server-generator/java-jaxrs/templates/ApiException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache similarity index 100% rename from samples/server-generator/java-jaxrs/templates/ApiException.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiException.mustache diff --git a/samples/server-generator/java-jaxrs/templates/ApiOriginFilter.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache similarity index 100% rename from samples/server-generator/java-jaxrs/templates/ApiOriginFilter.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache diff --git a/samples/server-generator/java-jaxrs/templates/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache similarity index 89% rename from samples/server-generator/java-jaxrs/templates/ApiResponse.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache index d824014ffa16..94711b26efb2 100644 --- a/samples/server-generator/java-jaxrs/templates/ApiResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache @@ -3,7 +3,7 @@ package {{apiPackage}}; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -public class ApiResponse { +public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; public static final int INFO = 3; @@ -14,9 +14,9 @@ public class ApiResponse { String type; String message; - public ApiResponse(){} + public ApiResponseMessage(){} - public ApiResponse(int code, String message){ + public ApiResponseMessage(int code, String message){ this.code = code; switch(code){ case ERROR: diff --git a/samples/server-generator/java-jaxrs/templates/NotFoundException.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache similarity index 100% rename from samples/server-generator/java-jaxrs/templates/NotFoundException.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/NotFoundException.mustache diff --git a/samples/server-generator/java-jaxrs/templates/README.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache similarity index 100% rename from samples/server-generator/java-jaxrs/templates/README.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache new file mode 100644 index 000000000000..3b5001b9e124 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -0,0 +1,46 @@ +package {{package}}; + +import {{modelPackage}}.*; + +import com.wordnik.swagger.annotations.*; +import com.sun.jersey.multipart.FormDataParam; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.*; + +@Path("/{{baseName}}") +@Api(value = "/{{baseName}}", description = "the {{baseName}} API") +{{#operations}} +public class {{classname}} { + {{#operation}} + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + // {{returnType}} + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}}, + {{/hasMore}}{{/responses}} }) + + public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/bodyParams.mustache new file mode 100644 index 000000000000..86546afb9ca4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/bodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache new file mode 100644 index 000000000000..ba842165f3d3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/formParams.mustache @@ -0,0 +1,2 @@ +{{#isFormParam}}{{#notFile}}@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@FormParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "{{{description}}}") @FormDataParam("file") InputStream inputStream, + @ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/headerParams.mustache new file mode 100644 index 000000000000..0f88692ad1d4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/headerParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache new file mode 100644 index 000000000000..48da4b2c7ffa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -0,0 +1,51 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@ApiModel(description = "{{{description}}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { + {{#vars}}{{#isEnum}} + public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} + }; + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty(required = {{required}}, value = "{{{description}}}") + @JsonProperty("{{name}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); + {{/vars}}sb.append("}\n"); + return sb.toString(); + } +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pathParams.mustache new file mode 100644 index 000000000000..1f1b30887a40 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/samples/server-generator/java-jaxrs/templates/pom.xml b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache similarity index 71% rename from samples/server-generator/java-jaxrs/templates/pom.xml rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index d22317ce5b77..f2d2907717f3 100644 --- a/samples/server-generator/java-jaxrs/templates/pom.xml +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -1,10 +1,10 @@ 4.0.0 - com.wordnik - swagger-java-jaxrs-petstore - war - swagger-java-jaxrs-petstore - 1.0.0-SNAPSHOT + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} src/main/java @@ -31,7 +31,7 @@ ${jetty-version} - /api + {{^basePath}}/{{/basePath}}{{#basePath}}{{basePath}}{{/basePath}} target/${project.artifactId}-${project.version} ${project.basedir}/conf/jetty/webdefault.xml @@ -71,15 +71,40 @@ com.wordnik - swagger-jaxrs_2.9.1 + swagger-jersey-jaxrs ${swagger-core-version} - compile org.slf4j slf4j-log4j12 ${slf4j-version} + + com.sun.jersey + jersey-core + ${jersey-version} + + + com.sun.jersey + jersey-json + ${jersey-version} + + + com.sun.jersey + jersey-servlet + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + com.sun.jersey + jersey-server + ${jersey-version} + + org.scalatest scalatest_2.9.1 @@ -99,8 +124,9 @@ - 1.2.1 - 7.6.0.v20120127 + 1.5.1-M1 + 8.1.11.v20130520 + 1.13 1.6.3 1.6.1 4.8.1 diff --git a/samples/server-generator/java-jaxrs/templates/project/build.properties b/modules/swagger-codegen/src/main/resources/JavaJaxRS/project/build.properties similarity index 100% rename from samples/server-generator/java-jaxrs/templates/project/build.properties rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/project/build.properties diff --git a/samples/server-generator/java-jaxrs/templates/project/plugins.sbt b/modules/swagger-codegen/src/main/resources/JavaJaxRS/project/plugins.sbt similarity index 100% rename from samples/server-generator/java-jaxrs/templates/project/plugins.sbt rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/project/plugins.sbt diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/queryParams.mustache new file mode 100644 index 000000000000..b9e80e5a7e75 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/queryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @QueryParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/samples/server-generator/java-jaxrs/templates/web.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache similarity index 75% rename from samples/server-generator/java-jaxrs/templates/web.mustache rename to modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache index f0b3ae47eaaf..f6181046ddac 100644 --- a/samples/server-generator/java-jaxrs/templates/web.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/web.mustache @@ -8,7 +8,7 @@ com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages - com.wordnik.swagger.jaxrs.listing;{{apiPackage}} + com.wordnik.swagger.jaxrs.json;com.wordnik.swagger.jaxrs.listing;{{apiPackage}} com.sun.jersey.spi.container.ContainerRequestFilters @@ -18,23 +18,25 @@ com.sun.jersey.api.json.POJOMappingFeature true + 1 + + + + DefaultJaxrsConfig + com.wordnik.swagger.jaxrs.config.DefaultJaxrsConfig api.version - 0.1 + 1.0.0 - swagger.version - 1.1 + swagger.api.title + {{{title}}} swagger.api.basepath - http://localhost:8002/api + http://localhost:8002 - - swagger.security.filter - com.wordnik.swagger.sample.util.ApiAuthorizationFilterImpl - - 1 + 2 diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig new file mode 100644 index 000000000000..bc7554b95f00 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig @@ -0,0 +1,14 @@ +com.wordnik.swagger.codegen.languages.AndroidClientCodegen +com.wordnik.swagger.codegen.languages.AsyncScalaClientCodegen +com.wordnik.swagger.codegen.languages.JavaClientCodegen +com.wordnik.swagger.codegen.languages.JaxRSServerCodegen +com.wordnik.swagger.codegen.languages.NodeJSServerCodegen +com.wordnik.swagger.codegen.languages.ObjcClientCodegen +com.wordnik.swagger.codegen.languages.ScalatraServerCodegen +com.wordnik.swagger.codegen.languages.ScalaClientCodegen +com.wordnik.swagger.codegen.languages.StaticDocCodegen +com.wordnik.swagger.codegen.languages.StaticHtmlGenerator +com.wordnik.swagger.codegen.languages.SwaggerGenerator +com.wordnik.swagger.codegen.languages.TizenClientCodegen +com.wordnik.swagger.codegen.languages.PhpClientCodegen +com.wordnik.swagger.codegen.languages.PythonClientCodegen diff --git a/src/main/resources/android-java/api.mustache b/modules/swagger-codegen/src/main/resources/android-java/api.mustache similarity index 55% rename from src/main/resources/android-java/api.mustache rename to modules/swagger-codegen/src/main/resources/android-java/api.mustache index 201b8c9ca5a5..1eab419d31ad 100644 --- a/src/main/resources/android-java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/api.mustache @@ -2,20 +2,18 @@ package {{package}}; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiInvoker; + +import {{modelPackage}}.*; + +import java.util.*; + {{#imports}}import {{import}}; {{/imports}} -import java.util.*; +import java.util.Map; +import java.util.HashMap; import java.io.File; -import org.apache.http.NameValuePair; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.entity.mime.*; -import org.apache.http.entity.mime.content.*; -import org.apache.http.entity.ContentType; - -import android.webkit.MimeTypeMap; - {{#operations}} public class {{classname}} { String basePath = "{{basePath}}"; @@ -37,20 +35,14 @@ public class {{classname}} { return basePath; } - private static String getMimeType(File file) { - MimeTypeMap mime = MimeTypeMap.getSingleton(); - int index = file.getName().lastIndexOf('.')+1; - String ext = file.getName().substring(index).toLowerCase(); - return mime.getMimeTypeFromExtension(ext); - } - {{#operation}} {{#errorList}} //error info- code: {{code}} reason: "{{reason}}" model: {{#responseModel}}{{responseModel}} {{/responseModel}}{{^responseModel}} {{/responseModel}} {{/errorList}} public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - Object postBody = {{#bodyParam}}{{bodyParam}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#requiredParamCount}} // verify required params are set if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { @@ -72,49 +64,7 @@ public class {{classname}} { {{#headerParams}}headerParams.put("{{baseName}}", {{paramName}}); {{/headerParams}} - String[] contentTypes = { - {{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}} - }; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - {{#formParams}} - {{^isFile}} - hasFields = true; - mp.add(new BasicNameValuePair("{{baseName}}", {{paramName}})); - {{/isFile}} - {{/formParams}} - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - {{#formParams}} - hasFields = true; - {{^isFile}} - builder.addTextBody("{{baseName}}", {{paramName}}.toString()); - {{/isFile}} - {{#isFile}} - builder.addBinaryBody("file", {{paramName}}, ContentType.create(getMimeType({{paramName}})), {{paramName}}.getName()); - {{/isFile}} - {{/formParams}} - {{#bodyParams}} - {{#isFile}} - hasFields = true; - builder.addBinaryBody("file", {{paramName}}, ContentType.create(getMimeType({{paramName}})), {{paramName}}.getName()); - {{/isFile}} - {{/bodyParams}} - if(hasFields) - postBody = builder; - } - else { - postBody = {{#bodyParam}}{{bodyParam}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; - } + String contentType = "application/json"; try { String response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, contentType); diff --git a/src/main/resources/android-java/apiException.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiException.mustache similarity index 100% rename from src/main/resources/android-java/apiException.mustache rename to modules/swagger-codegen/src/main/resources/android-java/apiException.mustache diff --git a/src/main/resources/android-java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache similarity index 84% rename from src/main/resources/android-java/apiInvoker.mustache rename to modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache index 1b4c32adab08..425c2e7e004c 100644 --- a/src/main/resources/android-java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache @@ -12,9 +12,7 @@ import org.apache.http.client.methods.*; import org.apache.http.conn.*; import org.apache.http.conn.scheme.*; import org.apache.http.conn.ssl.*; -import org.apache.http.entity.mime.*; import org.apache.http.entity.StringEntity; -import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.impl.client.*; import org.apache.http.impl.conn.*; import org.apache.http.params.*; @@ -158,23 +156,10 @@ public class ApiInvoker { } else if ("POST".equals(method)) { HttpPost post = new HttpPost(url); - if (body != null) { - if("application/x-www-form-urlencoded".equals(contentType)) { - post.setHeader("Content-Type", contentType); - post.setEntity(new UrlEncodedFormEntity((List)body)); - } - else if("multipart/form-data".equals(contentType)) { - String boundary = "-------------" + System.currentTimeMillis(); - post.setHeader("Content-type", "multipart/form-data; boundary="+boundary); - MultipartEntityBuilder builder = (MultipartEntityBuilder)body; - builder.setBoundary(boundary); - post.setEntity(builder.build()); - } - else { - post.setHeader("Content-Type", contentType); - post.setEntity(new StringEntity(serialize(body), "UTF-8")); - } + if (body != null) { + post.setHeader("Content-Type", contentType); + post.setEntity(new StringEntity(serialize(body), "UTF-8")); } for(String key : headers.keySet()) { post.setHeader(key, headers.get(key)); @@ -184,21 +169,8 @@ public class ApiInvoker { else if ("PUT".equals(method)) { HttpPut put = new HttpPut(url); if(body != null) { - if("application/x-www-form-urlencoded".equals(contentType)) { - put.setHeader("Content-Type", contentType); - put.setEntity(new UrlEncodedFormEntity((List)body)); - } - else if("multipart/form-data".equals(contentType)) { - String boundary = "-------------" + System.currentTimeMillis(); - put.setHeader("Content-type", "multipart/form-data; boundary="+boundary); - MultipartEntityBuilder builder = (MultipartEntityBuilder)body; - builder.setBoundary(boundary); - put.setEntity(builder.build()); - } - else { - put.setHeader("Content-Type", contentType); - put.setEntity(new StringEntity(serialize(body), "UTF-8")); - } + put.setHeader("Content-Type", contentType); + put.setEntity(new StringEntity(serialize(body), "UTF-8")); } for(String key : headers.keySet()) { put.setHeader(key, headers.get(key)); diff --git a/src/main/resources/android-java/httpPatch.mustache b/modules/swagger-codegen/src/main/resources/android-java/httpPatch.mustache similarity index 100% rename from src/main/resources/android-java/httpPatch.mustache rename to modules/swagger-codegen/src/main/resources/android-java/httpPatch.mustache diff --git a/src/main/resources/android-java/jsonUtil.mustache b/modules/swagger-codegen/src/main/resources/android-java/jsonUtil.mustache similarity index 100% rename from src/main/resources/android-java/jsonUtil.mustache rename to modules/swagger-codegen/src/main/resources/android-java/jsonUtil.mustache diff --git a/modules/swagger-codegen/src/main/resources/android-java/model.mustache b/modules/swagger-codegen/src/main/resources/android-java/model.mustache new file mode 100644 index 000000000000..48da4b2c7ffa --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android-java/model.mustache @@ -0,0 +1,51 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@ApiModel(description = "{{{description}}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { + {{#vars}}{{#isEnum}} + public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} + }; + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty(required = {{required}}, value = "{{{description}}}") + @JsonProperty("{{name}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); + {{/vars}}sb.append("}\n"); + return sb.toString(); + } +} +{{/model}} +{{/models}} diff --git a/src/main/resources/android-java/pom.mustache b/modules/swagger-codegen/src/main/resources/android-java/pom.mustache similarity index 81% rename from src/main/resources/android-java/pom.mustache rename to modules/swagger-codegen/src/main/resources/android-java/pom.mustache index 480132101bc8..5f48aadfa128 100644 --- a/src/main/resources/android-java/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/pom.mustache @@ -47,22 +47,7 @@ - - maven-assembly-plugin - - - package - - single - - - - - - jar-with-dependencies - - - + org.apache.maven.plugins @@ -122,6 +107,11 @@ + + com.wordnik + swagger-annotations + ${swagger-annotations-version} + com.fasterxml.jackson.core jackson-core @@ -146,24 +136,6 @@ ${httpclient-version} compile - - org.apache.httpcomponents - httpcore - ${httpclient-version} - compile - - - org.apache.httpcomponents - httpmime - ${httpclient-version} - compile - - - com.google.android - android - 4.1.1.4 - compile - @@ -173,12 +145,18 @@ test - + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + + 1.5.1-M1 2.1.4 4.8.1 1.0.0 4.8.1 - 4.3 + 4.0 diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache new file mode 100644 index 000000000000..603676e22bca --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache @@ -0,0 +1,44 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} +import com.wordnik.swagger.client._ +import scala.concurrent.{ Future, Await } +import scala.concurrent.duration._ +import collection.mutable + +{{#operations}} +class {{classname}}(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { + + {{#operation}} + def {{nickname}}({{#allParams}}{{#optional}}{{paramName}}: Option[{{dataType}}] = {{#defaultValue}}Some({{defaultValue}}){{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{#hasMore}}, + {{/hasMore}} + {{/optional}}{{^optional}}{{paramName}}: {{dataType}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, + {{/hasMore}}{{/optional}}{{/allParams}})(implicit reader: ClientResponseReader[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]{{#bodyParams}}, writer: RequestWriter[{{dataType}}]{{/bodyParams}}){{#returnType}}: Future[{{returnType}}]{{/returnType}}{{^returnType}}: Future[Unit]{{/returnType}} = { + // create path and map variables + val path = (addFmt("{{path}}"){{#pathParams}} + replaceAll ("\\{" + "{{baseName}}" + "\\}",{{paramName}}.toString){{/pathParams}}) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + {{#requiredParamCount}}// verify required params are set + val paramCount = (Set[Any]({{/requiredParamCount}}{{#requiredParams}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) - null).size + if (paramCount != {{requiredParamCount}}) sys.error("missing required params"){{/requiredParamCount}} + + {{#queryParams}}{{#optional}}if({{paramName}} != null) {{paramName}}.foreach { v => queryParams += "{{baseName}}" -> v.toString }{{/optional}}{{^optional}} + if({{paramName}} != null) queryParams += "{{baseName}}" -> {{paramName}}.toString{{/optional}}{{/queryParams}} + + {{#headerParams}}headerParams += "{{baseName}}" -> {{paramName}}.toString{{/headerParams}} + + val resFuture = client.submit("{{httpMethod}}", path, queryParams.toMap, headerParams.toMap, {{#bodyParam}}writer.write({{paramName}}){{/bodyParam}}{{^bodyParam}}"{{emptyBodyParam}}"{{/bodyParam}}) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + {{/operation}} + +} +{{/operations}} diff --git a/src/main/resources/asyncscala/client.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache similarity index 70% rename from src/main/resources/asyncscala/client.mustache rename to modules/swagger-codegen/src/main/resources/asyncscala/client.mustache index d652ab07a940..ea7efa354cb3 100644 --- a/src/main/resources/asyncscala/client.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/client.mustache @@ -1,9 +1,11 @@ -package {{package}} +package {{invokerPackage}} {{#imports}}import {{import}} {{/imports}} +import {{apiPackage}}._ + import com.wordnik.swagger.client._ -import apis._ + import java.io.Closeable class {{clientName}}(config: SwaggerConfig) extends Closeable { @@ -13,12 +15,9 @@ class {{clientName}}(config: SwaggerConfig) extends Closeable { private[this] val client = transportClient protected def transportClient: TransportClient = new RestClient(config) - - {{#apiInfo}} - {{#apis}} - val {{name}} = new {{className}}(client, config) - {{/apis}} - {{/apiInfo}} + {{#apiInfo}}{{#apis}} + val {{classVarName}} = new {{classname}}(client, config) + {{/apis}}{{/apiInfo}} def close() { client.close() diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/model.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/model.mustache new file mode 100644 index 000000000000..b0da2825b32d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/asyncscala/model.mustache @@ -0,0 +1,13 @@ +package {{package}} + +import org.joda.time.DateTime + +{{#models}} + +{{#model}} +case class {{classname}} ( + {{#vars}}{{name}}: {{#isNotRequired}}Option[{{/isNotRequired}}{{datatype}}{{#isNotRequired}}]{{/isNotRequired}}{{#hasMore}},{{/hasMore}}{{#description}} // {{description}}{{/description}} + {{/vars}} +) +{{/model}} +{{/models}} \ No newline at end of file diff --git a/src/main/resources/asyncscala/sbt.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache similarity index 61% rename from src/main/resources/asyncscala/sbt.mustache rename to modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache index 9abb4e488537..6264f46b12e4 100644 --- a/src/main/resources/asyncscala/sbt.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/sbt.mustache @@ -4,8 +4,8 @@ name := "{{projectName}}-client" libraryDependencies += "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5" -libraryDependencies += "joda-time" % "joda-time" % "2.5" +libraryDependencies += "joda-time" % "joda-time" % "2.3" -libraryDependencies += "org.joda" % "joda-convert" % "1.7" +libraryDependencies += "org.joda" % "joda-convert" % "1.3.1" -libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.1.2" % "provided" +libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.0.13" % "provided" diff --git a/src/main/resources/csharp/Newtonsoft.Json.dll b/modules/swagger-codegen/src/main/resources/csharp/Newtonsoft.Json.dll similarity index 100% rename from src/main/resources/csharp/Newtonsoft.Json.dll rename to modules/swagger-codegen/src/main/resources/csharp/Newtonsoft.Json.dll diff --git a/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache similarity index 100% rename from src/main/resources/csharp/api.mustache rename to modules/swagger-codegen/src/main/resources/csharp/api.mustache diff --git a/src/main/resources/csharp/apiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache similarity index 100% rename from src/main/resources/csharp/apiException.mustache rename to modules/swagger-codegen/src/main/resources/csharp/apiException.mustache diff --git a/src/main/resources/csharp/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache similarity index 100% rename from src/main/resources/csharp/apiInvoker.mustache rename to modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache diff --git a/src/main/resources/csharp/compile.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile.mustache similarity index 100% rename from src/main/resources/csharp/compile.mustache rename to modules/swagger-codegen/src/main/resources/csharp/compile.mustache diff --git a/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache similarity index 100% rename from src/main/resources/csharp/model.mustache rename to modules/swagger-codegen/src/main/resources/csharp/model.mustache diff --git a/src/main/resources/flash/ASAXB-0.1.1.swc b/modules/swagger-codegen/src/main/resources/flash/ASAXB-0.1.1.swc similarity index 100% rename from src/main/resources/flash/ASAXB-0.1.1.swc rename to modules/swagger-codegen/src/main/resources/flash/ASAXB-0.1.1.swc diff --git a/src/main/resources/flash/AirExecutorApp-app.xml b/modules/swagger-codegen/src/main/resources/flash/AirExecutorApp-app.xml similarity index 100% rename from src/main/resources/flash/AirExecutorApp-app.xml rename to modules/swagger-codegen/src/main/resources/flash/AirExecutorApp-app.xml diff --git a/src/main/resources/flash/ApiClientEvent.as b/modules/swagger-codegen/src/main/resources/flash/ApiClientEvent.as similarity index 100% rename from src/main/resources/flash/ApiClientEvent.as rename to modules/swagger-codegen/src/main/resources/flash/ApiClientEvent.as diff --git a/src/main/resources/flash/ApiError.as b/modules/swagger-codegen/src/main/resources/flash/ApiError.as similarity index 100% rename from src/main/resources/flash/ApiError.as rename to modules/swagger-codegen/src/main/resources/flash/ApiError.as diff --git a/src/main/resources/flash/ApiErrorCodes.as b/modules/swagger-codegen/src/main/resources/flash/ApiErrorCodes.as similarity index 100% rename from src/main/resources/flash/ApiErrorCodes.as rename to modules/swagger-codegen/src/main/resources/flash/ApiErrorCodes.as diff --git a/src/main/resources/flash/ApiInvoker.as b/modules/swagger-codegen/src/main/resources/flash/ApiInvoker.as similarity index 100% rename from src/main/resources/flash/ApiInvoker.as rename to modules/swagger-codegen/src/main/resources/flash/ApiInvoker.as diff --git a/src/main/resources/flash/ApiUrlHelper.as b/modules/swagger-codegen/src/main/resources/flash/ApiUrlHelper.as similarity index 100% rename from src/main/resources/flash/ApiUrlHelper.as rename to modules/swagger-codegen/src/main/resources/flash/ApiUrlHelper.as diff --git a/src/main/resources/flash/ApiUserCredentials.as b/modules/swagger-codegen/src/main/resources/flash/ApiUserCredentials.as similarity index 100% rename from src/main/resources/flash/ApiUserCredentials.as rename to modules/swagger-codegen/src/main/resources/flash/ApiUserCredentials.as diff --git a/src/main/resources/flash/ListWrapper.as b/modules/swagger-codegen/src/main/resources/flash/ListWrapper.as similarity index 100% rename from src/main/resources/flash/ListWrapper.as rename to modules/swagger-codegen/src/main/resources/flash/ListWrapper.as diff --git a/src/main/resources/flash/Response.as b/modules/swagger-codegen/src/main/resources/flash/Response.as similarity index 100% rename from src/main/resources/flash/Response.as rename to modules/swagger-codegen/src/main/resources/flash/Response.as diff --git a/src/main/resources/flash/SwaggerApi.as b/modules/swagger-codegen/src/main/resources/flash/SwaggerApi.as similarity index 100% rename from src/main/resources/flash/SwaggerApi.as rename to modules/swagger-codegen/src/main/resources/flash/SwaggerApi.as diff --git a/src/main/resources/flash/XMLWriter.as b/modules/swagger-codegen/src/main/resources/flash/XMLWriter.as similarity index 100% rename from src/main/resources/flash/XMLWriter.as rename to modules/swagger-codegen/src/main/resources/flash/XMLWriter.as diff --git a/src/main/resources/flash/api.mustache b/modules/swagger-codegen/src/main/resources/flash/api.mustache similarity index 100% rename from src/main/resources/flash/api.mustache rename to modules/swagger-codegen/src/main/resources/flash/api.mustache diff --git a/src/main/resources/flash/as3corelib.swc b/modules/swagger-codegen/src/main/resources/flash/as3corelib.swc similarity index 100% rename from src/main/resources/flash/as3corelib.swc rename to modules/swagger-codegen/src/main/resources/flash/as3corelib.swc diff --git a/src/main/resources/flash/build.properties b/modules/swagger-codegen/src/main/resources/flash/build.properties similarity index 100% rename from src/main/resources/flash/build.properties rename to modules/swagger-codegen/src/main/resources/flash/build.properties diff --git a/src/main/resources/flash/build.xml b/modules/swagger-codegen/src/main/resources/flash/build.xml similarity index 100% rename from src/main/resources/flash/build.xml rename to modules/swagger-codegen/src/main/resources/flash/build.xml diff --git a/src/main/resources/flash/facetValue.as b/modules/swagger-codegen/src/main/resources/flash/facetValue.as similarity index 100% rename from src/main/resources/flash/facetValue.as rename to modules/swagger-codegen/src/main/resources/flash/facetValue.as diff --git a/src/main/resources/flash/flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc b/modules/swagger-codegen/src/main/resources/flash/flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc similarity index 100% rename from src/main/resources/flash/flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc rename to modules/swagger-codegen/src/main/resources/flash/flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc diff --git a/src/main/resources/flash/flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc b/modules/swagger-codegen/src/main/resources/flash/flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc similarity index 100% rename from src/main/resources/flash/flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc rename to modules/swagger-codegen/src/main/resources/flash/flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc diff --git a/src/main/resources/flash/flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc b/modules/swagger-codegen/src/main/resources/flash/flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc similarity index 100% rename from src/main/resources/flash/flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc rename to modules/swagger-codegen/src/main/resources/flash/flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc diff --git a/src/main/resources/flash/flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc b/modules/swagger-codegen/src/main/resources/flash/flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc similarity index 100% rename from src/main/resources/flash/flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc rename to modules/swagger-codegen/src/main/resources/flash/flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc diff --git a/src/main/resources/flash/model.mustache b/modules/swagger-codegen/src/main/resources/flash/model.mustache similarity index 100% rename from src/main/resources/flash/model.mustache rename to modules/swagger-codegen/src/main/resources/flash/model.mustache diff --git a/src/main/resources/flash/modelList.mustache b/modules/swagger-codegen/src/main/resources/flash/modelList.mustache similarity index 100% rename from src/main/resources/flash/modelList.mustache rename to modules/swagger-codegen/src/main/resources/flash/modelList.mustache diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache new file mode 100644 index 000000000000..2fd81183a5ba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/bodyParam.mustache @@ -0,0 +1,3 @@ +{{#isBodyParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+ +
Body Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache new file mode 100644 index 000000000000..97f342e60d70 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/formParam.mustache @@ -0,0 +1,3 @@ +{{#isFormParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+ +
Form Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache new file mode 100644 index 000000000000..903713493be5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/headerParam.mustache @@ -0,0 +1,3 @@ +{{#isHeaderParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+ +
Header Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache new file mode 100644 index 000000000000..ccd35c8723dc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -0,0 +1,60 @@ + + + + API Reference + + + +

{{{appName}}}

+
{{{appDescription}}} for {{partner}}
+ {{#infoUrl}}
More information: {{{infoUrl}}}
{{/infoUrl}} + {{#infoEmail}}
Contact Info: {{{infoEmail}}}
{{/infoEmail}} +
{{{licenseInfo}}}
+
{{{licenseUrl}}}
+

Access

+
Access to the API requires an api key to be provided by {{partner}} for all requests. The api key is passed as a header with the name `api_key` and the value provided by Reverb Technologies, Inc. Unless otherwise agreed upon, access to the Reverb API is intended solely for usage by {{partner}} and not third parties.
+

Methods

+ {{#apiInfo}} + {{#apis}} + {{#operations}}{{#operation}} +
+
{{httpMethod}}: {{path}}
+
{{nickname}} {{summary}}
+
{{notes}}
+ +

Parameters

+
+ {{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>headerParam}}{{>formParam}} + {{/allParams}} +
+

Return type

+ + + + {{#examples}} +

Example data

+
Content-Type: {{{contentType}}}
+
{{{example}}}
+ {{/examples}} +
+
+ {{/operation}}{{/operations}} + {{/apis}}{{/apiInfo}} + +

Models

+ {{#models}} + {{#model}} +
+

{{classname}}

+
+ {{#vars}}
{{name}} {{#isNotRequired}}(optional){{/isNotRequired}}
{{datatype}} {{description}}
+ {{/vars}} +
+
+ {{/model}} + {{/models}} + + + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache new file mode 100644 index 000000000000..b47805a4f04a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/pathParam.mustache @@ -0,0 +1,3 @@ +{{#isPathParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+ +
Path Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache new file mode 100644 index 000000000000..52147fbd7188 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/queryParam.mustache @@ -0,0 +1,3 @@ +{{#isQueryParam}}
{{paramName}} {{^required}}(optional){{/required}}{{#required}}(required){{/required}}
+ +
Query Parameter — {{description}} {{#defaultValue}}default: {{{defaultValue}}}{{/defaultValue}}
{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache new file mode 100644 index 000000000000..0421bcc8c3cb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/style.css.mustache @@ -0,0 +1,136 @@ +body { + font-family: Trebuchet MS, sans-serif; + font-size: 15px; + color: #444; + margin-right: 24px; +} + +h1 { + font-size: 25px; +} +h2 { + font-size: 20px; +} +h3 { + font-size: 16px; + font-weight: bold; +} +hr { + height: 1px; + border: 0; + color: #ddd; + background-color: #ddd; + display: none; +} + +.app-desc { + clear: both; + margin-left: 20px; +} +.param-name { + width: 100%; +} +.license-info { + margin-left: 20px; +} + +.license-url { + margin-left: 20px; +} + +.model { + margin: 0 0 0px 20px; +} + +.method { + margin-left: 20px; +} + +.method-notes { + margin: 10px 0 20px 0; + font-size: 90%; + color: #555; +} + +pre { + padding: 10px; +} + +pre.get { + background-color: #0f6ab4; +} + +pre.post { + background-color: #10a54a; +} + +pre.put { + background-color: #c5862b; +} + +pre.delete { + background-color: #a41e22; +} + +.huge { + color: #fff; +} + +pre.example { + background-color: #f3f3f3; + padding: 10px; + border: 1px solid #ddd; +} + +code { + white-space: pre; +} + +.nickname { + font-weight: bold; +} + +.method-path { + font-size: 1.5em; + background-color: #0f6ab4; +} + +.parameter { + width: 500px; +} + +.param { + width: 500px; + padding: 10px 0 0 20px; + font-weight: bold; +} + +.param-desc { + width: 700px; + padding: 0 0 0 20px; + color: #777; +} + +.param-type { + font-style: italic; +} + +.field-label { + padding: 0; + margin: 0; + clear: both; +} + +.field-items { + padding: 0 0 15px 0; + margin-bottom: 15px; +} + +.return-type { + clear: both; + padding-bottom: 10px; +} + +.param-header { + font-weight: bold; +} diff --git a/src/main/resources/logback.xml b/modules/swagger-codegen/src/main/resources/logback.xml similarity index 100% rename from src/main/resources/logback.xml rename to modules/swagger-codegen/src/main/resources/logback.xml diff --git a/modules/swagger-codegen/src/main/resources/nodejs/README.mustache b/modules/swagger-codegen/src/main/resources/nodejs/README.mustache new file mode 100644 index 000000000000..ac6dc37d3dc0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/nodejs/README.mustache @@ -0,0 +1,8 @@ +# Swagger generated server + +## Overview +This server 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 a server stub. This is an example of building a node.js server. + +This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: + +[README](https://github.com/wordnik/swagger-codegen/README.md) \ No newline at end of file diff --git a/samples/server-generator/node/templates/api.mustache b/modules/swagger-codegen/src/main/resources/nodejs/api.mustache similarity index 75% rename from samples/server-generator/node/templates/api.mustache rename to modules/swagger-codegen/src/main/resources/nodejs/api.mustache index 990c3ebabfea..82f0145ce8e3 100644 --- a/samples/server-generator/node/templates/api.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/api.mustache @@ -25,7 +25,7 @@ exports.{{nickname}} = { "summary" : "{{{summary}}}", "method": "{{httpMethod}}", "params" : [{{#queryParams}} - params.query("{{paramName}}", "{{description}}", "{{swaggerDataType}}", {{required}}, {{allowMultiple}}, "{{{allowableValues}}}"{{#defaultValue}}, {{{defaultValue}}}{{/defaultValue}}){{#hasMore}},{{/hasMore}} + params.query("{{paramName}}", "{{description}}", "{{swaggerDataType}}", {{#required}}true{{/required}}{{^required}}false{{/required}}, {{#allowMultiple}}true{{/allowMultiple}}{{^allowMultiple}}false{{/allowMultiple}}, "{{{allowableValues}}}"{{#defaultValue}}, {{{defaultValue}}}{{/defaultValue}}){{#hasMore}},{{/hasMore}} {{/queryParams}}].concat([{{#pathParams}} params.path("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}} {{/pathParams}}]).concat([{{#headerParams}} @@ -33,7 +33,17 @@ exports.{{nickname}} = { {{/headerParams}}]).concat([{{#bodyParams}} params.body("body", "{{swaggerDataType}}", "{{description}}", {{#required}}{{required}}{{/required}}{{^required}}false{{/required}}) {{/bodyParams}}]), + {{#returnContainer}} + "type": "{{returnType}}", + "items": { + {{#returnTypeIsPrimitive}}"type": "{{returnContainer}}"{{/returnTypeIsPrimitive}} + {{^returnTypeIsPrimitive}}"$ref": "{{returnContainer}}"{{/returnTypeIsPrimitive}} + }, + // container + {{/returnContainer}} + {{^returnContainer}} "type" : "{{returnType}}", + {{/returnContainer}} "responseMessages" : [errors.invalid('id'), errors.notFound('{{returnType}}')], "nickname" : "{{nickname}}" }, diff --git a/modules/swagger-codegen/src/main/resources/nodejs/main.mustache b/modules/swagger-codegen/src/main/resources/nodejs/main.mustache new file mode 100644 index 000000000000..7f4ef645982a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/nodejs/main.mustache @@ -0,0 +1,53 @@ +var express = require("express") + , url = require("url") + , cors = require("cors") + , app = express() + , swagger = require("swagger-node-express") + , db = false + + +var corsOptions = { + credentials: true, + origin: function(origin,callback) { + if(origin===undefined) { + callback(null,false); + } else { + callback(null,true); + } + } +}; + +app.use(express.json()); +app.use(express.urlencoded()); +app.use(cors(corsOptions)); + +{{#basePath}} +var subpath = express(); + +app.use("{{{basePath}}}", subpath); + +swagger.setAppHandler(subpath); +{{/basePath}} +{{^basePath}} +swagger.setAppHandler(app); +{{/basePath}} + +swagger.configureSwaggerPaths("", "api-docs", "") + +var models = require("./app/models.js"); + +{{#apiInfo}} +{{#apis}} +var {{classname}} = require("./{{apiFolder}}/{{classname}}.js"); +{{/apis}} +{{/apiInfo}} + +swagger.addModels(models) + {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}.add{{httpMethod}}({{classname}}.{{nickname}}) + {{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}; + +// configures the app +swagger.configure("http://localhost:8002{{basePath}}", "0.1"); + +// start the server +app.listen(8002); diff --git a/modules/swagger-codegen/src/main/resources/nodejs/models.mustache b/modules/swagger-codegen/src/main/resources/nodejs/models.mustache new file mode 100644 index 000000000000..133fe7c15159 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/nodejs/models.mustache @@ -0,0 +1,3 @@ +exports.models = { + {{#models}}{{#model}}"{{classVarName}}": {{{modelJson}}}{{#hasMoreModels}},{{/hasMoreModels}}{{/model}}{{/models}} +} \ No newline at end of file diff --git a/samples/server-generator/node/templates/package.mustache b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache similarity index 90% rename from samples/server-generator/node/templates/package.mustache rename to modules/swagger-codegen/src/main/resources/nodejs/package.mustache index 322dc8199669..bfd94cb0649b 100755 --- a/samples/server-generator/node/templates/package.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache @@ -3,7 +3,7 @@ "description": "Wordnik node.js server generator", "version": "{{{artifactVersion}}}", "homepage": "{{{homepage}}}", - "main": "./{{codeDir}}/main.js", + "main": "./main.js", "engines": { "node": ">= 0.8.x" }, diff --git a/src/main/resources/objc/Podfile.mustache b/modules/swagger-codegen/src/main/resources/objc/Podfile.mustache similarity index 72% rename from src/main/resources/objc/Podfile.mustache rename to modules/swagger-codegen/src/main/resources/objc/Podfile.mustache index ee3f0856b6f1..ea7deab2625f 100644 --- a/src/main/resources/objc/Podfile.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Podfile.mustache @@ -1,3 +1,3 @@ platform :ios, '6.0' xcodeproj '{{projectName}}/{{projectName}}.xcodeproj' -pod 'AFNetworking', '~> 1.0' +pod 'AFNetworking', '~> 2.1' diff --git a/src/main/resources/objc/SWGApiClient.h b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h similarity index 88% rename from src/main/resources/objc/SWGApiClient.h rename to modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h index aab60cd05958..300cd8597782 100644 --- a/src/main/resources/objc/SWGApiClient.h +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h @@ -1,7 +1,15 @@ #import -#import "AFHTTPClient.h" +#import "AFHTTPRequestOperationManager.h" -@interface SWGApiClient : AFHTTPClient +/** + * 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 : AFHTTPRequestOperationManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @property(nonatomic, assign) NSTimeInterval timeoutInterval; diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m new file mode 100644 index 000000000000..ff454970cf05 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m @@ -0,0 +1,484 @@ +#import "SWGApiClient.h" +#import "SWGFile.h" + +@implementation SWGApiClient + +NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject"; + +static long requestId = 0; +static bool offlineState = false; +static NSMutableSet * queuedRequests = nil; +static bool cacheEnabled = false; +static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; +static NSOperationQueue* sharedQueue; +static void (^reachabilityChangeBlock)(int); +static bool loggingEnabled = true; + ++(void)setLoggingEnabled:(bool) state { + loggingEnabled = state; +} + ++(void)clearCache { + [[NSURLCache sharedURLCache] removeAllCachedResponses]; +} + ++(void)setCacheEnabled:(BOOL)enabled { + cacheEnabled = enabled; +} + ++(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]; +} + ++(NSOperationQueue*) sharedQueue { + return sharedQueue; +} + ++(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl { + static NSMutableDictionary *_pool = nil; + if (queuedRequests == nil) { + queuedRequests = [[NSMutableSet alloc]init]; + } + if(_pool == nil) { + // setup static vars + // create queue + sharedQueue = [[NSOperationQueue alloc] init]; + + // create pool + _pool = [[NSMutableDictionary alloc] init]; + + // initialize URL cache + [SWGApiClient configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; + + // configure reachability + [SWGApiClient configureCacheReachibilityForHost:baseUrl]; + } + + @synchronized(self) { + SWGApiClient * client = [_pool objectForKey:baseUrl]; + if (client == nil) { + client = [[SWGApiClient alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]]; + [_pool setValue:client forKey:baseUrl ]; + if(loggingEnabled) + NSLog(@"new client for path %@", baseUrl); + } + if(loggingEnabled) + NSLog(@"returning client for path %@", baseUrl); + return client; + } +} + +-(void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey { + [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; +} + ++(unsigned long)requestQueueSize { + return [queuedRequests count]; +} + ++(NSNumber*) nextRequestId { + long nextId = ++requestId; + if(loggingEnabled) + NSLog(@"got id %ld", nextId); + return [NSNumber numberWithLong:nextId]; +} + ++(NSNumber*) queueRequest { + NSNumber* requestId = [SWGApiClient nextRequestId]; + if(loggingEnabled) + NSLog(@"added %@ to request queue", requestId); + [queuedRequests addObject:requestId]; + return requestId; +} + ++(void) cancelRequest:(NSNumber*)requestId { + [queuedRequests removeObject:requestId]; +} + ++(NSString*) escape:(id)unescaped { + if([unescaped isKindOfClass:[NSString class]]){ + return (NSString *)CFBridgingRelease + (CFURLCreateStringByAddingPercentEscapes( + NULL, + (__bridge CFStringRef) unescaped, + NULL, + (CFStringRef)@"!*'();:@&=+$,/?%#[]", + kCFStringEncodingUTF8)); + } + else { + return [NSString stringWithFormat:@"%@", unescaped]; + } +} + +-(Boolean) executeRequestWithId:(NSNumber*) requestId { + NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { + if([obj intValue] == [requestId intValue]) + return TRUE; + else return FALSE; + }]; + + if(matchingItems.count == 1) { + if(loggingEnabled) + NSLog(@"removing request id %@", requestId); + [queuedRequests removeObject:requestId]; + return true; + } + else + return false; +} + +-(id)initWithBaseURL:(NSURL *)url { + self = [super initWithBaseURL:url]; + self.requestSerializer = [AFJSONRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + if (!self) + return nil; + return self; +} + ++(AFNetworkReachabilityStatus) getReachabilityStatus { + return reachabilityStatus; +} + ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { + reachabilityChangeBlock = changeBlock; +} + ++(void) setOfflineState:(BOOL) state { + offlineState = state; +} + ++(void) configureCacheReachibilityForHost:(NSString*)host { + [[SWGApiClient sharedClientFromPool:host].reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + reachabilityStatus = status; + switch (status) { + case AFNetworkReachabilityStatusUnknown: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); + [SWGApiClient setOfflineState:true]; + break; + + case AFNetworkReachabilityStatusNotReachable: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); + [SWGApiClient setOfflineState:true]; + break; + + case AFNetworkReachabilityStatusReachableViaWWAN: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); + [SWGApiClient setOfflineState:false]; + break; + + case AFNetworkReachabilityStatusReachableViaWiFi: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); + [SWGApiClient setOfflineState:false]; + break; + default: + break; + } + // call the reachability block, if configured + if(reachabilityChangeBlock != nil) { + reachabilityChangeBlock(status); + } + }]; + [[SWGApiClient sharedClientFromPool:host].reachabilityManager startMonitoring]; +} + +-(NSString*) pathWithQueryParamsToString:(NSString*) path + queryParams:(NSDictionary*) queryParams { + NSString * separator = nil; + int counter = 0; + + NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; + if(queryParams != nil){ + for(NSString * key in [queryParams keyEnumerator]){ + if(counter == 0) separator = @"?"; + else separator = @"&"; + NSString * value; + if([[queryParams valueForKey:key] isKindOfClass:[NSString class]]){ + value = [SWGApiClient escape:[queryParams valueForKey:key]]; + } + else { + value = [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]; + } + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [SWGApiClient escape:key], value]]; + counter += 1; + } + } + return requestUrl; +} + +- (NSString*)descriptionForRequest:(NSURLRequest*)request { + return [[request URL] absoluteString]; +} + +- (void)logRequest:(NSURLRequest*)request { + NSLog(@"request: %@", [self descriptionForRequest:request]); +} + +- (void)logResponse:(id)data forRequest:(NSURLRequest*)request error:(NSError*)error { + NSLog(@"request: %@ response: %@ ", [self descriptionForRequest:request], data ); +} + +-(NSNumber*) dictionary: (NSString*) path + method: (NSString*) method + queryParams: (NSDictionary*) queryParams + body: (id) body + headerParams: (NSDictionary*) headerParams + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock { + + NSMutableURLRequest * request = nil; + if (body != nil && [body isKindOfClass:[NSArray class]]){ + SWGFile * file; + NSMutableDictionary * params = [[NSMutableDictionary alloc] init]; + for(id obj in body) { + if([obj isKindOfClass:[SWGFile class]]) { + file = (SWGFile*) obj; + requestContentType = @"multipart/form-data"; + } + else if([obj isKindOfClass:[NSDictionary class]]) { + for(NSString * key in obj) { + params[key] = obj[key]; + } + } + } + NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString]; + + if(file != nil) { + request = [self.requestSerializer multipartFormRequestWithMethod: @"POST" + URLString: urlString + parameters: nil + constructingBodyWithBlock: ^(id formData) { + + for(NSString * key in params) { + NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding]; + [formData appendPartWithFormData: data name: key]; + } + + [formData appendPartWithFileData: [file data] + name: [file paramName] + fileName: [file name] + mimeType: [file mimeType]]; + + } + error:nil]; + } + } + else { + NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; + NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:body + error:nil]; + } + BOOL hasHeaderParams = false; + if(headerParams != nil && [headerParams count] > 0) + hasHeaderParams = true; + if(offlineState) { + NSLog(@"%@ cache forced", path); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + NSLog(@"%@ cache enabled", path); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + NSLog(@"%@ cache disabled", path); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer]; + + if(body != nil) { + if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){ + [requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; + } + else if ([body isKindOfClass:[SWGFile class]]) {} + else { + NSAssert(false, @"unsupported post type!"); + } + } + if(headerParams != nil){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; + + + if (self.logRequests) { + [self logRequest:request]; + } + + NSNumber* requestId = [SWGApiClient queueRequest]; + AFHTTPRequestOperation *op = + [self HTTPRequestOperationWithRequest:request + success:^(AFHTTPRequestOperation *operation, id JSON) { + if([self executeRequestWithId:requestId]) { + if(self.logServerResponses) + [self logResponse:JSON forRequest:request error:nil]; + completionBlock(JSON, nil); + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if([self executeRequestWithId:requestId]) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if(operation.responseObject) { + // Add in the (parsed) response body. + userInfo[SWGResponseObjectErrorKey] = operation.responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + + if(self.logServerResponses) + [self logResponse:nil forRequest:request error:augmentedError]; + completionBlock(nil, augmentedError); + } + } + ]; + + [self.operationQueue addOperation:op]; + return requestId; +} + +-(NSNumber*) stringWithCompletionBlock: (NSString*) path + method: (NSString*) method + queryParams: (NSDictionary*) queryParams + body: (id) body + headerParams: (NSDictionary*) headerParams + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + completionBlock: (void (^)(NSString*, NSError *))completionBlock { + NSMutableURLRequest * request = nil; + if (body != nil && [body isKindOfClass:[NSArray class]]){ + SWGFile * file; + NSMutableDictionary * params = [[NSMutableDictionary alloc] init]; + for(id obj in body) { + if([obj isKindOfClass:[SWGFile class]]) { + file = (SWGFile*) obj; + requestContentType = @"multipart/form-data"; + } + else if([obj isKindOfClass:[NSDictionary class]]) { + for(NSString * key in obj) { + params[key] = obj[key]; + } + } + } + NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString]; + + if(file != nil) { + request = [self.requestSerializer multipartFormRequestWithMethod: @"POST" + URLString: urlString + parameters: nil + constructingBodyWithBlock: ^(id formData) { + + for(NSString * key in params) { + NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding]; + [formData appendPartWithFormData: data name: key]; + } + + [formData appendPartWithFileData: [file data] + name: [file paramName] + fileName: [file name] + mimeType: [file mimeType]]; + + } + error:nil]; + } + } + else { + NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; + NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + + request = [self.requestSerializer requestWithMethod: method + URLString: urlString + parameters: body + error: nil]; + } + BOOL hasHeaderParams = false; + if(headerParams != nil && [headerParams count] > 0) + hasHeaderParams = true; + if(offlineState) { + NSLog(@"%@ cache forced", path); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + NSLog(@"%@ cache enabled", path); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + NSLog(@"%@ cache disabled", path); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + + AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer]; + + if(body != nil) { + if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){ + [requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; + } + else if ([body isKindOfClass:[SWGFile class]]){} + else { + NSAssert(false, @"unsupported post type!"); + } + } + if(headerParams != nil){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + + + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; + + NSNumber* requestId = [SWGApiClient queueRequest]; + AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request + success:^(AFHTTPRequestOperation *operation, id responseObject) { + NSString *response = [operation responseString]; + if([self executeRequestWithId:requestId]) { + if(self.logServerResponses) + [self logResponse:responseObject forRequest:request error:nil]; + completionBlock(response, nil); + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if([self executeRequestWithId:requestId]) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if(operation.responseObject) { + // Add in the (parsed) response body. + userInfo[SWGResponseObjectErrorKey] = operation.responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + + if(self.logServerResponses) + [self logResponse:nil forRequest:request error:augmentedError]; + completionBlock(nil, augmentedError); + } + }]; + + [self.operationQueue addOperation:op]; + return requestId; +} + +@end \ No newline at end of file diff --git a/src/main/resources/objc/SWGDate.h b/modules/swagger-codegen/src/main/resources/objc/SWGDate.h similarity index 100% rename from src/main/resources/objc/SWGDate.h rename to modules/swagger-codegen/src/main/resources/objc/SWGDate.h diff --git a/src/main/resources/objc/SWGDate.m b/modules/swagger-codegen/src/main/resources/objc/SWGDate.m similarity index 100% rename from src/main/resources/objc/SWGDate.m rename to modules/swagger-codegen/src/main/resources/objc/SWGDate.m diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGFile.h b/modules/swagger-codegen/src/main/resources/objc/SWGFile.h new file mode 100644 index 000000000000..fd87e13bacec --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/SWGFile.h @@ -0,0 +1,14 @@ +#import + +@interface SWGFile : NSObject + +@property(nonatomic, readonly) NSString* name; +@property(nonatomic, readonly) NSString* mimeType; +@property(nonatomic, readonly) NSData* data; +@property(nonatomic) NSString* paramName; + +- (id) initWithNameData: (NSString*) filename + mimeType: (NSString*) mimeType + data: (NSData*) data; + +@end \ No newline at end of file diff --git a/src/main/resources/objc/SWGFile.m b/modules/swagger-codegen/src/main/resources/objc/SWGFile.m similarity index 100% rename from src/main/resources/objc/SWGFile.m rename to modules/swagger-codegen/src/main/resources/objc/SWGFile.m diff --git a/src/main/resources/objc/SWGObject.h b/modules/swagger-codegen/src/main/resources/objc/SWGObject.h similarity index 100% rename from src/main/resources/objc/SWGObject.h rename to modules/swagger-codegen/src/main/resources/objc/SWGObject.h diff --git a/src/main/resources/objc/SWGObject.m b/modules/swagger-codegen/src/main/resources/objc/SWGObject.m similarity index 100% rename from src/main/resources/objc/SWGObject.m rename to modules/swagger-codegen/src/main/resources/objc/SWGObject.m diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache new file mode 100644 index 000000000000..2998682cbadd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -0,0 +1,148 @@ +{{#operations}} +#import "{{classname}}.h" +#import "SWGFile.h" +#import "SWGApiClient.h" +{{#imports}}#import "{{import}}.h" +{{/imports}} +{{newline}} + + +@implementation {{classname}} +static NSString * basePath = @"{{basePath}}"; + ++({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { + static {{classname}}* singletonAPI = nil; + + if (singletonAPI == nil) { + singletonAPI = [[{{classname}} alloc] init]; + [singletonAPI addHeader:headerValue forKey:key]; + } + return singletonAPI; +} + ++(void) setBasePath:(NSString*)path { + basePath = path; +} + ++(NSString*) getBasePath { + return basePath; +} + +-(SWGApiClient*) apiClient { + return [SWGApiClient sharedClientFromPool:basePath]; +} + +-(void) addHeader:(NSString*)value forKey:(NSString*)key { + [[self apiClient] setHeaderValue:value forKey:key]; +} + +-(id) init { + self = [super init]; + [self apiClient]; + return self; +} + +-(void) setHeaderValue:(NSString*) value + forKey:(NSString*)key { + [[self apiClient] setHeaderValue:value forKey:key]; +} + +-(unsigned long) requestQueueSize { + return [SWGApiClient requestQueueSize]; +} + + +{{#operation}} +-(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}} + {{/allParams}} + {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{returnType}} output, NSError* error))completionBlock{{/returnBaseType}} + {{^returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock{{/returnBaseType}} { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@{{path}}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + {{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [SWGApiClient escape:{{paramName}}]]; + {{/pathParams}} + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + {{#queryParams}}if({{paramName}} != nil) + queryParams[@"{{baseName}}"] = {{paramName}}; + {{/queryParams}} + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + {{#headerParams}}if({{paramName}} != nil) + headerParams[@"{{baseName}}"] = {{paramName}}; + {{/headerParams}} + + id bodyDictionary = nil; + {{#bodyParam}} + id __body = {{paramName}}; + + if(__body != nil && [__body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)__body) { + if([dict respondsToSelector:@selector(asDictionary)]) { + [objs addObject:[(SWGObject*)dict asDictionary]]; + } + else{ + [objs addObject:dict]; + } + } + bodyDictionary = objs; + } + else if([__body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)__body asDictionary]; + } + else if([__body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)__body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding] + options: NSJSONReadingMutableContainers + error: &error]; + bodyDictionary = JSON; + } + {{/bodyParam}} + {{^bodyParam}} + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + {{#formParams}}{{#notFile}} + formParams[@"{{paramName}}"] = {{paramName}}; + {{/notFile}}{{#isFile}} + requestContentType = @"multipart/form-data"; + [bodyDictionary addObject:{{paramName}}]; + {{paramName}}.paramName = @"{{baseName}}"; + {{/isFile}}{{/formParams}} + [bodyDictionary addObject:formParams]; + {{/bodyParam}} + + {{#requiredParamCount}} + {{#requiredParams}} + if({{paramName}} == nil) { + // error + } + {{/requiredParams}} + {{/requiredParamCount}} + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + {{#returnContainer}}{{>apiBodyResponseWithContainer}}{{/returnContainer}} + {{#returnSimpleType}} + {{#returnTypeIsPrimitive}}{{>apiPrimitiveResponse}}{{/returnTypeIsPrimitive}} + {{#returnBaseType}}{{>apiNonPrimitiveResponse}}{{/returnBaseType}} + {{/returnSimpleType}} +} + +{{/operation}} + +{{newline}} +{{/operations}} +@end \ No newline at end of file diff --git a/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache similarity index 56% rename from src/main/resources/objc/api-header.mustache rename to modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 961d09181611..c42c02d5aff3 100644 --- a/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -1,6 +1,7 @@ #import {{#imports}}#import "{{import}}.h" {{/imports}} +#import "SWGObject.h" {{newline}} {{#operations}} @@ -23,10 +24,14 @@ @param {{paramName}} {{description}} {{/allParams}} + return type: {{returnType}} */ --(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}}{{newline}} {{/hasMore}}{{/allParams}} - {{#returnBaseType}}{{#hasParams}}{{newline}} completionHandler : {{/hasParams}}(void (^)({{returnType}} output, NSError* error))completionBlock;{{/returnBaseType}} - {{^returnBaseType}}{{#hasParams}}{{newline}} completionHandler : {{/hasParams}}(void (^)(NSError* error))completionBlock;{{/returnBaseType}} +-(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}} +{{/hasMore}}{{/allParams}} + {{#returnBaseType}}{{#hasParams}} + completionHandler: {{/hasParams}}(void (^)({{returnType}} output, NSError* error))completionBlock;{{/returnBaseType}} + {{^returnBaseType}}{{#hasParams}} + completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock;{{/returnBaseType}} {{newline}} {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache b/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache new file mode 100644 index 000000000000..9e4d31b6e8a5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache @@ -0,0 +1,37 @@ + // {{returnContainer}} container response type + return [client dictionary: requestUrl + method: @"{{httpMethod}}" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}}{{^returnBaseType}}completionBlock(error);{{/returnBaseType}} + return; + } + {{#isMapContainer}} + NSDictionary *result = nil; + if (data) { + result = [[NSDictionary alloc]initWithDictionary: data]; + } + completionBlock(data, nil); + {{/isMapContainer}}{{#isListContainer}} + {{#returnBaseType}}if([data isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; + for (NSDictionary* dict in (NSArray*)data) { + {{#returnTypeIsPrimitive}} + {{returnBaseType}}* d = [[{{{returnBaseType}}} alloc]initWithString: dict]; + {{/returnTypeIsPrimitive}} + {{^returnTypeIsPrimitive}} + {{{returnBaseType}}}* d = [[{{{returnBaseType}}} alloc]initWithValues: dict]; + {{/returnTypeIsPrimitive}} + [objs addObject:d]; + } + completionBlock(objs, nil); + } + {{/returnBaseType}} + {{/isListContainer}} + }]; + \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache new file mode 100644 index 000000000000..1ab814c0589c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache @@ -0,0 +1,24 @@ + {{^returnTypeIsPrimitive}} + // comples response type + return [client dictionary: requestUrl + method: @"{{httpMethod}}" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}} + {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} + return; + } + {{#returnBaseType}} + {{returnBaseType}} *result = nil; + if (data) { + result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithValues: data]; + } + {{#returnBaseType}}completionBlock(result , nil);{{/returnBaseType}} + {{/returnBaseType}} + }]; + {{/returnTypeIsPrimitive}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache new file mode 100644 index 000000000000..8e6588c456ed --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache @@ -0,0 +1,35 @@ + // primitive response type + {{#returnBaseType}}return [client stringWithCompletionBlock: requestUrl + method: @"{{httpMethod}}" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(nil, error); + return; + } + {{returnBaseType}} *result = data ? [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data] : nil; + completionBlock(result, nil); + }]; + {{/returnBaseType}} + {{^returnBaseType}} + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"{{httpMethod}}" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + {{/returnBaseType}} + \ No newline at end of file diff --git a/src/main/resources/objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache similarity index 83% rename from src/main/resources/objc/model-body.mustache rename to modules/swagger-codegen/src/main/resources/objc/model-body.mustache index f927adedb00b..942a53f88785 100644 --- a/src/main/resources/objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-body.mustache @@ -5,9 +5,11 @@ @implementation {{classname}} --(id){{#vars}}{{name}}: ({{datatype}}) {{name}}{{#hasMore}}{{newline}} {{/hasMore}}{{/vars}}{{newline}}{ - {{#vars}}_{{name}} = {{name}}; - {{/vars}} +-(id){{#vars}}{{name}}: ({{datatype}}) {{name}} + {{/vars}} +{{newline}}{ + {{#vars}}_{{name}} = {{name}}; + {{/vars}} return self; } @@ -16,35 +18,26 @@ { self = [super init]; if(self) { - {{#vars}} - - {{#isPrimitiveType}} - _{{name}} = dict[@"{{baseName}}"]; - {{/isPrimitiveType}} + {{#vars}}{{#isPrimitiveType}}_{{name}} = dict[@"{{baseName}}"];{{/isPrimitiveType}} {{#complexType}} id {{name}}_dict = dict[@"{{baseName}}"]; {{#isContainer}} if([{{name}}_dict isKindOfClass:[NSArray class]]) { - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[(NSArray*){{name}}_dict count]]; - if([(NSArray*){{name}}_dict count] > 0) { for (NSDictionary* dict in (NSArray*){{name}}_dict) { - {{{complexType}}}* d = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{complexType}}} {{/instantiationType}} alloc] initWithValues:dict]; + {{{complexType}}}* d = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{complexType}}}{{/instantiationType}} alloc] initWithValues:dict]; [objs addObject:d]; } - _{{{name}}} = [[NSArray alloc] initWithArray:objs]; } - else { + else _{{name}} = [[NSArray alloc] init]; - } } else { _{{name}} = [[NSArray alloc] init]; } - {{/isContainer}} - {{#isNotContainer}} + {{/isContainer}}{{#isNotContainer}} if({{name}}_dict != nil) _{{name}} = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{complexType}}} {{/instantiationType}} alloc]initWithValues:{{name}}_dict]; {{/isNotContainer}} diff --git a/src/main/resources/objc/model-header.mustache b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache similarity index 97% rename from src/main/resources/objc/model-header.mustache rename to modules/swagger-codegen/src/main/resources/objc/model-header.mustache index 80b4458bca89..cb954f912101 100644 --- a/src/main/resources/objc/model-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache @@ -12,7 +12,7 @@ @property(nonatomic) {{datatype}} {{name}}; {{#description}}/* {{{description}}} {{#isNotRequired}}[optional]{{/isNotRequired}} */{{/description}}{{newline}} {{/vars}} - (id) {{#vars}}{{name}}: ({{datatype}}) {{name}}{{#hasMore}}{{newline}} {{/hasMore}}{{^hasMore}};{{/hasMore}} - {{/vars}} + {{/vars}} {{newline}} - (id) initWithValues: (NSDictionary*)dict; - (NSDictionary*) asDictionary; diff --git a/modules/swagger-codegen/src/main/resources/php/Swagger.mustache b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache new file mode 100644 index 000000000000..a7a18866345d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/Swagger.mustache @@ -0,0 +1,255 @@ +host = $host; + $this->headerName = $headerName; + $this->headerValue = $headerValue; + } + + /** + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + */ + public function setTimeout($seconds) { + if (!is_numeric($seconds)) { + throw new Exception('Timeout variable must be numeric.'); + } + $this->curl_timout = $seconds; + } + + + /** + * @param string $resourcePath path to method endpoint + * @param string $method method to call + * @param array $queryParams parameters to be place in query URL + * @param array $postData parameters to be placed in POST body + * @param array $headerParams parameters to be place in request header + * @return mixed + */ + public function callAPI($resourcePath, $method, $queryParams, $postData, + $headerParams) { + + $headers = array(); + + # Allow API key from $headerParams to override default + $added_api_key = False; + if ($headerParams != null) { + foreach ($headerParams as $key => $val) { + $headers[] = "$key: $val"; + if ($key == $this->headerName) { + $added_api_key = True; + } + } + } + if (! $added_api_key && $this->headerName != null) { + $headers[] = $this->headerName . ": " . $this->headerValue; + } + + if (strpos($headers['Content-Type'], "multipart/form-data") < 0 and (is_object($postData) or is_array($postData))) { + $postData = json_encode($this->sanitizeForSerialization($postData)); + } + + $url = $this->host . $resourcePath; + + $curl = curl_init(); + if ($this->curl_timout) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timout); + } + // return the result on success, rather than just TRUE + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + + if (! empty($queryParams)) { + $url = ($url . '?' . http_build_query($queryParams)); + } + + if ($method == self::$POST) { + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$PUT) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$DELETE) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method != self::$GET) { + throw new Exception('Method ' . $method . ' is not recognized.'); + } + curl_setopt($curl, CURLOPT_URL, $url); + + // Make the request + $response = curl_exec($curl); + $response_info = curl_getinfo($curl); + + // Handle the response + if ($response_info['http_code'] == 0) { + throw new Exception("TIMEOUT: api call to " . $url . + " took more than 5s to return" ); + } else if ($response_info['http_code'] == 200) { + $data = json_decode($response); + } else if ($response_info['http_code'] == 401) { + throw new Exception("Unauthorized API request to " . $url . + ": ".json_decode($response)->message ); + } else if ($response_info['http_code'] == 404) { + $data = null; + } else { + throw new Exception("Can't connect to the api: " . $url . + " response code: " . + $response_info['http_code']); + } + return $data; + } + + /** + * Build a JSON POST object + */ + protected function sanitizeForSerialization($data) + { + if (is_scalar($data) || null === $data) { + $sanitized = $data; + } else if ($data instanceof \DateTime) { + $sanitized = $data->format(\DateTime::ISO8601); + } else if (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = $this->sanitizeForSerialization($value); + } + $sanitized = $data; + } else if (is_object($data)) { + $values = array(); + foreach (array_keys($data::$swaggerTypes) as $property) { + $values[$property] = $this->sanitizeForSerialization($data->$property); + } + $sanitized = $values; + } else { + $sanitized = (string)$data; + } + + return $sanitized; + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * @param string $value a string which will be part of the path + * @return string the serialized object + */ + public static function toPathValue($value) { + return rawurlencode($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the query, by imploding comma-separated if it's an object. + * If it's a string, pass through unchanged. It will be url-encoded + * later. + * @param object $object an object to be serialized to a string + * @return string the serialized object + */ + public static function toQueryValue($object) { + if (is_array($object)) { + return implode(',', $object); + } else { + return $object; + } + } + + /** + * Just pass through the header value for now. Placeholder in case we + * find out we need to do something with header values. + * @param string $value a string which will be part of the header + * @return string the header string + */ + public static function toHeaderValue($value) { + return $value; + } + + /** + * Deserialize a JSON string into an object + * + * @param object $object object or primitive to be deserialized + * @param string $class class name is passed as a string + * @return object an instance of $class + */ + + public static function deserialize($data, $class) + { + if (null === $data) { + $deserialized = null; + } elseif (substr($class, 0, 4) == 'map[') { + $inner = substr($class, 4, -1); + $values = array(); + if(strrpos($inner, ",") !== false) { + $subClass = explode(',', $inner, 2)[1]; + foreach ($data as $key => $value) { + $values[] = array($key => self::deserialize($value, $subClass)); + } + } + $deserialized = $values; + } elseif (substr($class, 0, 6) == 'array[') { + $subClass = substr($class, 6, -1); + $values = array(); + foreach ($data as $key => $value) { + $values[] = self::deserialize($value, $subClass); + } + $deserialized = $values; + } elseif ($class == 'DateTime') { + $deserialized = new \DateTime($data); + } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { + settype($data, $class); + $deserialized = $data; + } else { + $instance = new $class(); + foreach ($instance::$swaggerTypes as $property => $type) { + if (isset($data->$property)) { + $instance->$property = self::deserialize($data->$property, $type); + } + } + $deserialized = $instance; + } + + return $deserialized; + } + +} + diff --git a/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache similarity index 63% rename from src/main/resources/php/api.mustache rename to modules/swagger-codegen/src/main/resources/php/api.mustache index 727f37b21362..4fd50fa898b9 100644 --- a/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -1,6 +1,6 @@ apiClient->toQueryValue(${{paramName}}); - } - {{/queryParams}} - - {{#headerParams}} - if(${{paramName}} != null) { + }{{/queryParams}} + {{#headerParams}}// header params + if(${{paramName}} !== null) { $headerParams['{{paramName}}'] = $this->apiClient->toHeaderValue(${{paramName}}); - } - {{/headerParams}} - - {{#pathParams}} - if(${{paramName}} != null) { + }{{/headerParams}} + {{#pathParams}}// path params + if(${{paramName}} !== null) { $resourcePath = str_replace("{" . "{{paramName}}" . "}", $this->apiClient->toPathValue(${{paramName}}), $resourcePath); - } - {{/pathParams}} + }{{/pathParams}} + {{#formParams}} + if (${{paramName}} !== null) { + $formParams[{{paramName}}] = {{#isFile}}'@' . {{/isFile}}${{paramName}}; + }{{/formParams}} + {{#bodyParams}}// body params + $body = null; + if (isset(${{paramName}})) { + $body = ${{paramName}}; + }{{/bodyParams}} - //make the API Call - if (! isset($body)) { - $body = null; + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); } + + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $body, $headerParams); - - {{#returnType}} - - if(! $response){ - return null; - } + {{#returnType}}if(! $response) { + return null; + } $responseObject = $this->apiClient->deserialize($response, '{{returnType}}'); - return $responseObject; - - {{/returnType}} + return $responseObject;{{/returnType}} } {{/operation}} {{newline}} diff --git a/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache similarity index 75% rename from src/main/resources/php/model.mustache rename to modules/swagger-codegen/src/main/resources/php/model.mustache index 06b40bd97bc5..13a9356d5863 100644 --- a/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -1,6 +1,6 @@ '{{{datatype}}}'{{#hasMore}}, - {{/hasMore}} - {{/vars}}{{newline}} + {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} ); - {{#vars}} - {{#description}} + {{#vars}}{{#description}} /** - * {{description}} - */ - {{/description}} - public ${{name}}; // {{{datatype}}} - {{/vars}} - + * {{{description}}} + */{{/description}} + public ${{name}}; /* {{{datatype}}} */{{/vars}} } {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache new file mode 100644 index 000000000000..cf1f7142bc06 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -0,0 +1,25 @@ +# Swagger Generated Python client + + +Usage example, based on the swagger petstore: + +```python +# include the client module +from client import * + +# build a client connection. In this example, we are passing the hostname as arg0, and +# sending a header with name `api_key` and value `special-key` on each call to the api. + +client = swagger.ApiClient('http://petstore.swagger.io/v2', 'api_key', 'special-key') + +# create the PetApi class with the client we just created +petApi = PetApi.PetApi(client) + +# call the API and fetch a pet, with petId=3 +pet = petApi.getPetById(petId=3) + +# write it into pretty JSON +json = client.sanitizeForSerialization(pet) +print json +{'category': {'category': None, 'status': None, 'name': 'string', 'tags': None, 'photoUrls': None, 'id': 0L}, 'status': {'category': None, 'status': None, 'name': None, 'tags': None, 'photoUrls': None, 'id': None}, 'name': 'foogly', 'tags': [{'id': 0L, 'name': 'string'}], 'photoUrls': ['string'], 'id': 3L} +``` diff --git a/src/main/resources/python3/__init__.mustache b/modules/swagger-codegen/src/main/resources/python/__init__.mustache similarity index 63% rename from src/main/resources/python3/__init__.mustache rename to modules/swagger-codegen/src/main/resources/python/__init__.mustache index 4b41ee706c70..728aacbb9ab6 100644 --- a/src/main/resources/python3/__init__.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__.mustache @@ -5,5 +5,5 @@ import os __all__ = [] for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) + if module != '__init__.py' and module[-3:] == '.py': + __all__.append(module[:-3]) diff --git a/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache similarity index 87% rename from src/main/resources/python/api.mustache rename to modules/swagger-codegen/src/main/resources/python/api.mustache index 1b304e81d963..32c10a00fa56 100644 --- a/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -1,7 +1,7 @@ #!/usr/bin/env python """ -WordAPI.py -Copyright 2014 Wordnik, Inc. +{{classname}}.py +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -59,8 +59,12 @@ class {{classname}}(object): queryParams = {} headerParams = {} formParams = {} + files = {} bodyParam = None + headerParams['Accept'] = '{{#produces}}{{mediaType}}{{#hasMore}},{{/hasMore}}{{/produces}}'; + headerParams['Content-Type'] = '{{#consumes}}{{mediaType}}{{#hasMore}},{{/hasMore}}{{/consumes}}'; + {{#queryParams}} if ('{{paramName}}' in params): queryParams['{{paramName}}'] = self.apiClient.toPathValue(params['{{paramName}}']) @@ -80,10 +84,8 @@ class {{classname}}(object): {{#formParams}} if ('{{paramName}}' in params): - formParams['{{paramName}}'] = params['{{paramName}}'] + {{#notFile}}formParams['{{paramName}}'] = params['{{paramName}}']{{/notFile}}{{#isFile}}files['{{paramName}}'] = params['{{paramName}}']{{/isFile}} {{/formParams}} - if formParams: - headerParams['Content-type'] = 'application/x-www-form-urlencoded' {{#bodyParam}} if ('{{paramName}}' in params): @@ -93,7 +95,7 @@ class {{classname}}(object): postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) + postData, headerParams, files=files) {{#returnType}} if not response: diff --git a/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache similarity index 96% rename from src/main/resources/python/model.mustache rename to modules/swagger-codegen/src/main/resources/python/model.mustache index 39547c900505..f6e95c72dc6f 100644 --- a/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -1,6 +1,6 @@ #!/usr/bin/env python """ -Copyright 2014 Wordnik, Inc. +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache new file mode 100644 index 000000000000..8d9053025d12 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -0,0 +1,246 @@ +#!/usr/bin/env python +"""Swagger generic API client. This client handles the client- +server communication, and is invariant across implementations. Specifics of +the methods and models for each application are generated from the Swagger +templates.""" + +import sys +import os +import re +import urllib +import urllib2 +import httplib +import json +import datetime +import mimetypes +import random +import string + +from models import * + + +class ApiClient: + """Generic API client for Swagger client library builds + + Attributes: + host: The base path for the server to call + headerName: a header to pass when making calls to the API + headerValue: a header value to pass when making calls to the API + """ + def __init__(self, host=None, headerName=None, headerValue=None): + self.headerName = headerName + self.headerValue = headerValue + self.host = host + self.cookie = None + self.boundary = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(30)) + + def callAPI(self, resourcePath, method, queryParams, postData, + headerParams=None, files=None): + + url = self.host + resourcePath + headers = {} + if headerParams: + for param, value in headerParams.iteritems(): + headers[param] = value + + if self.headerName: + headers[self.headerName] = self.headerValue + + if self.cookie: + headers['Cookie'] = self.cookie + + data = None + + if queryParams: + # Need to remove None values, these should not be sent + sentQueryParams = {} + for param, value in queryParams.items(): + if value != None: + sentQueryParams[param] = value + url = url + '?' + urllib.urlencode(sentQueryParams) + + if method in ['GET']: + #Options to add statements later on and for compatibility + pass + + elif method in ['POST', 'PUT', 'DELETE']: + if postData: + postData = self.sanitizeForSerialization(postData) + if 'Content-type' not in headers: + headers['Content-type'] = 'application/json' + data = json.dumps(postData) + elif headers['Content-type'] == 'multipart/form-data': + data = self.buildMultipartFormData(postData, files) + headers['Content-type'] = 'multipart/form-data; boundary={0}'.format(self.boundary) + headers['Content-length'] = str(len(data)) + else: + data = urllib.urlencode(postData) + + else: + raise Exception('Method ' + method + ' is not recognized.') + + request = MethodRequest(method=method, url=url, headers=headers, + data=data) + + # Make the request + response = urllib2.urlopen(request) + if 'Set-Cookie' in response.headers: + self.cookie = response.headers['Set-Cookie'] + string = response.read() + + try: + data = json.loads(string) + except ValueError: # PUT requests don't return anything + data = None + + return data + + def toPathValue(self, obj): + """Convert a string or object to a path-friendly value + Args: + obj -- object or string value + Returns: + string -- quoted value + """ + if type(obj) == list: + return urllib.quote(','.join(obj)) + else: + return urllib.quote(str(obj)) + + def sanitizeForSerialization(self, obj): + """Dump an object into JSON for POSTing.""" + + if type(obj) == type(None): + return None + elif type(obj) in [str, int, long, float, bool]: + return obj + elif type(obj) == list: + return [self.sanitizeForSerialization(subObj) for subObj in obj] + elif type(obj) == datetime.datetime: + return obj.isoformat() + else: + if type(obj) == dict: + objDict = obj + else: + objDict = obj.__dict__ + return {key: self.sanitizeForSerialization(val) + for (key, val) in objDict.iteritems() + if key != 'swaggerTypes'} + + if type(postData) == list: + # Could be a list of objects + if type(postData[0]) in safeToDump: + data = json.dumps(postData) + else: + data = json.dumps([datum.__dict__ for datum in postData]) + elif type(postData) not in safeToDump: + data = json.dumps(postData.__dict__) + + def buildMultipartFormData(self, postData, files): + def escape_quotes(s): + return s.replace('"', '\\"') + + lines = [] + + for name, value in postData.items(): + lines.extend(( + '--{0}'.format(self.boundary), + 'Content-Disposition: form-data; name="{0}"'.format(escape_quotes(name)), + '', + str(value), + )) + + for name, filepath in files.items(): + f = open(filepath, 'r') + filename = filepath.split('/')[-1] + mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' + lines.extend(( + '--{0}'.format(self.boundary), + 'Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(escape_quotes(name), escape_quotes(filename)), + 'Content-Type: {0}'.format(mimetype), + '', + f.read() + )) + + lines.extend(( + '--{0}--'.format(self.boundary), + '' + )) + return '\r\n'.join(lines) + + def deserialize(self, obj, objClass): + """Derialize a JSON string into an object. + + Args: + obj -- string or object to be deserialized + objClass -- class literal for deserialzied object, or string + of class name + Returns: + object -- deserialized object""" + + # Have to accept objClass as string or actual type. Type could be a + # native Python type, or one of the model classes. + if type(objClass) == str: + if 'list[' in objClass: + match = re.match('list\[(.*)\]', objClass) + subClass = match.group(1) + return [self.deserialize(subObj, subClass) for subObj in obj] + + if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str', 'bool', 'datetime']): + objClass = eval(objClass) + else: # not a native type, must be model class + objClass = eval(objClass + '.' + objClass) + + if objClass in [int, long, float, dict, list, str, bool]: + return objClass(obj) + elif objClass == datetime: + # Server will always return a time stamp in UTC, but with + # trailing +0000 indicating no offset from UTC. So don't process + # last 5 characters. + return datetime.datetime.strptime(obj[:-5], "%Y-%m-%dT%H:%M:%S.%f") + + instance = objClass() + + for attr, attrType in instance.swaggerTypes.iteritems(): + if obj is not None and attr in obj and type(obj) in [list, dict]: + value = obj[attr] + if attrType in ['str', 'int', 'long', 'float', 'bool']: + attrType = eval(attrType) + try: + value = attrType(value) + except UnicodeEncodeError: + value = unicode(value) + except TypeError: + value = value + setattr(instance, attr, value) + elif (attrType == 'datetime'): + setattr(instance, attr, datetime.datetime.strptime(value[:-5], "%Y-%m-%dT%H:%M:%S.%f")) + elif 'list[' in attrType: + match = re.match('list\[(.*)\]', attrType) + subClass = match.group(1) + subValues = [] + if not value: + setattr(instance, attr, None) + else: + for subValue in value: + subValues.append(self.deserialize(subValue, subClass)) + setattr(instance, attr, subValues) + else: + setattr(instance, attr, self.deserialize(value, objClass)) + + return instance + + +class MethodRequest(urllib2.Request): + def __init__(self, *args, **kwargs): + """Construct a MethodRequest. Usage is the same as for + `urllib2.Request` except it also takes an optional `method` + keyword argument. If supplied, `method` will be used instead of + the default.""" + + if 'method' in kwargs: + self.method = kwargs.pop('method') + return urllib2.Request.__init__(self, *args, **kwargs) + + def get_method(self): + return getattr(self, 'method', urllib2.Request.get_method(self)) \ No newline at end of file diff --git a/src/main/resources/python/__init__.mustache b/modules/swagger-codegen/src/main/resources/python3/__init__.mustache similarity index 100% rename from src/main/resources/python/__init__.mustache rename to modules/swagger-codegen/src/main/resources/python3/__init__.mustache diff --git a/src/main/resources/python3/api.mustache b/modules/swagger-codegen/src/main/resources/python3/api.mustache similarity index 98% rename from src/main/resources/python3/api.mustache rename to modules/swagger-codegen/src/main/resources/python3/api.mustache index 2d8fbdc29ca4..85159571f652 100644 --- a/src/main/resources/python3/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python3/api.mustache @@ -1,7 +1,7 @@ #!/usr/bin/env python """ -WordAPI.py -Copyright 2014 Wordnik, Inc. +{{classname}}.py +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/main/resources/python3/model.mustache b/modules/swagger-codegen/src/main/resources/python3/model.mustache similarity index 96% rename from src/main/resources/python3/model.mustache rename to modules/swagger-codegen/src/main/resources/python3/model.mustache index 39547c900505..f6e95c72dc6f 100644 --- a/src/main/resources/python3/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python3/model.mustache @@ -1,6 +1,6 @@ #!/usr/bin/env python """ -Copyright 2014 Wordnik, Inc. +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/src/main/resources/python3/swagger.mustache b/modules/swagger-codegen/src/main/resources/python3/swagger.mustache similarity index 100% rename from src/main/resources/python3/swagger.mustache rename to modules/swagger-codegen/src/main/resources/python3/swagger.mustache diff --git a/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache similarity index 100% rename from src/main/resources/ruby/api.mustache rename to modules/swagger-codegen/src/main/resources/ruby/api.mustache diff --git a/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache similarity index 100% rename from src/main/resources/ruby/model.mustache rename to modules/swagger-codegen/src/main/resources/ruby/model.mustache diff --git a/src/main/resources/ruby/monkey.mustache b/modules/swagger-codegen/src/main/resources/ruby/monkey.mustache similarity index 100% rename from src/main/resources/ruby/monkey.mustache rename to modules/swagger-codegen/src/main/resources/ruby/monkey.mustache diff --git a/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache similarity index 100% rename from src/main/resources/ruby/swagger.mustache rename to modules/swagger-codegen/src/main/resources/ruby/swagger.mustache diff --git a/src/main/resources/ruby/swagger/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache similarity index 100% rename from src/main/resources/ruby/swagger/configuration.mustache rename to modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache diff --git a/src/main/resources/ruby/swagger/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache similarity index 100% rename from src/main/resources/ruby/swagger/request.mustache rename to modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache diff --git a/src/main/resources/ruby/swagger/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache similarity index 100% rename from src/main/resources/ruby/swagger/response.mustache rename to modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache diff --git a/src/main/resources/ruby/swagger/version.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache similarity index 100% rename from src/main/resources/ruby/swagger/version.mustache rename to modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache diff --git a/src/main/resources/scala/api.mustache b/modules/swagger-codegen/src/main/resources/scala/api.mustache similarity index 87% rename from src/main/resources/scala/api.mustache rename to modules/swagger-codegen/src/main/resources/scala/api.mustache index d277a69bddf2..1de17ce60f59 100644 --- a/src/main/resources/scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/api.mustache @@ -11,10 +11,11 @@ import java.util.Date import scala.collection.mutable.HashMap {{#operations}} -class {{classname}} { - var basePath: String = "{{basePath}}" - var apiInvoker = ApiInvoker - +class {{classname}}(val defBasePath: String = "{{basePath}}", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value {{#operation}} @@ -26,7 +27,7 @@ class {{classname}} { {{newline}} val contentType = { - {{#bodyParam}}if({{bodyParam}} != null && {{bodyParam}}.isInstanceOf[File] ) + {{#bodyParam}}if({{paramName}} != null && {{paramName}}.isInstanceOf[File] ) "multipart/form-data" else "application/json" {{/bodyParam}} @@ -52,7 +53,7 @@ class {{classname}} { {{/headerParams}} try { - apiInvoker.invokeApi(basePath, path, "{{httpMethod}}", queryParams.toMap, {{#bodyParam}}{{bodyParam}}{{/bodyParam}}{{^bodyParam}}None{{/bodyParam}}, headerParams.toMap, contentType) match { + apiInvoker.invokeApi(basePath, path, "{{httpMethod}}", queryParams.toMap, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}None{{/bodyParam}}, headerParams.toMap, contentType) match { case s: String => {{#returnType}} Some(ApiInvoker.deserialize(s, "{{returnContainer}}", classOf[{{returnBaseType}}]).asInstanceOf[{{returnType}}]) {{/returnType}} diff --git a/src/main/resources/scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache similarity index 80% rename from src/main/resources/scala/apiInvoker.mustache rename to modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache index 5c6d60d37b58..186be3640143 100644 --- a/src/main/resources/scala/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/apiInvoker.mustache @@ -35,10 +35,14 @@ object ScalaJsonUtil { } } -object ApiInvoker { - val mapper = ScalaJsonUtil.getJsonMapper - val defaultHeaders: HashMap[String, String] = HashMap() - val hostMap: HashMap[String, Client] = HashMap() +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") @@ -151,14 +155,39 @@ object ApiInvoker { hostMap.contains(host) match { case true => hostMap(host) case false => { - val client = Client.create() + 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 = {{asyncHttpClient}}, + authScheme = "{{authScheme}}", + authPreemptive = {{authPreemptive}}) + class ApiException(val code: Int, msg: String) extends RuntimeException(msg) diff --git a/modules/swagger-codegen/src/main/resources/scala/model.mustache b/modules/swagger-codegen/src/main/resources/scala/model.mustache new file mode 100644 index 000000000000..a45b71a8f8e9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scala/model.mustache @@ -0,0 +1,15 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} + +{{#models}} + +{{#model}} + +case class {{classname}} ( + {{#vars}}{{#description}}/* {{{description}}} */ + {{/description}}{{name}}: {{{datatype}}}{{#hasMore}},{{/hasMore}}{{^hasMore}}){{/hasMore}} + {{/vars}} +{{/model}} +{{/models}} \ No newline at end of file diff --git a/src/main/resources/scala/pom.mustache b/modules/swagger-codegen/src/main/resources/scala/pom.mustache similarity index 78% rename from src/main/resources/scala/pom.mustache rename to modules/swagger-codegen/src/main/resources/scala/pom.mustache index d5ad2d05a094..1163b7d381a7 100644 --- a/src/main/resources/scala/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/scala/pom.mustache @@ -5,7 +5,7 @@ {{artifactId}} jar {{artifactId}} - {{apiVersion}} + {{artifactVersion}} 2.2.0 @@ -150,33 +150,40 @@ + + com.fasterxml.jackson.module + jackson-module-scala_2.10 + ${jackson-version} + com.sun.jersey jersey-client ${jersey-version} - compile com.sun.jersey.contribs jersey-multipart ${jersey-version} + + + org.jfarcand + jersey-ahc-client + ${jersey-async-version} compile org.scala-lang scala-library ${scala-version} - compile com.wordnik - swagger-core_${scala-short-version} + swagger-core ${swagger-core-version} - compile org.scalatest - scalatest_${scala-short-version} + scalatest_2.10 ${scala-test-version} test @@ -186,44 +193,29 @@ ${junit-version} test + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + - - - scala_2.11 - - 2.11.2 - 2.11 - 1.3.10 - 2.2.2 - - - - scala_2.10 - - true - - - 2.10.3 - 2.10 - 1.3.10 - 2.1.2 - - - - scala_2.9.1 - - 2.9.1-1 - 2.9.1 - 1.3.1 - 1.9.2 - - - + 2.10.4 + 1.2 + 2.2 1.7 - 4.8.1 + 1.5.0-M1 + 1.0.5 1.0.0 + 2.4.2 + 4.8.1 - 3.2.0 + 3.1.5 + 2.1.3 diff --git a/samples/server-generator/scalatra/templates/Bootstrap.mustache b/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache similarity index 79% rename from samples/server-generator/scalatra/templates/Bootstrap.mustache rename to modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache index 07bcf6c60673..64c0b07eb283 100644 --- a/samples/server-generator/scalatra/templates/Bootstrap.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/Bootstrap.mustache @@ -10,11 +10,8 @@ class ScalatraBootstrap extends LifeCycle { override def init(context: ServletContext) { implicit val system = ActorSystem("appActorSystem") try { - {{#apiInfo}} - {{#apis}} - context mount (new {{classname}}, "/{{baseName}}/*") - {{/apis}} - {{/apiInfo}} + {{#apiInfo}}{{#apis}}context mount (new {{classname}}, "/{{baseName}}/*") + {{/apis}}{{/apiInfo}} context mount (new ResourcesApp, "/api-docs/*") } catch { case e: Throwable => e.printStackTrace() diff --git a/modules/swagger-codegen/src/main/resources/scalatra/JettyMain.scala b/modules/swagger-codegen/src/main/resources/scalatra/JettyMain.scala new file mode 100644 index 000000000000..e25f16ba3929 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/JettyMain.scala @@ -0,0 +1,43 @@ +import org.eclipse.jetty.server._ +import org.eclipse.jetty.webapp.WebAppContext +import org.scalatra.servlet.ScalatraListener + +object JettyMain { + + object conf { + val port = sys.env.get("PORT") map (_.toInt) getOrElse (8080) + val stopTimeout = sys.env.get("STOP_TIMEOUT") map (_.toInt) getOrElse (5000) + val connectorIdleTimeout = sys.env.get("CONNECTOR_IDLE_TIMEOUT") map (_.toInt) getOrElse (90000) + val webapp = sys.env.get("PUBLIC") getOrElse "webapp" + val contextPath = sys.env.get("CONTEXT_PATH") getOrElse "/" + } + + def main(args: Array[String]) = { + val server: Server = new Server + println("starting jetty") + + server setStopTimeout conf.stopTimeout + //server setDumpAfterStart true + server setStopAtShutdown true + + val httpConfig = new HttpConfiguration() + httpConfig setSendDateHeader true + httpConfig setSendServerVersion false + + val connector = new NetworkTrafficServerConnector(server, new HttpConnectionFactory(httpConfig)) + connector setPort conf.port + connector setSoLingerTime 0 + connector setIdleTimeout conf.connectorIdleTimeout + server addConnector connector + + val webapp = conf.webapp + val webApp = new WebAppContext + webApp setContextPath conf.contextPath + webApp setResourceBase conf.webapp + webApp setEventListeners Array(new ScalatraListener) + + server setHandler webApp + + server.start() + } +} diff --git a/samples/server-generator/scalatra/templates/JsonUtil.scala b/modules/swagger-codegen/src/main/resources/scalatra/JsonUtil.scala similarity index 100% rename from samples/server-generator/scalatra/templates/JsonUtil.scala rename to modules/swagger-codegen/src/main/resources/scalatra/JsonUtil.scala diff --git a/samples/server-generator/scalatra/templates/README.mustache b/modules/swagger-codegen/src/main/resources/scalatra/README.mustache similarity index 100% rename from samples/server-generator/scalatra/templates/README.mustache rename to modules/swagger-codegen/src/main/resources/scalatra/README.mustache diff --git a/samples/server-generator/scalatra/templates/ServletApp.mustache b/modules/swagger-codegen/src/main/resources/scalatra/ServletApp.mustache similarity index 86% rename from samples/server-generator/scalatra/templates/ServletApp.mustache rename to modules/swagger-codegen/src/main/resources/scalatra/ServletApp.mustache index 706d9a77cdda..f6e53468ec9d 100644 --- a/samples/server-generator/scalatra/templates/ServletApp.mustache +++ b/modules/swagger-codegen/src/main/resources/scalatra/ServletApp.mustache @@ -30,10 +30,10 @@ class SwaggerApp extends Swagger(apiInfo = ApiSwagger.apiInfo, apiVersion = "1.0 object ApiSwagger { val apiInfo = ApiInfo( - "{{{appName}}}", - "{{{appDescription}}}", - "{{{infoUrl}}}", - "{{{infoEmail}}}", - "{{{licenseInfo}}}", - "{{{licenseUrl}}}") + """{{{appName}}}""", + """{{{appDescription}}}""", + """{{{infoUrl}}}""", + """{{{infoEmail}}}""", + """{{{licenseInfo}}}""", + """{{{licenseUrl}}}""") } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/api.mustache b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache new file mode 100644 index 000000000000..54710361fe9a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/api.mustache @@ -0,0 +1,94 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} + +import java.io.File + +import org.scalatra.{ TypedParamSupport, ScalatraServlet } +import org.scalatra.swagger._ +import org.json4s._ +import org.json4s.JsonDSL._ +import org.scalatra.json.{ JValueResult, JacksonJsonSupport } +import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException} + +import scala.collection.JavaConverters._ + +class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet + with FileUploadSupport + with JacksonJsonSupport + with SwaggerSupport { + protected implicit val jsonFormats: Formats = DefaultFormats + + protected val applicationDescription: String = "{{classname}}" + override protected val applicationName: Option[String] = Some("{{baseName}}") + + before() { + contentType = formats("json") + response.headers += ("Access-Control-Allow-Origin" -> "*") + } +{{#operations}} +{{#operation}} + {{newline}} + + val {{nickname}}Operation = (apiOperation[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]("{{nickname}}") + summary "{{{summary}}}" + parameters( + {{#allParams}}{{#isQueryParam}}queryParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} + {{/isQueryParam}} + {{#isPathParam}}pathParam[{{dataType}}]("{{paramName}}").description(""){{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} + {{/isPathParam}} + {{#isHeaderParam}}headerParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} + {{/isHeaderParam}} + {{#isBodyParam}}bodyParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} + {{/isBodyParam}} + {{#isFormParam}}formParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} + {{/isFormParam}} + {{#hasMore}},{{/hasMore}} + {{/allParams}}) + ) + + {{httpMethod}}("{{path}}",operation({{nickname}}Operation)) { + {{#allParams}} + {{#isFile}} + val {{paramName}} = fileParams("{{paramName}}") + {{/isFile}} + {{^isFile}} + {{#isPathParam}} + val {{paramName}} = params.getOrElse("{{paramName}}", halt(400)) + {{/isPathParam}} + + {{#isQueryParam}} + {{#collectionFormat}}val {{paramName}}String = params.getAs[String]("{{paramName}}") + val {{paramName}} = if("{{collectionFormat}}".equals("default")) { + {{paramName}}String match { + case Some(str) => str.split(",") + case None => List() + } + } + else + List() + {{/collectionFormat}} + {{^collectionFormat}}val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}"){{/collectionFormat}} + + {{/isQueryParam}} + + {{#isHeaderParam}} + val {{paramName}} = request.getHeader("{{paramName}}") + {{/isHeaderParam}} + + {{#isFormParam}} + val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}") + {{/isFormParam}} + + {{#isBodyParam}} + val {{paramName}} = parsedBody.extract[{{dataType}}] + {{/isBodyParam}} + {{/isFile}} + println("{{paramName}}: " + {{paramName}}) + {{/allParams}} + } + +{{/operation}} +{{/operations}} +} \ No newline at end of file diff --git a/samples/server-generator/scalatra/templates/build.sbt b/modules/swagger-codegen/src/main/resources/scalatra/build.sbt similarity index 79% rename from samples/server-generator/scalatra/templates/build.sbt rename to modules/swagger-codegen/src/main/resources/scalatra/build.sbt index 9f04adc46ba6..afe84c2c7f09 100644 --- a/samples/server-generator/scalatra/templates/build.sbt +++ b/modules/swagger-codegen/src/main/resources/scalatra/build.sbt @@ -18,24 +18,27 @@ name := "scalatra-sample" version := "0.1.0-SNAPSHOT" -scalaVersion := "2.10.0" +scalaVersion := "2.11.2" + +scalacOptions += "-language:postfixOps" libraryDependencies ++= Seq( - "org.scalatest" %% "scalatest" % "2.0" % "test", + "org.scalatest" %% "scalatest" % "2.2.1" % "test", "org.scalatra" %% "scalatra" % "2.3.0.RC3", "org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3", "org.scalatra" %% "scalatra-json" % "2.3.0.RC3", "org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3", "org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3", "org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3", - "org.json4s" %% "json4s-jackson" % "3.1.0", - "org.json4s" %% "json4s-ext" % "3.1.0", + "org.json4s" %% "json4s-jackson" % "3.2.10", + "org.json4s" %% "json4s-ext" % "3.2.10", "commons-codec" % "commons-codec" % "1.7", - "net.databinder.dispatch" %% "dispatch-core" % "0.9.5", - "net.databinder.dispatch" %% "json4s-jackson" % "0.9.5", - "com.typesafe.akka" %% "akka-actor" % "2.1.0", - "org.eclipse.jetty" % "jetty-server" % "8.1.7.v20120910" % "container;provided", - "org.eclipse.jetty" % "jetty-webapp" % "8.1.7.v20120910" % "container;provided", + "net.databinder.dispatch" %% "dispatch-core" % "0.11.2", + //"net.databinder.dispatch" %% "json4s-jackson" % "0.11.2", + "net.databinder.dispatch" %% "dispatch-json4s-jackson" % "0.11.2", + "com.typesafe.akka" %% "akka-actor" % "2.3.6", + "org.eclipse.jetty" % "jetty-server" % "9.2.3.v20140905" % "container;compile;test", + "org.eclipse.jetty" % "jetty-webapp" % "9.2.3.v20140905" % "container;compile;test", "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar")) ) @@ -51,9 +54,11 @@ ivyXML := -mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) => - { +mergeStrategy in assembly <<= (mergeStrategy in assembly) { + (old) => { case "about.html" => MergeStrategy.discard case x => old(x) } } + +net.virtualvoid.sbt.graph.Plugin.graphSettings diff --git a/modules/swagger-codegen/src/main/resources/scalatra/model.mustache b/modules/swagger-codegen/src/main/resources/scalatra/model.mustache new file mode 100644 index 000000000000..8c5d19546622 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/model.mustache @@ -0,0 +1,15 @@ +package {{package}} + +{{#imports}}import {{import}} +{{/imports}} + +{{#models}} + +{{#model}} +case class {{classname}} ( + {{#vars}}{{name}}: {{#isNotRequired}}Option[{{/isNotRequired}}{{datatype}}{{#isNotRequired}}] {{#description}} // {{description}}{{/description}} + {{/isNotRequired}}{{#hasMore}}, + {{/hasMore}}{{/vars}} +) +{{/model}} +{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/scalatra/project/build.properties b/modules/swagger-codegen/src/main/resources/scalatra/project/build.properties new file mode 100644 index 000000000000..be6c454fbaca --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.13.5 diff --git a/modules/swagger-codegen/src/main/resources/scalatra/project/plugins.sbt b/modules/swagger-codegen/src/main/resources/scalatra/project/plugins.sbt new file mode 100644 index 000000000000..7358abbbbc6a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/project/plugins.sbt @@ -0,0 +1,9 @@ +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.1") + +addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "0.7.5") + +addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.9.0") + +addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.3.0") + +addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.7.4") diff --git a/modules/swagger-codegen/src/main/resources/scalatra/sbt b/modules/swagger-codegen/src/main/resources/scalatra/sbt new file mode 100755 index 000000000000..08e58821219c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/scalatra/sbt @@ -0,0 +1,525 @@ +#!/usr/bin/env bash +# +# A more capable sbt runner, coincidentally also called sbt. +# Author: Paul Phillips + +# todo - make this dynamic +declare -r sbt_release_version="0.13.6" +declare -r sbt_unreleased_version="0.13.6" +declare -r buildProps="project/build.properties" + +declare sbt_jar sbt_dir sbt_create sbt_version +declare scala_version sbt_explicit_version +declare verbose noshare batch trace_level log_level +declare sbt_saved_stty debugUs + +echoerr () { echo >&2 "$@"; } +vlog () { [[ -n "$verbose" ]] && echoerr "$@"; } + +# spaces are possible, e.g. sbt.version = 0.13.0 +build_props_sbt () { + [[ -r "$buildProps" ]] && \ + grep '^sbt\.version' "$buildProps" | tr '=' ' ' | awk '{ print $2; }' +} + +update_build_props_sbt () { + local ver="$1" + local old="$(build_props_sbt)" + + [[ -r "$buildProps" ]] && [[ "$ver" != "$old" ]] && { + perl -pi -e "s/^sbt\.version\b.*\$/sbt.version=${ver}/" "$buildProps" + grep -q '^sbt.version[ =]' "$buildProps" || printf "\nsbt.version=%s\n" "$ver" >> "$buildProps" + + vlog "!!!" + vlog "!!! Updated file $buildProps setting sbt.version to: $ver" + vlog "!!! Previous value was: $old" + vlog "!!!" + } +} + +set_sbt_version () { + sbt_version="${sbt_explicit_version:-$(build_props_sbt)}" + [[ -n "$sbt_version" ]] || sbt_version=$sbt_release_version + export sbt_version +} + +# restore stty settings (echo in particular) +onSbtRunnerExit() { + [[ -n "$sbt_saved_stty" ]] || return + vlog "" + vlog "restoring stty: $sbt_saved_stty" + stty "$sbt_saved_stty" + unset sbt_saved_stty +} + +# save stty and trap exit, to ensure echo is reenabled if we are interrupted. +trap onSbtRunnerExit EXIT +sbt_saved_stty="$(stty -g 2>/dev/null)" +vlog "Saved stty: $sbt_saved_stty" + +# this seems to cover the bases on OSX, and someone will +# have to tell me about the others. +get_script_path () { + local path="$1" + [[ -L "$path" ]] || { echo "$path" ; return; } + + local target="$(readlink "$path")" + if [[ "${target:0:1}" == "/" ]]; then + echo "$target" + else + echo "${path%/*}/$target" + fi +} + +die() { + echo "Aborting: $@" + exit 1 +} + +make_url () { + version="$1" + + case "$version" in + 0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;; + 0.10.* ) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + 0.11.[12]) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + *) echo "$sbt_launch_repo/org.scala-sbt/sbt-launch/$version/sbt-launch.jar" ;; + esac +} + +init_default_option_file () { + local overriding_var="${!1}" + local default_file="$2" + if [[ ! -r "$default_file" && "$overriding_var" =~ ^@(.*)$ ]]; then + local envvar_file="${BASH_REMATCH[1]}" + if [[ -r "$envvar_file" ]]; then + default_file="$envvar_file" + fi + fi + echo "$default_file" +} + +declare -r cms_opts="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC" +declare -r jit_opts="-XX:ReservedCodeCacheSize=256m -XX:+TieredCompilation" +declare -r default_jvm_opts_common="-Xms512m -Xmx1536m -Xss2m $jit_opts $cms_opts" +declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" +declare -r latest_28="2.8.2" +declare -r latest_29="2.9.3" +declare -r latest_210="2.10.4" +declare -r latest_211="2.11.2" + +declare -r script_path="$(get_script_path "$BASH_SOURCE")" +declare -r script_name="${script_path##*/}" + +# some non-read-onlies set with defaults +declare java_cmd="java" +declare sbt_opts_file="$(init_default_option_file SBT_OPTS .sbtopts)" +declare jvm_opts_file="$(init_default_option_file JVM_OPTS .jvmopts)" +declare sbt_launch_repo="http://typesafe.artifactoryonline.com/typesafe/ivy-releases" + +# pull -J and -D options to give to java. +declare -a residual_args +declare -a java_args +declare -a scalac_args +declare -a sbt_commands + +# args to jvm/sbt via files or environment variables +declare -a extra_jvm_opts extra_sbt_opts + +# if set, use JAVA_HOME over java found in path +[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java" + +# directory to store sbt launchers +declare sbt_launch_dir="$HOME/.sbt/launchers" +[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir" +[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers.XXXXXX)" + +java_version () { + local version=$("$java_cmd" -version 2>&1 | grep -e 'java version' | awk '{ print $3 }' | tr -d \") + vlog "Detected Java version: $version" + echo "${version:2:1}" +} + +# MaxPermSize critical on pre-8 jvms but incurs noisy warning on 8+ +default_jvm_opts () { + local v="$(java_version)" + if [[ $v -ge 8 ]]; then + echo "$default_jvm_opts_common" + else + echo "-XX:MaxPermSize=384m $default_jvm_opts_common" + fi +} + +build_props_scala () { + if [[ -r "$buildProps" ]]; then + versionLine="$(grep '^build.scala.versions' "$buildProps")" + versionString="${versionLine##build.scala.versions=}" + echo "${versionString%% .*}" + fi +} + +execRunner () { + # print the arguments one to a line, quoting any containing spaces + vlog "# Executing command line:" && { + for arg; do + if [[ -n "$arg" ]]; then + if printf "%s\n" "$arg" | grep -q ' '; then + printf >&2 "\"%s\"\n" "$arg" + else + printf >&2 "%s\n" "$arg" + fi + fi + done + vlog "" + } + + [[ -n "$batch" ]] && exec /dev/null; then + curl --fail --silent "$url" --output "$jar" + elif which wget >/dev/null; then + wget --quiet -O "$jar" "$url" + fi + } && [[ -r "$jar" ]] +} + +acquire_sbt_jar () { + sbt_url="$(jar_url "$sbt_version")" + sbt_jar="$(jar_file "$sbt_version")" + + [[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar" +} + +usage () { + cat < display stack traces with a max of frames (default: -1, traces suppressed) + -debug-inc enable debugging log for the incremental compiler + -no-colors disable ANSI color codes + -sbt-create start sbt even if current directory contains no sbt project + -sbt-dir path to global settings/plugins directory (default: ~/.sbt/) + -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11+) + -ivy path to local Ivy repository (default: ~/.ivy2) + -no-share use all local caches; no sharing + -offline put sbt in offline mode + -jvm-debug Turn on JVM debugging, open at the given port. + -batch Disable interactive mode + -prompt Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted + + # sbt version (default: sbt.version from $buildProps if present, otherwise $sbt_release_version) + -sbt-force-latest force the use of the latest release of sbt: $sbt_release_version + -sbt-version use the specified version of sbt (default: $sbt_release_version) + -sbt-dev use the latest pre-release version of sbt: $sbt_unreleased_version + -sbt-jar use the specified jar as the sbt launcher + -sbt-launch-dir directory to hold sbt launchers (default: ~/.sbt/launchers) + -sbt-launch-repo repo url for downloading sbt launcher jar (default: $sbt_launch_repo) + + # scala version (default: as chosen by sbt) + -28 use $latest_28 + -29 use $latest_29 + -210 use $latest_210 + -211 use $latest_211 + -scala-home use the scala build at the specified directory + -scala-version use the specified version of scala + -binary-version use the specified scala version when searching for dependencies + + # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) + -java-home alternate JAVA_HOME + + # passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution + # The default set is used if JVM_OPTS is unset and no -jvm-opts file is found + $(default_jvm_opts) + JVM_OPTS environment variable holding either the jvm args directly, or + the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts') + Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument. + -jvm-opts file containing jvm args (if not given, .jvmopts in project root is used if present) + -Dkey=val pass -Dkey=val directly to the jvm + -J-X pass option -X directly to the jvm (-J is stripped) + + # passing options to sbt, OR to this runner + SBT_OPTS environment variable holding either the sbt args directly, or + the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts') + Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument. + -sbt-opts file containing sbt args (if not given, .sbtopts in project root is used if present) + -S-X add -X to sbt's scalacOptions (-S is stripped) +EOM +} + +addJava () { + vlog "[addJava] arg = '$1'" + java_args=( "${java_args[@]}" "$1" ) +} +addSbt () { + vlog "[addSbt] arg = '$1'" + sbt_commands=( "${sbt_commands[@]}" "$1" ) +} +setThisBuild () { + vlog "[addBuild] args = '$@'" + local key="$1" && shift + addSbt "set $key in ThisBuild := $@" +} + +addScalac () { + vlog "[addScalac] arg = '$1'" + scalac_args=( "${scalac_args[@]}" "$1" ) +} +addResidual () { + vlog "[residual] arg = '$1'" + residual_args=( "${residual_args[@]}" "$1" ) +} +addResolver () { + addSbt "set resolvers += $1" +} +addDebugger () { + addJava "-Xdebug" + addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1" +} +setScalaVersion () { + [[ "$1" == *"-SNAPSHOT" ]] && addResolver 'Resolver.sonatypeRepo("snapshots")' + addSbt "++ $1" +} + +process_args () +{ + require_arg () { + local type="$1" + local opt="$2" + local arg="$3" + + if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then + die "$opt requires <$type> argument" + fi + } + while [[ $# -gt 0 ]]; do + case "$1" in + -h|-help) usage; exit 1 ;; + -v) verbose=true && shift ;; + -d) addSbt "--debug" && shift ;; + -w) addSbt "--warn" && shift ;; + -q) addSbt "--error" && shift ;; + -x) debugUs=true && shift ;; + -trace) require_arg integer "$1" "$2" && trace_level="$2" && shift 2 ;; + -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; + -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; + -no-share) noshare=true && shift ;; + -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; + -sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;; + -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; + -offline) addSbt "set offline := true" && shift ;; + -jvm-debug) require_arg port "$1" "$2" && addDebugger "$2" && shift 2 ;; + -batch) batch=true && shift ;; + -prompt) require_arg "expr" "$1" "$2" && setThisBuild shellPrompt "(s => { val e = Project.extract(s) ; $2 })" && shift 2 ;; + + -sbt-create) sbt_create=true && shift ;; + -sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;; + -sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;; + -sbt-force-latest) sbt_explicit_version="$sbt_release_version" && shift ;; + -sbt-dev) sbt_explicit_version="$sbt_unreleased_version" && shift ;; + -sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;; + -sbt-launch-repo) require_arg path "$1" "$2" && sbt_launch_repo="$2" && shift 2 ;; + -scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;; + -binary-version) require_arg version "$1" "$2" && setThisBuild scalaBinaryVersion "\"$2\"" && shift 2 ;; + -scala-home) require_arg path "$1" "$2" && setThisBuild scalaHome "Some(file(\"$2\"))" && shift 2 ;; + -java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;; + -sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;; + -jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;; + + -D*) addJava "$1" && shift ;; + -J*) addJava "${1:2}" && shift ;; + -S*) addScalac "${1:2}" && shift ;; + -28) setScalaVersion "$latest_28" && shift ;; + -29) setScalaVersion "$latest_29" && shift ;; + -210) setScalaVersion "$latest_210" && shift ;; + -211) setScalaVersion "$latest_211" && shift ;; + + *) addResidual "$1" && shift ;; + esac + done +} + +# process the direct command line arguments +process_args "$@" + +# skip #-styled comments and blank lines +readConfigFile() { + while read line; do + [[ $line =~ ^# ]] || [[ -z $line ]] || echo "$line" + done < "$1" +} + +# if there are file/environment sbt_opts, process again so we +# can supply args to this runner +if [[ -r "$sbt_opts_file" ]]; then + vlog "Using sbt options defined in file $sbt_opts_file" + while read opt; do extra_sbt_opts+=("$opt"); done < <(readConfigFile "$sbt_opts_file") +elif [[ -n "$SBT_OPTS" && ! ("$SBT_OPTS" =~ ^@.*) ]]; then + vlog "Using sbt options defined in variable \$SBT_OPTS" + extra_sbt_opts=( $SBT_OPTS ) +else + vlog "No extra sbt options have been defined" +fi + +[[ -n "${extra_sbt_opts[*]}" ]] && process_args "${extra_sbt_opts[@]}" + +# reset "$@" to the residual args +set -- "${residual_args[@]}" +argumentCount=$# + +# set sbt version +set_sbt_version + +# only exists in 0.12+ +setTraceLevel() { + case "$sbt_version" in + "0.7."* | "0.10."* | "0.11."* ) echoerr "Cannot set trace level in sbt version $sbt_version" ;; + *) setThisBuild traceLevel $trace_level ;; + esac +} + +# set scalacOptions if we were given any -S opts +[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\"" + +# Update build.properties on disk to set explicit version - sbt gives us no choice +[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version" +vlog "Detected sbt version $sbt_version" + +[[ -n "$scala_version" ]] && vlog "Overriding scala version to $scala_version" + +# no args - alert them there's stuff in here +(( argumentCount > 0 )) || { + vlog "Starting $script_name: invoke with -help for other options" + residual_args=( shell ) +} + +# verify this is an sbt dir or -create was given +[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || { + cat < diff --git a/src/main/resources/swagger-static/main.mustache b/modules/swagger-codegen/src/main/resources/swagger-static/main.mustache similarity index 100% rename from src/main/resources/swagger-static/main.mustache rename to modules/swagger-codegen/src/main/resources/swagger-static/main.mustache diff --git a/src/main/resources/swagger-static/model.mustache b/modules/swagger-codegen/src/main/resources/swagger-static/model.mustache similarity index 89% rename from src/main/resources/swagger-static/model.mustache rename to modules/swagger-codegen/src/main/resources/swagger-static/model.mustache index fd107aa1fef0..a9a39ab6e91c 100644 --- a/src/main/resources/swagger-static/model.mustache +++ b/modules/swagger-codegen/src/main/resources/swagger-static/model.mustache @@ -5,7 +5,7 @@ {{#vars}}
  • {{name}} : {{datatype}} -
    {description}} +
    {{description}}
{{/vars}} diff --git a/src/main/resources/swagger-static/operation.mustache b/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache similarity index 59% rename from src/main/resources/swagger-static/operation.mustache rename to modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache index 88db8645de83..d0e35f1b2963 100644 --- a/src/main/resources/swagger-static/operation.mustache +++ b/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache @@ -18,9 +18,31 @@
    {{#allParams}}
    + {{#isContainer}} + {{#complexType}} + + {{/complexType}} + {{#simpleType}} + +
    {{paramName}} : {{dataType}} ({{type}})
    + {{#optional}}optional{{/optional}} +
    + {{/simpleType}} + {{/isContainer}} + {{#isNotContainer}} + {{#simpleType}} + +
    {{paramName}} : {{dataType}} ({{type}})
    + {{#optional}}optional{{/optional}} + + {{/simpleType}} + {{/isNotContainer}} + + {{#foo}}
    {{paramName}} : {{#complexType}} 
    {{dataType}}{{/complexType}}{{#simpleType}}{{dataType}}{{/simpleType}} ({{type}})
    {{#optional}}optional{{/optional}}
    + {{/foo}}

    {{description}}

    {{/allParams}} diff --git a/src/main/resources/swagger-static/package.mustache b/modules/swagger-codegen/src/main/resources/swagger-static/package.mustache similarity index 100% rename from src/main/resources/swagger-static/package.mustache rename to modules/swagger-codegen/src/main/resources/swagger-static/package.mustache diff --git a/src/main/resources/swagger-static/pom.xml b/modules/swagger-codegen/src/main/resources/swagger-static/pom.xml similarity index 100% rename from src/main/resources/swagger-static/pom.xml rename to modules/swagger-codegen/src/main/resources/swagger-static/pom.xml diff --git a/modules/swagger-codegen/src/main/resources/tizen/README.md b/modules/swagger-codegen/src/main/resources/tizen/README.md new file mode 100644 index 000000000000..ec17473f00ff --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/README.md @@ -0,0 +1,2 @@ +https://github.com/Backendless/Tizen-Backendless-Geo-Service-Demo/blob/master/src/Backendless.cpp + diff --git a/modules/swagger-codegen/src/main/resources/tizen/api-body.mustache b/modules/swagger-codegen/src/main/resources/tizen/api-body.mustache new file mode 100644 index 000000000000..9573cc2b377f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/api-body.mustache @@ -0,0 +1,131 @@ +#include "{{classname}}.h" + +#include "{{prefix}}Helpers.h" +#include "{{prefix}}Error.h" + +using namespace Tizen::Base; + +namespace Swagger { + +{{#operations}} + +{{classname}}::{{classname}}() { + +} + +{{classname}}::~{{classname}}() { + +} + +{{#operation}} +void +{{nickname}}Processor(HttpResponse* pHttpResponse, void (* handler)(void*, {{prefix}}Error*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + {{#returnType}}ByteBuffer* pBuffer = pHttpResponse->ReadBodyN(); + IJsonValue* pJson = JsonParser::ParseN(*pBuffer); + + {{{returnType}}} out = {{{defaultResponse}}}; + jsonToValue(out, pJson, L"{{returnType}}", L"{{returnBaseType}}"); + + if (pJson) { + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + handler(out, null); + } + else { + {{prefix}}Error* error = new {{prefix}}Error(0, new String(L"No parsable response received")); + handler(null, error); + } + {{/returnType}}{{^returnType}}handler(null, null);{{/returnType}} + } + else { + {{prefix}}Error* error = new {{prefix}}Error(code, new String(pHttpResponse->GetStatusText())); + {{#returnType}}handler(null, error);{{/returnType}} + {{^returnType}}handler(error, null);{{/returnType}} + } +} + +{{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} +{{classname}}::{{nickname}}WithCompletion({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}},{{/hasParams}} {{#returnType}}void (* success)({{returnType}}, {{prefix}}Error*){{/returnType}}{{^returnType}}void(*success)({{prefix}}Error*){{/returnType}}) { + client = new {{prefix}}ApiClient(); + + client->success(&{{nickname}}Processor, (void(*)(void*, {{prefix}}Error*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + {{#headerParams}}{{#collectionFormat}} + int sz = {{paramName}}->GetCount(); + for(int i = 0; i < sz; i++) { + String itemAt = stringify({{paramName}}->GetAt(i), "{{baseType}}"); + headerParams->Add(new String("{{paramName}}"), new String(itemAt)); + } + {{/collectionFormat}}{{^collectionFormat}} + headerParams->Add(new String("{{baseName}}"), {{paramName}}); + {{/collectionFormat}} + {{/headerParams}} + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + {{#queryParams}}{{#collectionFormat}} + int sz = {{paramName}}->GetCount(); + for(int i = 0; i < sz; i++) { + String itemAt = stringify({{paramName}}->GetAt(i), "{{baseType}}"); + queryParams->Add(new String("{{paramName}}"), new String(itemAt)); + } + {{/collectionFormat}}{{^collectionFormat}} + queryParams->Add(new String("{{baseName}}"), {{paramName}}); + {{/collectionFormat}} + {{/queryParams}} + + String* mBody = null; + + {{#bodyParams}} + {{#isContainer}} + if({{paramName}} != null) { + mBody = new String(""); + int sz = {{paramName}}->GetCount(); + for(int i = 0; i < sz; i++) { + {{prefix}}Object * obj = ({{prefix}}Object*){{paramName}}->GetAt(i); + String json = obj->asJson(); + if(i > 0) + mBody->Append(","); + mBody->Append(json); + } + mBody->Append("]"); + headerParams->Add(new String("Content-Type"), new String("application/json")); + } + {{/isContainer}} + {{^isContainer}} + if({{paramName}} != null) { + mBody = new String({{paramName}}->asJson()); + headerParams->Add(new String("Content-Type"), new String("application/json")); + } + {{/isContainer}} + {{/bodyParams}} + + String url(L"{{{path}}}"); + + {{#pathParams}} + String s_{{paramName}}(L"{"); + s_{{paramName}}.Append(L"{{{baseName}}}"); + s_{{paramName}}.Append(L"}"); + url.Replace(s_{{paramName}}, stringify({{{paramName}}}, L"{{dataType}}")); + {{/pathParams}} + + client->execute({{classname}}::getBasePath(), url, "{{httpMethod}}", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + {{#returnType}}return null;{{/returnType}} +} + +{{/operation}} +{{/operations}} + +} /* namespace Swagger */ diff --git a/modules/swagger-codegen/src/main/resources/tizen/api-header.mustache b/modules/swagger-codegen/src/main/resources/tizen/api-header.mustache new file mode 100644 index 000000000000..2a1daf951587 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/api-header.mustache @@ -0,0 +1,37 @@ +#ifndef {{classname}}_H_ +#define {{classname}}_H_ + +#include +#include "{{prefix}}ApiClient.h" +#include "{{prefix}}Error.h" + +{{#imports}}{{{import}}} +{{/imports}} + +using namespace Tizen::Net::Http; + +namespace Swagger { + +{{#operations}} +class {{classname}} { +public: + {{classname}}(); + virtual ~{{classname}}(); + + {{#operation}} + {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} + {{nickname}}WithCompletion({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}},{{/hasParams}} {{#returnType}}void (* handler)({{returnType}}, {{prefix}}Error*){{/returnType}}{{^returnType}}void(* handler)({{prefix}}Error*){{/returnType}}); + {{/operation}} + static String getBasePath() { + return L"{{basePath}}"; + } + +private: + {{prefix}}ApiClient* client; +}; + + +{{/operations}} +} /* namespace Swagger */ + +#endif /* {{classname}}_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/tizen/apiclient-body.mustache b/modules/swagger-codegen/src/main/resources/tizen/apiclient-body.mustache new file mode 100644 index 000000000000..a8442e6b02e7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/apiclient-body.mustache @@ -0,0 +1,124 @@ +#include "{{prefix}}ApiClient.h" +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; + +namespace Swagger { + +{{prefix}}ApiClient::{{prefix}}ApiClient() { + enc = new Utf8Encoding(); +} + +void +{{prefix}}ApiClient::success(void (*success) (HttpResponse*, void (*cb)(void*, {{prefix}}Error*)), void (*cb)(void*, {{prefix}}Error*)) { + this->successFunction = success; + this->cb = cb; +} + +{{prefix}}ApiClient::~{{prefix}}ApiClient() { + if(enc) + delete enc; +} + +result +{{prefix}}ApiClient::execute(String host, String path, String method, IMap* queryParams, String* body, IMap* headerParams, IMap* formParams, String contentType) { + NetHttpMethod httpMethod; + if(method.Equals(L"GET", false)) { + httpMethod = NET_HTTP_METHOD_GET; + } + else if(method.Equals(L"PUT", false)) { + httpMethod = NET_HTTP_METHOD_PUT; + } + else if(method.Equals(L"POST", false)) { + httpMethod = NET_HTTP_METHOD_POST; + } + else if(method.Equals(L"DELETE", false)) { + httpMethod = NET_HTTP_METHOD_DELETE; + } + else if(method.Equals(L"OPTIONS", false)) { + httpMethod = NET_HTTP_METHOD_OPTIONS; + } + else if(method.Equals(L"HEAD", false)) { + httpMethod = NET_HTTP_METHOD_HEAD; + } + else if(method.Equals(L"TRACE", false)) { + httpMethod = NET_HTTP_METHOD_TRACE; + } + + String uri = String(host); + uri.Append(path); + + HttpSession* __pHttpSession = null; + HttpTransaction* pHttpTransaction = null; + HttpRequest* pHttpRequest = null; + + if (__pHttpSession == null) { + __pHttpSession = new (std::nothrow) HttpSession(); + __pHttpSession->Construct(NET_HTTP_SESSION_MODE_NORMAL, null, uri, null); + __pHttpSession->SetAutoRedirectionEnabled(true); + } + pHttpTransaction = __pHttpSession->OpenTransactionN(); + pHttpTransaction->AddHttpTransactionListener(*this); + + pHttpRequest = const_cast< HttpRequest* >(pHttpTransaction->GetRequest()); + + HttpHeader *pHeader = pHttpRequest->GetHeader(); + if(contentType != null && !contentType.Equals(L"", true)) { + pHeader->AddField(L"Accept", contentType); + } + if(queryParams != null) { + IMapEnumerator* pMapEnum = queryParams->GetMapEnumeratorN(); + String queryParam = L""; + while (pMapEnum->MoveNext() == E_SUCCESS) { + if(queryParam.GetLength() == 0) + queryParam.Append(L"?"); + else + queryParam.Append(L"&"); + + String* pKey = static_cast< String* > (pMapEnum->GetKey()); + String* pValue = static_cast< String* > (pMapEnum->GetValue()); + String encoded; + UrlEncoder::Encode(*pKey, L"UTF-8", encoded); + + queryParam.Append(encoded); + queryParam.Append("="); + UrlEncoder::Encode(*pValue, L"UTF-8", encoded); + queryParam.Append(encoded); + } + uri.Append(queryParam); + delete queryParams; + } + if(headerParams != null) { + IMapEnumerator* pMapEnum = headerParams->GetMapEnumeratorN(); + while (pMapEnum->MoveNext() == E_SUCCESS) { + String* pKey = static_cast< String* > (pMapEnum->GetKey()); + String* pValue = static_cast< String* > (pMapEnum->GetValue()); + pHeader->AddField(*pKey, *pValue); + } + delete headerParams; + } + if(body != null) { + HttpStringEntity * pEntity = new HttpStringEntity(); + String* cp = new String(*body); + result res = pEntity->Construct(*body, L"application/json", "utf-8", *enc); + res = pHttpRequest->SetEntity(*pEntity); + } + + pHttpRequest->SetUri(uri); + pHttpRequest->SetMethod(httpMethod); + + AppLog("%ls", uri.GetPointer()); + return pHttpTransaction->Submit(); +} + +void +{{prefix}}ApiClient::OnTransactionCompleted(HttpSession& httpSession, HttpTransaction& pHttpTransaction) { + HttpResponse* pHttpResponse = pHttpTransaction.GetResponse(); + + if(successFunction != null) { + successFunction(pHttpResponse, cb); + } + delete &httpSession; + delete &pHttpTransaction; +} + +} /* namespace Swagger */ diff --git a/modules/swagger-codegen/src/main/resources/tizen/apiclient-header.mustache b/modules/swagger-codegen/src/main/resources/tizen/apiclient-header.mustache new file mode 100644 index 000000000000..959e8cbb6f22 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/apiclient-header.mustache @@ -0,0 +1,73 @@ +#include + +#include "{{prefix}}Helpers.h" +#include "{{prefix}}Error.h" + +using namespace Tizen::Net::Http; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Text; + +#ifndef APICLIENT_H_ +#define APICLIENT_H_ + +namespace Swagger { + +class {{prefix}}ApiClient: public IHttpTransactionEventListener { +public: + {{prefix}}ApiClient(); + virtual ~{{prefix}}ApiClient(); + + result + execute(String host, String path, String method, IMap* queryParams, String* body, IMap* headerParams, IMap* formParams, String contentType); + + void success(void (*res) (HttpResponse*, void (*cb)(void*, {{prefix}}Error*)), void (*cb)(void*, {{prefix}}Error*)); + + virtual void + OnTransactionCompleted(HttpSession& httpSession, HttpTransaction& pHttpTransaction); + + virtual void + OnAudioInAudioFocusChanged(void) { + AppLog("OnAudioInAudioFocusChanged"); + } + + virtual void + OnTransactionCertVerificationRequiredN(HttpSession& httpSession, HttpTransaction& httpTransaction, + Tizen::Base::String* pCert) { + AppLog("OnTransactionCertVerificationRequiredN"); + httpTransaction.Resume(); + + delete pCert; + } + + virtual void + OnTransactionReadyToWrite(HttpSession& httpSession, HttpTransaction& httpTransaction, int recommendedChunkSize) { + AppLog("OnTransactionReadyToWrite"); + } + + virtual void + OnTransactionReadyToRead(HttpSession& httpSession, HttpTransaction& httpTransaction, int availableBodyLen) { + AppLog("OnTransactionReadyToRead"); + } + + virtual void + OnTransactionAborted(HttpSession& httpSession, HttpTransaction& httpTransaction, result r) { + AppLog("OnTransactionAborted: %ls", GetErrorMessage(r)); + delete &httpTransaction; + } + + virtual void + OnTransactionHeaderCompleted(HttpSession& httpSession, HttpTransaction& httpTransaction, int headerLen, bool + bAuthRequired) { + AppLog("OnTransactionHeaderCompleted"); +} + +private: + void (*successFunction) (HttpResponse*, void (*success)(void*, {{prefix}}Error*)); + void (*cb)(void*, {{prefix}}Error*); + Utf8Encoding* enc; +}; + + +} /* namespace Swagger */ +#endif /* APICLIENT_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/tizen/error-body.mustache b/modules/swagger-codegen/src/main/resources/tizen/error-body.mustache new file mode 100644 index 000000000000..6c169bdcee59 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/error-body.mustache @@ -0,0 +1,55 @@ +#include "{{prefix}}Error.h" + +using namespace Tizen::Base; +using namespace Tizen::System; + +namespace Swagger { + +{{prefix}}Error::{{prefix}}Error() { + init(); +} + +{{prefix}}Error::{{prefix}}Error(int code, String* message) { + init(); + this->setCode(code); + this->setMessage(message); +} + +{{prefix}}Error::~{{prefix}}Error() { + this->cleanup(); +} + +void +{{prefix}}Error::init() { + pCode = 0; + pMessage = null; +} + +void +{{prefix}}Error::cleanup() { + if(pMessage != null) { + delete pMessage; + pMessage = null; + } +} + +int +{{prefix}}Error::getCode() { + return pCode; +} +void +{{prefix}}Error::setCode(int pCode) { + this->pCode = pCode; +} + +String* +{{prefix}}Error::getMessage() { + return pMessage; +} +void +{{prefix}}Error::setMessage(String* pMessage) { + this->pMessage = pMessage; +} + +} /* namespace Swagger */ + diff --git a/modules/swagger-codegen/src/main/resources/tizen/error-header.mustache b/modules/swagger-codegen/src/main/resources/tizen/error-header.mustache new file mode 100644 index 000000000000..0e94b25d2679 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/error-header.mustache @@ -0,0 +1,35 @@ +#ifndef {{prefix}}Error_H_ +#define {{prefix}}Error_H_ + +#include + +using namespace Tizen::Base; + +namespace Swagger { + +class {{prefix}}Error { +public: + {{prefix}}Error(); + {{prefix}}Error(int code, String* message); + virtual ~{{prefix}}Error(); + + + void init(); + + void cleanup(); + + int getCode(); + void setCode(int pCode); + + String* getMessage(); + void setMessage(String* pMessage); + + +private: + int pCode; + String* pMessage; +}; + +} /* namespace Swagger */ + +#endif /* {{prefix}}Error_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/tizen/helpers-body.mustache b/modules/swagger-codegen/src/main/resources/tizen/helpers-body.mustache new file mode 100644 index 000000000000..67dfd5ce022a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/helpers-body.mustache @@ -0,0 +1,273 @@ +#include "{{prefix}}Helpers.h" +#include "{{prefix}}ModelFactory.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; +using namespace Tizen::Web::Json; +using namespace Tizen::Locales; +using namespace Tizen::System; + +namespace Swagger { + JsonObject* + toJson(void* ptr, String type, String containerType) { + if(ptr == null) + return null; + if(containerType != null && !type.Equals(L"", false)) { + if(containerType.Equals(L"array", false)) { + if(type != null) { + IList* list = static_cast< IList* >(ptr); + JsonArray* array = new JsonArray(); + int sz = list->GetCount(); + for(int i = 0; i < sz; i++) { + void* itemAt = list->GetAt(i); + JsonObject* item = toJson(itemAt, type, null); + if(item != null) + array->Add(item); + } + return (JsonObject*)array; + } + return null; + } + } + else if(type.Equals(L"Boolean", false)) { + Boolean* v = static_cast< Boolean* >(ptr); + return (JsonObject*) new JsonBool(*v); + } + else if(type.Equals(L"String", false)) { + String* v = static_cast< String* >(ptr); + return (JsonObject*) new JsonString(*v); + } + else if(type.Equals(L"Integer", false)) { + Integer* v = static_cast< Integer* >(ptr); + return (JsonObject*) new JsonNumber(v->ToInt()); + } + else if(type.Equals(L"Long", false)) { + Long* v = static_cast< Long* >(ptr); + return (JsonObject*) new JsonNumber(v->ToInt()); + } + else if(type.Equals(L"Float", false)) { + Float* v = static_cast< Float* >(ptr); + return (JsonObject*) new JsonNumber(v->ToFloat()); + } + else if(type.Equals(L"Double", false)) { + Double* v = static_cast< Double* >(ptr); + return (JsonObject*) new JsonNumber(v->ToDouble()); + } + else if(type.Equals(L"DateTime", false)) { + DateTime* v = static_cast< DateTime* >(ptr); + DateTimeFormatter* pFormatter = DateTimeFormatter::CreateDateTimeFormatterN(); + String date; + pFormatter->ApplyPattern(L"yyyy-MM-dd"); + pFormatter->Format(*v, date); + + String time; + pFormatter->ApplyPattern(L"hh:mm:ss"); + pFormatter->Format(*v, time); + String formattedString = date + "T" + time; + delete pFormatter; + return (JsonObject*)new JsonString(formattedString); + } + else if(type.StartsWith(L"{{prefix}}", 0)) { + {{prefix}}Object* obj = static_cast< {{prefix}}Object* >(ptr); + return obj->asJsonObject(); + } + return null; + } + + void + toISO8601(String str, DateTime* dt) { + int idx, start; + int year, month, day, hour, minute, second; + + start = 0; + str.IndexOf(L"-", start, idx); + String yearString; + str.SubString(0, idx, yearString); + Integer::Parse(yearString, year); + + start = idx+1; + str.IndexOf(L"-", start, idx); + String monthString; + str.SubString(start, idx - start, monthString); + Integer::Parse(monthString, month); + + start = idx+1; + str.IndexOf(L"T", start, idx); + String dayString; + str.SubString(start, idx - start, dayString); + Integer::Parse(dayString, day); + + start = idx+1; + str.IndexOf(L":", start, idx); + if(idx > 0) { + String hourString; + str.SubString(start, idx - start, hourString); + Integer::Parse(hourString, hour); + } + + start = idx+1; + str.IndexOf(L":", start, idx); + if(idx > 0) { + String minuteString; + str.SubString(start, idx - start, minuteString); + Integer::Parse(minuteString, minute); + } + + start = idx+1; + str.IndexOf(L"+", start, idx); + if(idx > 0) { + String secondString; + str.SubString(start, idx - start, secondString); + Integer::Parse(secondString, second); + } + + dt->SetValue(year, month, day, hour, minute, second); + } + + void + jsonToValue(void* target, IJsonValue* ptr, String type, String innerType) { + if(target == null || ptr == null) { + return; + } + if(type.StartsWith(L"Boolean", 0)) { + JsonBool* json = static_cast< JsonBool* >(ptr); + Boolean* val = static_cast< Boolean* > (target); + val->value = json->ToBool(); + } + else if(type.StartsWith(L"String", 0)) { + JsonString* json = static_cast< JsonString* >(ptr); + String* val = static_cast< String* > (target); + val->Clear(); + val->Append(json->GetPointer()); + } + else if(type.StartsWith(L"Integer", 0)) { + JsonNumber* json = static_cast< JsonNumber* >(ptr); + Integer* val = static_cast< Integer* > (target); + *val = json->ToInt(); + } + else if(type.StartsWith(L"Long", 0)) { + JsonNumber* json = static_cast< JsonNumber* >(ptr); + Long* val = static_cast< Long* > (target); + *val = json->ToLong(); + } + else if(type.StartsWith(L"DateTime", 0)) { + JsonString* json = static_cast< JsonString* >(ptr); + String str; + str.Append(json->GetPointer()); + + DateTime* val = static_cast< DateTime* > (target); + toISO8601(str, val); + } + else if(type.StartsWith(L"{{prefix}}", 0)) { + {{prefix}}Object* obj = static_cast< {{prefix}}Object* > (target); + obj->fromJsonObject(ptr); + } + else if(type.StartsWith(L"IList", 0)) { + IList* obj = static_cast< IList* >(target); + JsonArray* pJsonArray = static_cast< JsonArray* >(ptr); + + IEnumeratorT< IJsonValue* >* pEnum = pJsonArray->GetEnumeratorN(); + while (pEnum->MoveNext() == E_SUCCESS) { + IJsonValue* pJsonValue = null; + pEnum->GetCurrent(pJsonValue); + void* updatedTarget = null; + updatedTarget = create(innerType); + + if(updatedTarget != null) { + jsonToValue(updatedTarget, pJsonValue, innerType, L""); + obj->Add((Object*)updatedTarget); + } + } + delete pEnum; + } + } + + Integer* + jsonToInteger(IJsonValue* value) { + if(value == null) + return null; + switch(value->GetType()) { + case JSON_TYPE_STRING: + break; + case JSON_TYPE_NUMBER: { + JsonNumber* number = static_cast< JsonNumber* >(value); + int num = number->ToInt(); + return new Integer(num); + } + case JSON_TYPE_OBJECT: + break; + case JSON_TYPE_ARRAY: + break; + case JSON_TYPE_BOOL: + break; + case JSON_TYPE_NULL: + break; + } + return null; + } + + Long* + jsonToLong(IJsonValue* value) { + if(value == null) + return null; + switch(value->GetType()) { + case JSON_TYPE_STRING: + break; + case JSON_TYPE_NUMBER: { + JsonNumber* number = static_cast< JsonNumber* >(value); + long int num = number->ToLong(); + return new Long(num); + } + case JSON_TYPE_OBJECT: + break; + case JSON_TYPE_ARRAY: + break; + case JSON_TYPE_BOOL: + break; + case JSON_TYPE_NULL: + break; + } + return null; + } + + String* + jsonToString(IJsonValue* value) { + if(value == null) + return null; + switch(value->GetType()) { + case JSON_TYPE_STRING: { + JsonString* string = static_cast< JsonString* >(value); + return new String(string->GetPointer()); + } + case JSON_TYPE_NUMBER: + break; + case JSON_TYPE_OBJECT: + break; + case JSON_TYPE_ARRAY: + break; + case JSON_TYPE_BOOL: + break; + case JSON_TYPE_NULL: + break; + } + return null; + } + + String + stringify(void* ptr, String type) { + if(type.StartsWith(L"String", 0)) { + String * str = static_cast< String* > (ptr); + return String(str->GetPointer()); + } + if(type.StartsWith(L"Integer", 0)) { + Integer* pInt = static_cast< Integer* > (ptr); + return pInt->ToString(); + } + if(type.StartsWith(L"Long", 0)) { + Long* pLong = static_cast< Long* > (ptr); + return pLong->ToString(); + } + return L""; + } +} /* namespace Swagger */ diff --git a/modules/swagger-codegen/src/main/resources/tizen/helpers-header.mustache b/modules/swagger-codegen/src/main/resources/tizen/helpers-header.mustache new file mode 100644 index 000000000000..a897e097ca5f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/helpers-header.mustache @@ -0,0 +1,45 @@ +#ifndef HELPERS_H_ +#define HELPERS_H_ + +#include +#include +#include +#include +#include +#include "{{prefix}}Helpers.h" +#include "{{prefix}}Object.h" + +using Tizen::Base::String; +using Tizen::Base::DateTime; +using namespace Tizen::Web::Json; +using namespace Tizen::Base::Collection; + +using Tizen::Base::Long; +using Tizen::Base::DateTime; +using Tizen::Base::String; +using Tizen::Base::Integer; + +namespace Swagger { +JsonObject* +toJson(void* v, String type, String containerType); + +void +jsonToValue(void* target, IJsonValue* ptr, String type, String innerType); + +Integer* +jsonToInteger(IJsonValue* value); + +Long* +jsonToLong(IJsonValue* value); + +String* +jsonToString(IJsonValue* value); + +DateTime* +jsonToDateTime(IJsonValue* value); + +String +stringify(void* ptr, String type); + +} /* namespace Swagger */ +#endif /* HELPERS_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/tizen/model-body.mustache b/modules/swagger-codegen/src/main/resources/tizen/model-body.mustache new file mode 100644 index 000000000000..a8387a15a163 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/model-body.mustache @@ -0,0 +1,158 @@ +{{#models}}{{#model}} +#include "{{classname}}.h" +#include + +using namespace Tizen::Base; +using namespace Tizen::System; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; +using namespace Tizen::Web::Json; +using namespace Tizen::Locales; + + +namespace Swagger { + +{{classname}}::{{classname}}() { + init(); +} + +{{classname}}::~{{classname}}() { + this->cleanup(); +} + +void +{{classname}}::init() { + {{#vars}}{{name}} = null; + {{/vars}} +} + +void +{{classname}}::cleanup() { + {{#vars}}if({{name}} != null) { + {{#isContainer}}{{name}}->RemoveAll(true);{{/isContainer}} + delete {{name}}; + {{name}} = null; + } + {{/vars}} +} + + +{{classname}}* +{{classname}}::fromJson(String* json) { + this->cleanup(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; + return this; +} + + +void +{{classname}}::fromJsonObject(IJsonValue* pJson) { + JsonObject* pJsonObject = static_cast< JsonObject* >(pJson); + + if(pJsonObject != null) { + {{#vars}}JsonString* {{name}}Key = new JsonString(L"{{baseName}}"); + IJsonValue* {{name}}Val = null; + pJsonObject->GetValue({{name}}Key, {{name}}Val); + if({{name}}Val != null) { + {{#isContainer}}{{name}} = {{defaultValue}};{{/isContainer}} + {{#isNotContainer}}{{name}} = {{defaultValue}};{{/isNotContainer}} + jsonToValue({{name}}, {{name}}Val, L"{{baseType}}", L"{{complexType}}"); + } + delete {{name}}Key; + {{/vars}} + } +} + +{{classname}}::{{classname}}(String* json) { + init(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; +} + +String +{{classname}}::asJson () +{ + JsonObject* pJsonObject = asJsonObject(); + + char *pComposeBuf = new char[256]; + JsonWriter::Compose(pJsonObject, pComposeBuf, 256); + String s = String(pComposeBuf); + + delete pComposeBuf; + pJsonObject->RemoveAll(true); + delete pJsonObject; + + return s; +} + +JsonObject* +{{classname}}::asJsonObject() { + JsonObject *pJsonObject = new JsonObject(); + pJsonObject->Construct(); + + {{#vars}} + JsonString *{{name}}Key = new JsonString(L"{{baseName}}"); + pJsonObject->Add({{name}}Key, toJson({{getter}}(), "{{complexType}}", "{{containerType}}")); + + {{/vars}} + return pJsonObject; +} + +{{#vars}} +{{datatype}} +{{classname}}::{{getter}}() { + return {{name}}; +} +void +{{classname}}::{{setter}}({{datatype}} {{name}}) { + this->{{name}} = {{name}}; +} + +{{/vars}} + + +} /* namespace Swagger */ + +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/tizen/model-header.mustache b/modules/swagger-codegen/src/main/resources/tizen/model-header.mustache new file mode 100644 index 000000000000..1a2a831f5ac2 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/model-header.mustache @@ -0,0 +1,58 @@ +{{#models}}{{#model}}/* + * {{classname}}.h + * + * {{description}} + */ + +#ifndef {{classname}}_H_ +#define {{classname}}_H_ + +#include +#include +#include +#include +#include "{{prefix}}Helpers.h" +#include "{{prefix}}Object.h" + +using namespace Tizen::Web::Json; + +{{/model}}{{/models}} +{{#imports}}{{{import}}} +{{/imports}} + +{{#models}}{{#model}} +namespace Swagger { + +class {{classname}}: public {{prefix}}Object { +public: + {{classname}}(); + {{classname}}(String* json); + virtual ~{{classname}}(); + + void init(); + + void cleanup(); + + String asJson (); + + JsonObject* asJsonObject(); + + void fromJsonObject(IJsonValue* json); + + {{classname}}* fromJson(String* obj); + + {{#vars}} + {{datatype}} {{getter}}(); + void {{setter}}({{datatype}} {{name}}); + {{/vars}} + +private: + {{#vars}}{{datatype}} {{name}}; + {{/vars}} +}; + +} /* namespace Swagger */ + +#endif /* {{classname}}_H_ */ +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/tizen/modelFactory.mustache b/modules/swagger-codegen/src/main/resources/tizen/modelFactory.mustache new file mode 100644 index 000000000000..395203bde6b3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/modelFactory.mustache @@ -0,0 +1,31 @@ +#ifndef ModelFactory_H_ +#define ModelFactory_H_ + +#include "{{prefix}}Object.h" +{{#models}}{{#model}} +#include "{{classname}}.h"{{/model}}{{/models}} + +namespace Swagger { + void* + create(String type) { + {{#models}}{{#model}}if(type.Equals(L"{{classname}}", true)) { + return new {{classname}}(); + } + {{/model}}{{/models}} + if(type.Equals(L"String", true)) { + return new String(); + } + if(type.Equals(L"Integer", true)) { + return new Integer(); + } + if(type.Equals(L"Long", true)) { + return new Long(); + } + if(type.Equals(L"DateTime", true)) { + return new DateTime(); + } + return null; + } +} /* namespace Swagger */ + +#endif /* ModelFactory_H_ */ diff --git a/modules/swagger-codegen/src/main/resources/tizen/object.mustache b/modules/swagger-codegen/src/main/resources/tizen/object.mustache new file mode 100644 index 000000000000..8cbbe07fb617 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/tizen/object.mustache @@ -0,0 +1,27 @@ +#ifndef _{{prefix}}_OBJECT_H_ +#define _{{prefix}}_OBJECT_H_ + +#include +#include +#include + +using Tizen::Base::String; + +using namespace Tizen::Web::Json; + +class {{prefix}}Object { + public: + virtual JsonObject* asJsonObject() { + return null; + } + virtual ~{{prefix}}Object() {} + virtual {{prefix}}Object* fromJson(String* obj) { + return null; + } + virtual void fromJsonObject(IJsonValue* obj) {} + virtual String asJson() { + return L""; + } +}; + +#endif /* _{{prefix}}_OBJECT_H_ */ diff --git a/src/main/resources/validator/index.mustache b/modules/swagger-codegen/src/main/resources/validator/index.mustache similarity index 100% rename from src/main/resources/validator/index.mustache rename to modules/swagger-codegen/src/main/resources/validator/index.mustache diff --git a/src/test/resources/petstore-1.2/api-docs b/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/api-docs similarity index 100% rename from src/test/resources/petstore-1.2/api-docs rename to modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/api-docs diff --git a/src/test/resources/petstore-1.2/pet b/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/pet similarity index 100% rename from src/test/resources/petstore-1.2/pet rename to modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/pet diff --git a/src/test/resources/petstore-1.2/store b/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/store similarity index 98% rename from src/test/resources/petstore-1.2/store rename to modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/store index f7670669dfe4..e59994447cda 100644 --- a/src/test/resources/petstore-1.2/store +++ b/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/store @@ -112,6 +112,7 @@ "models": { "Order": { "id": "Order", + "description": "an order in the system", "properties": { "id": { "type": "integer", diff --git a/src/test/resources/petstore-1.2/user b/modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/user similarity index 100% rename from src/test/resources/petstore-1.2/user rename to modules/swagger-codegen/src/test/resources/1_2/petstore-1.2/user diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json new file mode 100644 index 000000000000..1f6089f1c5ae --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -0,0 +1,965 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://helloreverb.com/terms/", + "contact": { + "email": "apiteam@wordnik.com" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "schemes": [ + "http" + ], + "paths": { + "/pet": { + "post": { + "tags": [ + "pet" + ], + "summary": "Add a new pet to the store", + "description": "", + "operationId": "addPet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": false, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "put": { + "tags": [ + "pet" + ], + "summary": "Update an existing pet", + "description": "", + "operationId": "updatePet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": false, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Validation exception" + }, + "404": { + "description": "Pet not found" + }, + "400": { + "description": "Invalid ID supplied" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByStatus": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by status", + "description": "Multiple status values can be provided with comma seperated strings", + "operationId": "findPetsByStatus", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Status values that need to be considered for filter", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi", + "default": "available" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid status value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByTags": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by tags", + "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "operationId": "findPetsByTags", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "Tags to filter by", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid tag value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}": { + "get": { + "tags": [ + "pet" + ], + "summary": "Find pet by ID", + "description": "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", + "operationId": "getPetById", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "404": { + "description": "Pet not found" + }, + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "400": { + "description": "Invalid ID supplied" + } + }, + "security": [ + { + "api_key": [] + }, + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "post": { + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "string" + }, + { + "name": "name", + "in": "formData", + "description": "Updated name of the pet", + "required": false, + "type": "string" + }, + { + "name": "status", + "in": "formData", + "description": "Updated status of the pet", + "required": false, + "type": "string" + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "delete": { + "tags": [ + "pet" + ], + "summary": "Deletes a pet", + "description": "", + "operationId": "deletePet", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "api_key", + "in": "header", + "description": "", + "required": false, + "type": "string" + }, + { + "name": "petId", + "in": "path", + "description": "Pet id to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid pet value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}/uploadImage": { + "post": { + "tags": [ + "pet" + ], + "summary": "uploads an image", + "description": "", + "operationId": "uploadFile", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to update", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "additionalMetadata", + "in": "formData", + "description": "Additional data to pass to server", + "required": false, + "type": "string" + }, + { + "name": "file", + "in": "formData", + "description": "file to upload", + "required": false, + "type": "file" + } + ], + "responses": { + "default": { + "description": "successful operation" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/store/inventory": { + "get": { + "tags": [ + "store" + ], + "summary": "Returns pet inventories by status", + "description": "Returns a map of status codes to quantities", + "operationId": "getInventory", + "produces": [ + "application/json", + "application/xml" + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + } + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/store/order": { + "post": { + "tags": [ + "store" + ], + "summary": "Place an order for a pet", + "description": "", + "operationId": "placeOrder", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "order placed for purchasing the pet", + "required": false, + "schema": { + "$ref": "#/definitions/Order" + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid Order" + } + } + } + }, + "/store/order/{orderId}": { + "get": { + "tags": [ + "store" + ], + "summary": "Find purchase order by ID", + "description": "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + "operationId": "getOrderById", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "Order not found" + }, + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid ID supplied" + } + } + }, + "delete": { + "tags": [ + "store" + ], + "summary": "Delete purchase order by ID", + "description": "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "operationId": "deleteOrder", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of the order that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "Order not found" + }, + "400": { + "description": "Invalid ID supplied" + } + } + } + }, + "/user": { + "post": { + "tags": [ + "user" + ], + "summary": "Create user", + "description": "This can only be done by the logged in user.", + "operationId": "createUser", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Created user object", + "required": false, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithArray": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithArrayInput", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithList": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithListInput", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/login": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs user into the system", + "description": "", + "operationId": "loginUser", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "username", + "in": "query", + "description": "The user name for login", + "required": false, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The password for login in clear text", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "string" + } + }, + "400": { + "description": "Invalid username/password supplied" + } + } + } + }, + "/user/logout": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs out current logged in user session", + "description": "", + "operationId": "logoutUser", + "produces": [ + "application/json", + "application/xml" + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/{username}": { + "get": { + "tags": [ + "user" + ], + "summary": "Get user by user name", + "description": "", + "operationId": "getUserByName", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be fetched. Use user1 for testing. ", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/User" + } + }, + "400": { + "description": "Invalid username supplied" + } + } + }, + "put": { + "tags": [ + "user" + ], + "summary": "Updated user", + "description": "This can only be done by the logged in user.", + "operationId": "updateUser", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "name that need to be deleted", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "description": "Updated user object", + "required": false, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid user supplied" + } + } + }, + "delete": { + "tags": [ + "user" + ], + "summary": "Delete user", + "description": "This can only be done by the logged in user.", + "operationId": "deleteUser", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid username supplied" + } + } + } + } + }, + "securityDefinitions": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + }, + "definitions": { + "User": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "username": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "userStatus": { + "type": "integer", + "format": "int32", + "description": "User Status" + } + }, + "xml": { + "name": "User" + } + }, + "Category": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Category" + } + }, + "Pet": { + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "#/definitions/Category" + }, + "name": { + "type": "string", + "example": "doggie" + }, + "photoUrls": { + "type": "array", + "xml": { + "name": "photoUrl", + "wrapped": true + }, + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "xml": { + "name": "tag", + "wrapped": true + }, + "items": { + "$ref": "#/definitions/Tag" + } + }, + "status": { + "type": "string", + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ] + } + }, + "xml": { + "name": "Pet" + } + }, + "Tag": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Tag" + } + }, + "Order": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "petId": { + "type": "integer", + "format": "int64" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "shipDate": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "description": "Order Status", + "enum": [ + "placed", + "approved", + "delivered" + ] + }, + "complete": { + "type": "boolean" + } + }, + "xml": { + "name": "Order" + } + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/2_0/postBodyTest.json b/modules/swagger-codegen/src/test/resources/2_0/postBodyTest.json new file mode 100644 index 000000000000..e2a917c67444 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/postBodyTest.json @@ -0,0 +1,102 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://helloreverb.com/terms/", + "contact": { + "name": "apiteam@wordnik.com" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "schemes": [ + "http" + ], + "paths": { + "/animals": { + "post": { + "tags": [ + "pet" + ], + "summary": "Add a new animal to the store", + "description": "", + "consumes": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "pet", + "description": "Animals", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Animal" + } + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + } + } + }, + "/insects": { + "post": { + "tags": [ + "pet" + ], + "summary": "Add a new insect to the store", + "description": "", + "consumes": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "pet", + "description": "Insects", + "required": false, + "schema": { + "$ref": "#/definitions/Insect" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + } + } + } + }, + "definitions": { + "Animal": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + } + } + }, + "Insect": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + } + } + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/2_0/wordnik.json b/modules/swagger-codegen/src/test/resources/2_0/wordnik.json new file mode 100644 index 000000000000..d201b15c5df1 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/wordnik.json @@ -0,0 +1,2456 @@ +{ + "swagger": "2.0", + "info": { + "title": "The Wordnik Public API", + "version": "4.0" + }, + "host": "api.wordnik.com", + "basePath": "/v4", + "schemes": [ + "https" + ], + "security": [ + { + "apiKey": [] + } + ], + "paths": { + "/account.json/apiTokenStatus": { + "get": { + "tags": [ + "account" + ], + "summary": "Returns usage statistics for the API account.", + "operationId": "getApiTokenStatus", + "parameters": [ + { + "name": "api_key", + "in": "header", + "description": "Wordnik authentication token", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "Usage statistics for the supplied API key", + "schema": { + "$ref": "#/definitions/ApiTokenStatus" + } + }, + "400": { + "description": "No token supplied." + }, + "404": { + "description": "No API account with supplied token." + } + } + } + }, + "/account.json/authenticate/{username}": { + "get": { + "tags": [ + "account" + ], + "summary": "Authenticates a User", + "operationId": "authenticate", + "parameters": [ + { + "name": "username", + "in": "path", + "description": "A confirmed Wordnik username", + "required": true, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The user's password", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "A valid authentication token", + "schema": { + "$ref": "#/definitions/AuthenticationToken" + } + }, + "403": { + "description": "Account not available." + }, + "404": { + "description": "User not found." + } + } + }, + "post": { + "tags": [ + "account" + ], + "summary": "Authenticates a user", + "operationId": "authenticatePost", + "parameters": [ + { + "name": "username", + "in": "path", + "description": "A confirmed Wordnik username", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "schema": { + "type": "string" + }, + "description": "The user's password", + "required": true + } + ], + "responses": { + "200": { + "description": "A valid authentication token", + "schema": { + "$ref": "#/definitions/AuthenticationToken" + } + }, + "403": { + "description": "Account not available." + }, + "404": { + "description": "User not found." + } + } + } + }, + "/account.json/user": { + "get": { + "tags": [ + "account" + ], + "summary": "Returns the logged-in User", + "description": "Requires a valid auth_token to be set.", + "operationId": "getLoggedInUser", + "parameters": [ + { + "name": "auth_token", + "in": "header", + "description": "The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "The logged-in user", + "schema": { + "$ref": "#/definitions/User" + } + }, + "403": { + "description": "Not logged in." + }, + "404": { + "description": "User not found." + } + } + } + }, + "/account.json/wordLists": { + "get": { + "tags": [ + "account" + ], + "summary": "Fetches WordList objects for the logged-in user.", + "operationId": "getWordListsForLoggedInUser", + "parameters": [ + { + "name": "auth_token", + "in": "header", + "description": "auth_token of logged-in user", + "required": true, + "type": "string" + }, + { + "name": "skip", + "in": "query", + "description": "Results to skip", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "limit", + "in": "query", + "description": "Maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/WordList" + } + } + }, + "403": { + "description": "Not authenticated." + }, + "404": { + "description": "User account not found." + } + } + } + }, + "/word.json/{word}": { + "get": { + "tags": [ + "word" + ], + "summary": "Given a word as a string, returns the WordObject that represents it", + "operationId": "getWord", + "parameters": [ + { + "name": "word", + "in": "path", + "description": "String value of WordObject to return", + "required": true, + "type": "string" + }, + { + "name": "useCanonical", + "in": "query", + "description": "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", + "required": false, + "type": "string" + }, + { + "name": "includeSuggestions", + "in": "query", + "description": "Return suggestions (for correct spelling, case variants, etc.)", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/WordObject" + } + }, + "400": { + "description": "Invalid word supplied." + } + } + } + }, + "/word.json/{word}/audio": { + "get": { + "tags": [ + "word" + ], + "summary": "Fetches audio metadata for a word.", + "description": "The metadata includes a time-expiring fileUrl which allows reading the audio file directly from the API. Currently only audio pronunciations from the American Heritage Dictionary in mp3 format are supported.", + "operationId": "getAudio", + "parameters": [ + { + "name": "word", + "in": "path", + "description": "Word to get audio for.", + "required": true, + "type": "string" + }, + { + "name": "useCanonical", + "in": "query", + "description": "Use the canonical form of the word", + "required": false, + "type": "string" + }, + { + "name": "limit", + "in": "query", + "description": "Maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/AudioFile" + } + } + }, + "400": { + "description": "Invalid word supplied." + } + } + } + }, + "/word.json/{word}/definitions": { + "get": { + "tags": [ + "word" + ], + "summary": "Return definitions for a word", + "operationId": "getDefinitions", + "parameters": [ + { + "name": "word", + "in": "path", + "description": "Word to return definitions for", + "required": true, + "type": "string" + }, + { + "name": "limit", + "in": "query", + "description": "Maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "partOfSpeech", + "in": "query", + "description": "CSV list of part-of-speech types", + "required": false, + "type": "string" + }, + { + "name": "includeRelated", + "in": "query", + "description": "Return related words with definitions", + "required": false, + "type": "string" + }, + { + "name": "sourceDictionaries", + "in": "query", + "description": "Source dictionary to return definitions from. If 'all' is received, results are returned from all sources. If multiple values are received (e.g. 'century,wiktionary'), results are returned from the first specified dictionary that has definitions. If left blank, results are returned from the first dictionary that has definitions. By default, dictionaries are searched in this order: ahd, wiktionary, webster, century, wordnet", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv" + }, + { + "name": "useCanonical", + "in": "query", + "description": "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", + "required": false, + "type": "string" + }, + { + "name": "includeTags", + "in": "query", + "description": "Return a closed set of XML tags in response", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Definition" + } + } + }, + "400": { + "description": "Invalid word supplied." + }, + "404": { + "description": "No definitions found." + } + } + } + }, + "/word.json/{word}/etymologies": { + "get": { + "tags": [ + "word" + ], + "summary": "Fetches etymology data", + "operationId": "getEtymologies", + "parameters": [ + { + "name": "word", + "in": "path", + "description": "Word to return", + "required": true, + "type": "string" + }, + { + "name": "useCanonical", + "in": "query", + "description": "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "400": { + "description": "Invalid word supplied." + }, + "404": { + "description": "No definitions found." + } + } + } + }, + "/word.json/{word}/examples": { + "get": { + "tags": [ + "word" + ], + "summary": "Returns examples for a word", + "operationId": "getExamples", + "parameters": [ + { + "name": "word", + "in": "path", + "description": "Word to return examples for", + "required": true, + "type": "string" + }, + { + "name": "includeDuplicates", + "in": "query", + "description": "Show duplicate examples from different sources", + "required": false, + "type": "string" + }, + { + "name": "useCanonical", + "in": "query", + "description": "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", + "required": false, + "type": "string" + }, + { + "name": "skip", + "in": "query", + "description": "Results to skip", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "limit", + "in": "query", + "description": "Maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "success", + "$ref": "/definitions/ExampleSearchResults" + }, + "400": { + "description": "Invalid word supplied." + } + } + } + }, + "/word.json/{word}/frequency": { + "get": { + "tags": [ + "word" + ], + "summary": "Returns word usage over time", + "operationId": "getWordFrequency", + "parameters": [ + { + "name": "word", + "in": "path", + "description": "Word to return", + "required": true, + "type": "string" + }, + { + "name": "useCanonical", + "in": "query", + "description": "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", + "required": false, + "type": "string" + }, + { + "name": "startYear", + "in": "query", + "description": "Starting Year", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "endYear", + "in": "query", + "description": "Ending Year", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/FrequencySummary" + } + }, + "400": { + "description": "Invalid word supplied." + }, + "404": { + "description": "No results." + } + } + } + }, + "/word.json/{word}/hyphenation": { + "get": { + "tags": [ + "word" + ], + "summary": "Returns syllable information for a word", + "operationId": "getHyphenation", + "parameters": [ + { + "name": "word", + "in": "path", + "description": "Word to get syllables for", + "required": true, + "type": "string" + }, + { + "name": "useCanonical", + "in": "query", + "description": "If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", + "required": false, + "type": "string" + }, + { + "name": "sourceDictionary", + "in": "query", + "description": "Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet.", + "required": false, + "type": "string" + }, + { + "name": "limit", + "in": "query", + "description": "Maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "success", + "type": "array", + "items": { + "schema": { + "$ref": "#/definitions/Syllable" + } + } + }, + "400": { + "description": "Invalid word supplied." + } + } + } + }, + "/word.json/{word}/phrases": { + "get": { + "tags": [ + "word" + ], + "summary": "Fetches bi-gram phrases for a word", + "operationId": "getPhrases", + "parameters": [ + { + "name": "word", + "in": "path", + "description": "Word to fetch phrases for", + "required": true, + "type": "string" + }, + { + "name": "limit", + "in": "query", + "description": "Maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "wlmi", + "in": "query", + "description": "Minimum WLMI for the phrase", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "useCanonical", + "in": "query", + "description": "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Bigram" + } + } + }, + "400": { + "description": "Invalid word supplied." + } + } + } + }, + "/word.json/{word}/pronunciations": { + "get": { + "tags": [ + "word" + ], + "summary": "Returns text pronunciations for a given word", + "operationId": "getTextPronunciations", + "parameters": [ + { + "name": "word", + "in": "path", + "description": "Word to get pronunciations for", + "required": true, + "type": "string" + }, + { + "name": "useCanonical", + "in": "query", + "description": "If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", + "required": false, + "type": "string" + }, + { + "name": "sourceDictionary", + "in": "query", + "description": "Get from a single dictionary", + "required": false, + "type": "string" + }, + { + "name": "typeFormat", + "in": "query", + "description": "Text pronunciation type", + "required": false, + "type": "string" + }, + { + "name": "limit", + "in": "query", + "description": "Maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "success", + "type": "array", + "items": { + "schema": { + "$ref": "#/definitions/TextPron" + } + } + }, + "400": { + "description": "Invalid word supplied." + } + } + } + }, + "/word.json/{word}/relatedWords": { + "get": { + "tags": [ + "word" + ], + "summary": "Given a word as a string, returns relationships from the Word Graph", + "operationId": "getRelatedWords", + "parameters": [ + { + "name": "word", + "in": "path", + "description": "Word to fetch relationships for", + "required": true, + "type": "string" + }, + { + "name": "useCanonical", + "in": "query", + "description": "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", + "required": false, + "type": "string" + }, + { + "name": "relationshipTypes", + "in": "query", + "description": "Limits the total results per type of relationship type", + "required": false, + "type": "string" + }, + { + "name": "limitPerRelationshipType", + "in": "query", + "description": "Restrict to the supplied relationship types", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "success", + "type": "array", + "items": { + "schema": { + "$ref": "#/definitions/Related" + } + } + }, + "400": { + "description": "Invalid word supplied." + } + } + } + }, + "/word.json/{word}/topExample": { + "get": { + "tags": [ + "word" + ], + "summary": "Returns a top example for a word", + "operationId": "getTopExample", + "parameters": [ + { + "name": "word", + "in": "path", + "description": "Word to fetch examples for", + "required": true, + "type": "string" + }, + { + "name": "useCanonical", + "in": "query", + "description": "If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/Example" + } + }, + "400": { + "description": "Invalid word supplied." + } + } + } + }, + "/wordList.json/{permalink}": { + "get": { + "tags": [ + "wordList" + ], + "summary": "Fetches a WordList by ID", + "operationId": "getWordListByPermalink", + "parameters": [ + { + "name": "permalink", + "in": "path", + "description": "permalink of WordList to fetch", + "required": true, + "type": "string" + }, + { + "name": "auth_token", + "in": "header", + "description": "The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/WordList" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "403": { + "description": "Not Authorized to access WordList" + }, + "404": { + "description": "WordList not found" + } + } + }, + "put": { + "tags": [ + "wordList" + ], + "summary": "Updates an existing WordList", + "operationId": "updateWordList", + "parameters": [ + { + "name": "permalink", + "in": "path", + "description": "permalink of WordList to update", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "description": "Updated WordList", + "required": false, + "schema": { + "$ref": "#/definitions/WordList" + } + }, + { + "name": "auth_token", + "in": "header", + "description": "The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success" + }, + "400": { + "description": "Invalid ID supplied" + }, + "403": { + "description": "Not Authorized to update WordList" + }, + "404": { + "description": "WordList not found" + } + } + }, + "delete": { + "tags": [ + "wordList" + ], + "summary": "Deletes an existing WordList", + "operationId": "deleteWordList", + "parameters": [ + { + "name": "permalink", + "in": "path", + "description": "ID of WordList to delete", + "required": true, + "type": "string" + }, + { + "name": "auth_token", + "in": "header", + "description": "The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success" + }, + "400": { + "description": "Invalid ID supplied" + }, + "403": { + "description": "Not Authorized to delete WordList" + }, + "404": { + "description": "WordList not found" + } + } + } + }, + "/wordList.json/{permalink}/deleteWords": { + "post": { + "tags": [ + "wordList" + ], + "summary": "Removes words from a WordList", + "operationId": "deleteWordsFromWordList", + "parameters": [ + { + "name": "permalink", + "in": "path", + "description": "permalink of WordList to use", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "description": "Words to remove from WordList", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/StringValue" + } + } + }, + { + "name": "auth_token", + "in": "header", + "description": "The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success" + }, + "400": { + "description": "Invalid permalink supplied" + }, + "403": { + "description": "Not Authorized to modify WordList" + }, + "404": { + "description": "WordList not found" + } + } + } + }, + "/wordList.json/{permalink}/words": { + "get": { + "tags": [ + "wordList" + ], + "summary": "Fetches words in a WordList", + "operationId": "getWordListWords", + "parameters": [ + { + "name": "permalink", + "in": "path", + "description": "ID of WordList to use", + "required": true, + "type": "string" + }, + { + "name": "sortBy", + "in": "query", + "description": "Field to sort by", + "required": false, + "type": "string" + }, + { + "name": "sortOrder", + "in": "query", + "description": "Direction to sort", + "required": false, + "type": "string" + }, + { + "name": "skip", + "in": "query", + "description": "Results to skip", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "limit", + "in": "query", + "description": "Maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "auth_token", + "in": "header", + "description": "The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success", + "type": "array", + "items": { + "schema": { + "$ref": "#/definitions/WordListWord" + } + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "403": { + "description": "Not Authorized to access WordList" + }, + "404": { + "description": "WordList not found" + } + } + }, + "post": { + "tags": [ + "wordList" + ], + "summary": "Adds words to a WordList", + "operationId": "addWordsToWordList", + "parameters": [ + { + "name": "permalink", + "in": "path", + "description": "permalink of WordList to user", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "description": "Array of words to add to WordList", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/StringValue" + } + } + }, + { + "name": "auth_token", + "in": "header", + "description": "The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success" + }, + "400": { + "description": "Invalid permalink supplied" + }, + "403": { + "description": "Not Authorized to access WordList" + }, + "404": { + "description": "WordList not found" + } + } + } + }, + "/wordLists.json": { + "post": { + "tags": [ + "wordLists" + ], + "summary": "Creates a WordList.", + "operationId": "createWordList", + "parameters": [ + { + "in": "body", + "name": "body", + "description": "WordList to create", + "required": false, + "schema": { + "$ref": "#/definitions/WordList" + } + }, + { + "name": "auth_token", + "in": "header", + "description": "The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/WordList" + } + }, + "400": { + "description": "Invalid WordList supplied or mandatory fields are missing" + }, + "403": { + "description": "Not authenticated" + }, + "404": { + "description": "WordList owner not found" + } + } + } + }, + "/words.json/randomWord": { + "get": { + "tags": [ + "words" + ], + "summary": "Returns a single random WordObject", + "operationId": "getRandomWord", + "parameters": [ + { + "name": "hasDictionaryDef", + "in": "query", + "description": "Only return words with dictionary definitions", + "required": false, + "type": "string" + }, + { + "name": "includePartOfSpeech", + "in": "query", + "description": "CSV part-of-speech values to include", + "required": false, + "type": "string" + }, + { + "name": "excludePartOfSpeech", + "in": "query", + "description": "CSV part-of-speech values to exclude", + "required": false, + "type": "string" + }, + { + "name": "minCorpusCount", + "in": "query", + "description": "Minimum corpus frequency for terms", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "maxCorpusCount", + "in": "query", + "description": "Maximum corpus frequency for terms", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "minDictionaryCount", + "in": "query", + "description": "Minimum dictionary count", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "maxDictionaryCount", + "in": "query", + "description": "Maximum dictionary count", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "minLength", + "in": "query", + "description": "Minimum word length", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "maxLength", + "in": "query", + "description": "Maximum word length", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/WordObject" + } + }, + "404": { + "description": "No word found." + } + } + } + }, + "/words.json/randomWords": { + "get": { + "tags": [ + "words" + ], + "summary": "Returns an array of random WordObjects", + "operationId": "getRandomWords", + "parameters": [ + { + "name": "hasDictionaryDef", + "in": "query", + "description": "Only return words with dictionary definitions", + "required": false, + "type": "string" + }, + { + "name": "includePartOfSpeech", + "in": "query", + "description": "CSV part-of-speech values to include", + "required": false, + "type": "string" + }, + { + "name": "excludePartOfSpeech", + "in": "query", + "description": "CSV part-of-speech values to exclude", + "required": false, + "type": "string" + }, + { + "name": "minCorpusCount", + "in": "query", + "description": "Minimum corpus frequency for terms", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "maxCorpusCount", + "in": "query", + "description": "Maximum corpus frequency for terms", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "minDictionaryCount", + "in": "query", + "description": "Minimum dictionary count", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "maxDictionaryCount", + "in": "query", + "description": "Maximum dictionary count", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "minLength", + "in": "query", + "description": "Minimum word length", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "maxLength", + "in": "query", + "description": "Maximum word length", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "sortBy", + "in": "query", + "description": "Attribute to sort by", + "required": false, + "type": "string" + }, + { + "name": "sortOrder", + "in": "query", + "description": "Sort direction", + "required": false, + "type": "string" + }, + { + "name": "limit", + "in": "query", + "description": "Maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "success", + "type": "array", + "items": { + "schema": { + "$ref": "#/definitions/WordObject" + } + } + }, + "400": { + "description": "Invalid term supplied." + }, + "404": { + "description": "No results." + } + } + } + }, + "/words.json/reverseDictionary": { + "get": { + "tags": [ + "words" + ], + "summary": "Reverse dictionary search", + "operationId": "reverseDictionary", + "parameters": [ + { + "name": "query", + "in": "query", + "description": "Search term", + "required": true, + "type": "string" + }, + { + "name": "findSenseForWord", + "in": "query", + "description": "Restricts words and finds closest sense", + "required": false, + "type": "string" + }, + { + "name": "includeSourceDictionaries", + "in": "query", + "description": "Only include these comma-delimited source dictionaries", + "required": false, + "type": "string" + }, + { + "name": "excludeSourceDictionaries", + "in": "query", + "description": "Exclude these comma-delimited source dictionaries", + "required": false, + "type": "string" + }, + { + "name": "includePartOfSpeech", + "in": "query", + "description": "Only include these comma-delimited parts of speech", + "required": false, + "type": "string" + }, + { + "name": "excludePartOfSpeech", + "in": "query", + "description": "Exclude these comma-delimited parts of speech", + "required": false, + "type": "string" + }, + { + "name": "minCorpusCount", + "in": "query", + "description": "Minimum corpus frequency for terms", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "maxCorpusCount", + "in": "query", + "description": "Maximum corpus frequency for terms", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "minLength", + "in": "query", + "description": "Minimum word length", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "maxLength", + "in": "query", + "description": "Maximum word length", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "expandTerms", + "in": "query", + "description": "Expand terms", + "required": false, + "type": "string" + }, + { + "name": "includeTags", + "in": "query", + "description": "Return a closed set of XML tags in response", + "required": false, + "type": "string" + }, + { + "name": "sortBy", + "in": "query", + "description": "Attribute to sort by", + "required": false, + "type": "string" + }, + { + "name": "sortOrder", + "in": "query", + "description": "Sort direction", + "required": false, + "type": "string" + }, + { + "name": "skip", + "in": "query", + "description": "Results to skip", + "required": false, + "type": "string" + }, + { + "name": "limit", + "in": "query", + "description": "Maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/DefinitionSearchResults" + } + }, + "400": { + "description": "Invalid term supplied." + } + } + } + }, + "/words.json/search/{query}": { + "get": { + "tags": [ + "words" + ], + "summary": "Searches words", + "operationId": "searchWords", + "parameters": [ + { + "name": "query", + "in": "path", + "description": "Search query", + "required": true, + "type": "string" + }, + { + "name": "caseSensitive", + "in": "query", + "description": "Search case sensitive", + "required": false, + "type": "string" + }, + { + "name": "includePartOfSpeech", + "in": "query", + "description": "Only include these comma-delimited parts of speech", + "required": false, + "type": "string" + }, + { + "name": "excludePartOfSpeech", + "in": "query", + "description": "Exclude these comma-delimited parts of speech", + "required": false, + "type": "string" + }, + { + "name": "minCorpusCount", + "in": "query", + "description": "Minimum corpus frequency for terms", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "maxCorpusCount", + "in": "query", + "description": "Maximum corpus frequency for terms", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "minDictionaryCount", + "in": "query", + "description": "Minimum number of dictionary entries for words returned", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "maxDictionaryCount", + "in": "query", + "description": "Maximum dictionary definition count", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "minLength", + "in": "query", + "description": "Minimum word length", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "maxLength", + "in": "query", + "description": "Maximum word length", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "skip", + "in": "query", + "description": "Results to skip", + "required": false, + "type": "integer", + "format": "int32" + }, + { + "name": "limit", + "in": "query", + "description": "Maximum number of results to return", + "required": false, + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "success", + "schema": { + "$ref": "#/definitions/WordSearchResults" + } + }, + "400": { + "description": "Invalid query supplied." + } + } + } + }, + "/words.json/wordOfTheDay": { + "get": { + "tags": [ + "words" + ], + "summary": "Returns a specific WordOfTheDay", + "operationId": "getWordOfTheDay", + "parameters": [ + { + "name": "date", + "in": "query", + "description": "Fetches by date in yyyy-MM-dd", + "required": false, + "type": "string" + } + ], + "responses": { + "default": { + "description": "success", + "schema": { + "$ref": "#/definitions/WordOfTheDay" + } + } + } + } + } + }, + "definitions": { + "User": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "username": { + "type": "string" + }, + "email": { + "type": "string" + }, + "status": { + "type": "integer", + "format": "int32" + }, + "faceBookId": { + "type": "string" + }, + "userName": { + "type": "string" + }, + "displayName": { + "type": "string" + }, + "password": { + "type": "string" + } + } + }, + "Syllable": { + "properties": { + "text": { + "type": "string" + }, + "seq": { + "type": "integer", + "format": "int32" + }, + "type": { + "type": "string" + } + } + }, + "AudioType": { + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string" + } + } + }, + "WordOfTheDay": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "parentId": { + "type": "string" + }, + "category": { + "type": "string" + }, + "createdBy": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "contentProvider": { + "$ref": "#/definitions/ContentProvider" + }, + "htmlExtra": { + "type": "string" + }, + "word": { + "type": "string" + }, + "definitions": { + "type": "array", + "items": { + "$ref": "#/definitions/SimpleDefinition" + } + }, + "examples": { + "type": "array", + "items": { + "$ref": "#/definitions/SimpleExample" + } + }, + "note": { + "type": "string" + }, + "publishDate": { + "type": "string", + "format": "date-time" + } + } + }, + "Facet": { + "properties": { + "facetValues": { + "type": "array", + "items": { + "$ref": "#/definitions/FacetValue" + } + }, + "name": { + "type": "string" + } + } + }, + "WordObject": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "word": { + "type": "string" + }, + "originalWord": { + "type": "string" + }, + "suggestions": { + "type": "array", + "items": { + "type": "string" + } + }, + "canonicalForm": { + "type": "string" + }, + "vulgar": { + "type": "string" + } + } + }, + "WordSearchResults": { + "properties": { + "searchResults": { + "type": "array", + "items": { + "$ref": "#/definitions/WordSearchResult" + } + }, + "totalResults": { + "type": "integer", + "format": "int32" + } + } + }, + "AuthenticationToken": { + "properties": { + "token": { + "type": "string" + }, + "userId": { + "type": "integer", + "format": "int64" + }, + "userSignature": { + "type": "string" + } + } + }, + "ExampleSearchResults": { + "properties": { + "facets": { + "type": "array", + "items": { + "$ref": "#/definitions/Facet" + } + }, + "examples": { + "type": "array", + "items": { + "$ref": "#/definitions/Example" + } + } + } + }, + "Example": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "exampleId": { + "type": "integer", + "format": "int64" + }, + "title": { + "type": "string" + }, + "text": { + "type": "string" + }, + "score": { + "$ref": "#/definitions/ScoredWord" + }, + "sentence": { + "$ref": "#/definitions/Sentence" + }, + "word": { + "type": "string" + }, + "provider": { + "$ref": "#/definitions/ContentProvider" + }, + "year": { + "type": "integer", + "format": "int32" + }, + "rating": { + "type": "number", + "format": "float" + }, + "documentId": { + "type": "integer", + "format": "int64" + }, + "url": { + "type": "string" + } + } + }, + "SimpleDefinition": { + "properties": { + "text": { + "type": "string" + }, + "source": { + "type": "string" + }, + "note": { + "type": "string" + }, + "partOfSpeech": { + "type": "string" + } + } + }, + "ExampleUsage": { + "properties": { + "text": { + "type": "string" + } + } + }, + "AudioFile": { + "properties": { + "attributionUrl": { + "type": "string" + }, + "commentCount": { + "type": "integer", + "format": "int32" + }, + "voteCount": { + "type": "integer", + "format": "int32" + }, + "fileUrl": { + "type": "string" + }, + "audioType": { + "type": "string" + }, + "id": { + "type": "integer", + "format": "int64" + }, + "duration": { + "type": "number", + "format": "double" + }, + "attributionText": { + "type": "string" + }, + "createdBy": { + "type": "string" + }, + "description": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "voteWeightedAverage": { + "type": "number", + "format": "float" + }, + "voteAverage": { + "type": "number", + "format": "float" + }, + "word": { + "type": "string" + } + } + }, + "WordListWord": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "word": { + "type": "string" + }, + "username": { + "type": "string" + }, + "userId": { + "type": "integer", + "format": "int64" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "numberCommentsOnWord": { + "type": "integer", + "format": "int64" + }, + "numberLists": { + "type": "integer", + "format": "int64" + } + } + }, + "Bigram": { + "properties": { + "count": { + "type": "integer", + "format": "int64" + }, + "gram2": { + "type": "string" + }, + "gram1": { + "type": "string" + }, + "wlmi": { + "type": "number", + "format": "double" + }, + "mi": { + "type": "number", + "format": "double" + } + } + }, + "Frequency": { + "properties": { + "count": { + "type": "integer", + "format": "int64" + }, + "year": { + "type": "integer", + "format": "int32" + } + } + }, + "TextPron": { + "properties": { + "raw": { + "type": "string" + }, + "seq": { + "type": "integer", + "format": "int32" + }, + "rawType": { + "type": "string" + } + } + }, + "ApiTokenStatus": { + "properties": { + "valid": { + "type": "boolean" + }, + "token": { + "type": "string" + }, + "resetsInMillis": { + "type": "integer", + "format": "int64" + }, + "remainingCalls": { + "type": "integer", + "format": "int64" + }, + "expiresInMillis": { + "type": "integer", + "format": "int64" + }, + "totalRequests": { + "type": "integer", + "format": "int64" + } + } + }, + "WordList": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "permalink": { + "type": "string" + }, + "name": { + "type": "string" + }, + "createdAt": { + "type": "string", + "format": "date-time" + }, + "updatedAt": { + "type": "string", + "format": "date-time" + }, + "lastActivityAt": { + "type": "string", + "format": "date-time" + }, + "username": { + "type": "string" + }, + "userId": { + "type": "integer", + "format": "int64" + }, + "description": { + "type": "string" + }, + "numberWordsInList": { + "type": "integer", + "format": "int64" + }, + "type": { + "type": "string" + } + } + }, + "WordSearchResult": { + "properties": { + "count": { + "type": "integer", + "format": "int64" + }, + "lexicality": { + "type": "number", + "format": "double" + }, + "word": { + "type": "string" + } + } + }, + "DefinitionSearchResults": { + "properties": { + "results": { + "type": "array", + "items": { + "$ref": "#/definitions/Definition" + } + }, + "totalResults": { + "type": "integer", + "format": "int32" + } + } + }, + "Note": { + "properties": { + "noteType": { + "type": "string" + }, + "appliesTo": { + "type": "array", + "items": { + "type": "string" + } + }, + "value": { + "type": "string" + }, + "pos": { + "type": "integer", + "format": "int32" + } + } + }, + "StringValue": { + "properties": { + "word": { + "type": "string" + } + } + }, + "Related": { + "properties": { + "label1": { + "type": "string" + }, + "relationshipType": { + "type": "string" + }, + "label2": { + "type": "string" + }, + "label3": { + "type": "string" + }, + "words": { + "type": "array", + "items": { + "type": "string" + } + }, + "gram": { + "type": "string" + }, + "label4": { + "type": "string" + } + } + }, + "FacetValue": { + "properties": { + "count": { + "type": "integer", + "format": "int64" + }, + "value": { + "type": "string" + } + } + }, + "ScoredWord": { + "properties": { + "position": { + "type": "integer", + "format": "int32" + }, + "id": { + "type": "integer", + "format": "int64" + }, + "docTermCount": { + "type": "integer", + "format": "int32" + }, + "lemma": { + "type": "string" + }, + "wordType": { + "type": "string" + }, + "score": { + "type": "number", + "format": "float" + }, + "sentenceId": { + "type": "integer", + "format": "int64" + }, + "word": { + "type": "string" + }, + "stopword": { + "type": "boolean" + }, + "baseWordScore": { + "type": "number", + "format": "double" + }, + "partOfSpeech": { + "type": "string" + } + } + }, + "Citation": { + "properties": { + "cite": { + "type": "string" + }, + "source": { + "type": "string" + } + } + }, + "Category": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "Root": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + }, + "categories": { + "type": "array", + "items": { + "$ref": "#/definitions/Category" + } + } + } + }, + "Sentence": { + "properties": { + "hasScoredWords": { + "type": "boolean" + }, + "id": { + "type": "integer", + "format": "int64" + }, + "scoredWords": { + "type": "array", + "items": { + "$ref": "#/definitions/ScoredWord" + } + }, + "display": { + "type": "string" + }, + "rating": { + "type": "integer", + "format": "int32" + }, + "documentMetadataId": { + "type": "integer", + "format": "int64" + } + } + }, + "ContentProvider": { + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string" + } + } + }, + "Label": { + "properties": { + "text": { + "type": "string" + }, + "type": { + "type": "string" + } + } + }, + "SimpleExample": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "title": { + "type": "string" + }, + "text": { + "type": "string" + }, + "url": { + "type": "string" + } + } + }, + "PartOfSpeech": { + "properties": { + "roots": { + "type": "array", + "items": { + "$ref": "#/definitions/Root" + } + }, + "storageAbbr": { + "type": "array", + "items": { + "type": "string" + } + }, + "allCategories": { + "type": "array", + "items": { + "$ref": "#/definitions/Category" + } + } + } + }, + "Definition": { + "properties": { + "extendedText": { + "type": "string" + }, + "text": { + "type": "string" + }, + "sourceDictionary": { + "type": "string" + }, + "citations": { + "type": "array", + "items": { + "$ref": "#/definitions/Citation" + } + }, + "labels": { + "type": "array", + "items": { + "$ref": "#/definitions/Label" + } + }, + "score": { + "type": "number", + "format": "float" + }, + "exampleUses": { + "type": "array", + "items": { + "$ref": "#/definitions/ExampleUsage" + } + }, + "attributionUrl": { + "type": "string" + }, + "seqString": { + "type": "string" + }, + "attributionText": { + "type": "string" + }, + "relatedWords": { + "type": "array", + "items": { + "$ref": "#/definitions/Related" + } + }, + "sequence": { + "type": "string" + }, + "word": { + "type": "string" + }, + "notes": { + "type": "array", + "items": { + "$ref": "#/definitions/Note" + } + }, + "textProns": { + "type": "array", + "items": { + "$ref": "#/definitions/TextPron" + } + }, + "partOfSpeech": { + "type": "string" + } + } + }, + "FrequencySummary": { + "properties": { + "unknownYearCount": { + "type": "integer", + "format": "int32" + }, + "totalCount": { + "type": "integer", + "format": "int64" + }, + "frequencyString": { + "type": "string" + }, + "word": { + "type": "string" + }, + "frequency": { + "type": "array", + "items": { + "$ref": "#/definitions/Frequency" + } + } + } + } + }, + "securityDefinitions": { + "apiKey": { + "type": "apiKey", + "in": "header", + "name": "api_key" + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/ClientAuthInputTest.scala b/modules/swagger-codegen/src/test/scala/ClientAuthInputTest.scala new file mode 100644 index 000000000000..83c3be06f937 --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/ClientAuthInputTest.scala @@ -0,0 +1,44 @@ +import com.wordnik.swagger.codegen._ + +import com.wordnik.swagger.models.auth.AuthorizationValue + +import org.junit.runner.RunWith +import org.scalatest.junit.JUnitRunner +import org.scalatest.FlatSpec +import org.scalatest.Matchers + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class ClientAuthInputTest extends FlatSpec with Matchers { + behavior of "ClientAuthInput" + + it should "read a file upload param from a 2.0 spec" in { + val input = new ClientOptInput() + + val header = "api_key:special-key,api_key:hello,X-AUTHORIZATION:0e6c11d79a,Authorization:Basic 1jz0" + input.setAuth(header) + val authValues = input.getAuthorizationValues() + authValues.size() should be (4) + + val a1 = authValues.get(0) + a1.getKeyName should be ("api_key") + a1.getValue should be ("special-key") + a1.getType should be ("header") + + val a2 = authValues.get(1) + a2.getKeyName should be ("api_key") + a2.getValue should be ("hello") + a2.getType should be ("header") + + val a3 = authValues.get(2) + a3.getKeyName should be ("X-AUTHORIZATION") + a3.getValue should be ("0e6c11d79a") + a3.getType should be ("header") + + val a4 = authValues.get(3) + a4.getKeyName should be ("Authorization") + a4.getValue should be ("Basic 1jz0") + a4.getType should be ("header") + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/CodegenTest.scala b/modules/swagger-codegen/src/test/scala/CodegenTest.scala new file mode 100644 index 000000000000..a9ccbd9f0f2c --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/CodegenTest.scala @@ -0,0 +1,97 @@ +import com.wordnik.swagger.models._ +import com.wordnik.swagger.util.Json +import io.swagger.parser._ + +import com.wordnik.swagger.codegen.DefaultCodegen + +import org.junit.runner.RunWith +import org.scalatest.junit.JUnitRunner +import org.scalatest.FlatSpec +import org.scalatest.Matchers + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class CodegenTest extends FlatSpec with Matchers { + behavior of "Codegen" + + it should "read a file upload param from a 2.0 spec" in { + val model = new SwaggerParser() + .read("src/test/resources/2_0/petstore.json") + + val codegen = new DefaultCodegen() + val path = "/pet/{petId}/uploadImage" + val p = model.getPaths().get(path).getPost() + val op = codegen.fromOperation(path, "post", p) + + op.operationId should be ("uploadFile") + op.httpMethod should be ("POST") + op.hasConsumes should equal (true) + op.consumes.size should be(1) + op.consumes.get(0).get("mediaType") should be ("multipart/form-data") + + op.hasProduces should equal (true) + val allParams = op.allParams + allParams.size should be (3) + + val formParams = op.formParams + formParams.size should be (2) + + val file = formParams.get(1) + file.isFormParam should equal (true) + file.dataType should be ("file") + file.required should equal (false) + file.isFile should equal (true) + file.hasMore should be (null) + } + + it should "read formParam values from a 2.0 spec" in { + val model = new SwaggerParser() + .read("src/test/resources/2_0/petstore.json") + + val codegen = new DefaultCodegen() + val path = "/pet/{petId}" + val p = model.getPaths().get(path).getPost() + val op = codegen.fromOperation(path, "post", p) + + op.operationId should be ("updatePetWithForm") + op.httpMethod should be ("POST") + op.hasConsumes should equal (true) + op.consumes.size should be(1) + op.consumes.get(0).get("mediaType") should be ("application/x-www-form-urlencoded") + + op.hasProduces should equal (true) + op.produces.size should be(2) + op.produces.get(0).get("mediaType") should be ("application/json") + op.produces.get(0).get("hasMore") should be ("true") + op.produces.get(1).get("mediaType") should be ("application/xml") + + val pathParams = op.pathParams + pathParams.size should be (1) + + val idParam = pathParams.get(0) + idParam.isPathParam should equal (true) + idParam.dataType should be ("String") + idParam.required should equal (true) + idParam.hasMore should be (null) + + val allParams = op.allParams + allParams.size should be (3) + + val formParams = op.formParams + formParams.size should be (2) + val nameParam = formParams.get(0) + nameParam.isFormParam should equal (true) + nameParam.notFile should equal (true) + nameParam.dataType should be ("String") + nameParam.required should equal (false) + nameParam.hasMore should equal (true) + + val statusParam = formParams.get(1) + statusParam.isFormParam should equal (true) + statusParam.notFile should equal (true) + statusParam.dataType should be ("String") + statusParam.required should equal (false) + statusParam.hasMore should be (null) + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala new file mode 100644 index 000000000000..e621b18565dd --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala @@ -0,0 +1,34 @@ +package Java + +import com.wordnik.swagger.codegen.languages.JavaClientCodegen +import com.wordnik.swagger.models._ +import com.wordnik.swagger.models.properties._ +import org.junit.runner.RunWith +import org.scalatest.{FlatSpec, Matchers} +import org.scalatest.junit.JUnitRunner + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class JavaModelEnumTest extends FlatSpec with Matchers { + + it should "convert a java model with an enum" in { + val enumProperty = new StringProperty() + enumProperty.setEnum(List("VALUE1", "VALUE2", "VALUE3").asJava) + val model = new ModelImpl() + .property("name", enumProperty) + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.vars.size should be(1) + val enumVar = cm.vars.get(0) + enumVar.baseName should be ("name") + enumVar.datatype should be ("String") + enumVar.datatypeWithEnum should be("NameEnum") + enumVar.name should be("name") + enumVar.defaultValue should be("null") + enumVar.baseType should be("String") + enumVar.isEnum should equal(true) + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala new file mode 100644 index 000000000000..513786e4609b --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala @@ -0,0 +1,268 @@ +package Java + +import com.wordnik.swagger.codegen.languages.JavaClientCodegen +import com.wordnik.swagger.util.Json +import com.wordnik.swagger.models._ +import com.wordnik.swagger.models.properties._ + +import org.junit.runner.RunWith +import org.scalatest.junit.JUnitRunner +import org.scalatest.FlatSpec +import org.scalatest.Matchers + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class JavaModelTest extends FlatSpec with Matchers { + + it should "convert a simple java model" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name") + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (3) + + val vars = cm.vars + vars.get(0).baseName should be ("id") + vars.get(0).getter should be ("getId") + vars.get(0).setter should be ("setId") + vars.get(0).datatype should be ("Long") + vars.get(0).name should be ("id") + vars.get(0).defaultValue should be ("null") + vars.get(0).baseType should be ("Long") + vars.get(0).hasMore should equal (true) + vars.get(0).required should equal (true) + vars.get(0).isNotContainer should equal (true) + + vars.get(1).baseName should be ("name") + vars.get(1).getter should be ("getName") + vars.get(1).setter should be ("setName") + vars.get(1).datatype should be ("String") + vars.get(1).name should be ("name") + vars.get(1).defaultValue should be ("null") + vars.get(1).baseType should be ("String") + vars.get(1).hasMore should equal (true) + vars.get(1).required should equal (true) + vars.get(1).isNotContainer should equal (true) + + vars.get(2).baseName should be ("createdAt") + vars.get(2).getter should be ("getCreatedAt") + vars.get(2).setter should be ("setCreatedAt") + vars.get(2).datatype should be ("Date") + vars.get(2).name should be ("createdAt") + vars.get(2).defaultValue should be ("null") + vars.get(2).baseType should be ("Date") + vars.get(2).hasMore should equal (null) + vars.get(2).required should equal (false) + vars.get(2).isNotContainer should equal (true) + } + + it should "convert a model with list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty() + .items(new StringProperty())) + .required("id") + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (2) + + val vars = cm.vars + vars.get(1).baseName should be ("urls") + vars.get(1).getter should be ("getUrls") + vars.get(1).setter should be ("setUrls") + vars.get(1).datatype should be ("List") + vars.get(1).name should be ("urls") + vars.get(1).defaultValue should be ("new ArrayList() ") + vars.get(1).baseType should be ("List") + vars.get(1).containerType should be ("array") + vars.get(1).required should equal (false) + vars.get(1).isContainer should equal (true) + } + + it should "convert a model with a map property" in { + val model = new ModelImpl() + .description("a sample model") + .property("translations", new MapProperty() + .additionalProperties(new StringProperty())) + .required("id") + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("translations") + vars.get(0).getter should be ("getTranslations") + vars.get(0).setter should be ("setTranslations") + vars.get(0).datatype should be ("Map") + vars.get(0).name should be ("translations") + vars.get(0).defaultValue should be ("new HashMap() ") + vars.get(0).baseType should be ("Map") + vars.get(0).containerType should be ("map") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + } + + it should "convert a model with complex properties" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")) + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).getter should be ("getChildren") + vars.get(0).setter should be ("setChildren") + vars.get(0).datatype should be ("Children") + vars.get(0).name should be ("children") + vars.get(0).defaultValue should be ("null") + vars.get(0).baseType should be ("Children") + vars.get(0).required should equal (false) + vars.get(0).isNotContainer should equal (true) + } + + it should "convert a model with complex list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))) + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).complexType should be ("Children") + vars.get(0).getter should be ("getChildren") + vars.get(0).setter should be ("setChildren") + vars.get(0).datatype should be ("List") + vars.get(0).name should be ("children") + vars.get(0).defaultValue should be ("new ArrayList() ") + vars.get(0).baseType should be ("List") + vars.get(0).containerType should be ("array") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + } + + it should "convert a model with complex map property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new MapProperty() + .additionalProperties(new RefProperty("#/definitions/Children"))) + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + (cm.imports.asScala.toSet & Set("Map", "List", "Children")).size should be (3) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).complexType should be ("Children") + vars.get(0).getter should be ("getChildren") + vars.get(0).setter should be ("setChildren") + vars.get(0).datatype should be ("Map") + vars.get(0).name should be ("children") + vars.get(0).defaultValue should be ("new HashMap() ") + vars.get(0).baseType should be ("Map") + vars.get(0).containerType should be ("map") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + vars.get(0).isNotContainer should be (null) + } + + it should "convert an array model" in { + val model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")) + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("an array model") + cm.vars.size should be (0) + cm.parent should be ("ArrayList") + cm.imports.size should be (3) + (cm.imports.asScala.toSet & Set("List", "ArrayList", "Children")).size should be (3) + } + + it should "convert an map model" in { + val model = new ModelImpl() + .description("an map model") + .additionalProperties(new RefProperty("#/definitions/Children")) + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("an map model") + cm.vars.size should be (0) + cm.parent should be ("HashMap") + cm.imports.size should be (3) + (cm.imports.asScala.toSet & Set("Map", "HashMap", "Children")).size should be (3) + } + + it should "convert a model with upper-case property names" in { + val model = new ModelImpl() + .description("a model with upper-case property names") + .property("NAME", new StringProperty()) + .required("NAME") + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("NAME") + vars.get(0).getter should be ("getNAME") + vars.get(0).setter should be ("setNAME") + vars.get(0).datatype should be ("String") + vars.get(0).name should be ("NAME") + vars.get(0).defaultValue should be ("null") + vars.get(0).baseType should be ("String") + vars.get(0).hasMore should equal (null) + vars.get(0).required should equal (true) + vars.get(0).isNotContainer should equal (true) + } +} diff --git a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala new file mode 100644 index 000000000000..1cfed711c8d8 --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala @@ -0,0 +1,262 @@ +package objc + +import com.wordnik.swagger.codegen.languages.ObjcClientCodegen +import com.wordnik.swagger.util.Json +import com.wordnik.swagger.models._ +import com.wordnik.swagger.models.properties._ + +import io.swagger.parser.SwaggerParser + +import org.junit.runner.RunWith +import org.scalatest.junit.JUnitRunner +import org.scalatest.FlatSpec +import org.scalatest.Matchers + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class ObjcModelTest extends FlatSpec with Matchers { + + it should "convert a simple java model" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name") + + val codegen = new ObjcClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("SWGSample") + cm.description should be ("a sample model") + cm.vars.size should be (3) + + val vars = cm.vars + vars.get(0).baseName should be ("id") + vars.get(0).datatype should be ("NSNumber*") + vars.get(0).name should be ("_id") + vars.get(0).defaultValue should be (null) + vars.get(0).baseType should be ("NSNumber") + vars.get(0).hasMore should equal (true) + vars.get(0).required should equal (true) + vars.get(0).isPrimitiveType should equal (true) + vars.get(0).isNotContainer should equal (true) + + vars.get(1).baseName should be ("name") + vars.get(1).datatype should be ("NSString*") + vars.get(1).name should be ("name") + vars.get(1).defaultValue should be (null) + vars.get(1).baseType should be ("NSString") + vars.get(1).hasMore should equal (true) + vars.get(1).required should equal (true) + vars.get(0).isPrimitiveType should equal (true) + vars.get(1).isNotContainer should equal (true) + + vars.get(2).baseName should be ("createdAt") + vars.get(2).complexType should be ("SWGDate") + vars.get(2).datatype should be ("SWGDate*") + vars.get(2).name should be ("createdAt") + vars.get(2).defaultValue should be (null) + vars.get(2).baseType should be ("SWGDate") + vars.get(2).hasMore should equal (null) + vars.get(2).required should equal (false) + vars.get(2).isNotContainer should equal (true) + + (cm.imports.asScala.toSet & + Set("SWGDate")).size should be (1) + } + + it should "convert a model with list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty() + .items(new StringProperty())) + .required("id") + + val codegen = new ObjcClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("SWGSample") + cm.description should be ("a sample model") + cm.vars.size should be (2) + + val vars = cm.vars + vars.get(0).baseName should be ("id") + vars.get(0).datatype should be ("NSNumber*") + vars.get(0).name should be ("_id") + vars.get(0).defaultValue should be (null) + vars.get(0).baseType should be ("NSNumber") + vars.get(0).hasMore should equal (true) + vars.get(0).required should equal (true) + vars.get(0).isPrimitiveType should equal (true) + vars.get(0).isNotContainer should equal (true) + + vars.get(1).baseName should be ("urls") + vars.get(1).datatype should be ("NSArray*") + vars.get(1).name should be ("urls") + // vars.get(1).defaultValue should be ("null") + vars.get(1).baseType should be ("NSArray") + vars.get(1).hasMore should be (null) + vars.get(1).containerType should equal ("array") + vars.get(1).required should equal (false) + vars.get(1).isPrimitiveType should equal (true) + vars.get(1).isContainer should equal (true) + } + + it should "convert a model with a map property" in { + val model = new ModelImpl() + .description("a sample model") + .property("translations", new MapProperty() + .additionalProperties(new StringProperty())) + .required("id") + + val codegen = new ObjcClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("SWGSample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("translations") + vars.get(0).datatype should be ("NSDictionary*") + vars.get(0).name should be ("translations") + vars.get(0).baseType should be ("NSDictionary") + vars.get(0).containerType should be ("map") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + vars.get(0).isPrimitiveType should equal (true) + } + + it should "convert a model with complex property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")) + + val codegen = new ObjcClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("SWGSample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).datatype should be ("SWGChildren*") + vars.get(0).name should be ("children") + vars.get(0).baseType should be ("SWGChildren") + vars.get(0).required should equal (false) + vars.get(0).isNotContainer should equal (true) + } + + it should "convert a model with complex list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))) + + val codegen = new ObjcClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("SWGSample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).complexType should be ("SWGChildren") + vars.get(0).datatype should be ("NSArray*") + vars.get(0).name should be ("children") + vars.get(0).baseType should be ("NSArray") + vars.get(0).containerType should be ("array") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + } + + it should "convert a model with complex map property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new MapProperty() + .additionalProperties(new RefProperty("#/definitions/Children"))) + + val codegen = new ObjcClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("SWGSample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + (cm.imports.asScala.toSet & Set("SWGChildren")).size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).complexType should be ("SWGChildren") + vars.get(0).datatype should be ("NSDictionary*") + vars.get(0).name should be ("children") + vars.get(0).baseType should be ("NSDictionary") + vars.get(0).containerType should be ("map") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + vars.get(0).isNotContainer should be (null) + } + + it should "convert an array model" in { + val model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")) + val codegen = new ObjcClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("SWGSample") + cm.description should be ("an array model") + cm.vars.size should be (0) + cm.parent should be ("NSMutableArray") + cm.imports.size should be (3) + (cm.imports.asScala.toSet & Set("SWGChildren", "NSArray", "NSMutableArray")).size should be (3) + } + + it should "convert an map model" in { + val model = new ModelImpl() + .description("an map model") + .additionalProperties(new RefProperty("#/definitions/Children")) + + val codegen = new ObjcClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("SWGSample") + cm.description should be ("an map model") + cm.vars.size should be (0) + cm.parent should be ("NSMutableDictionary") + cm.imports.size should be (3) + (cm.imports.asScala.toSet & Set("SWGChildren", "NSDictionary", "NSMutableDictionary")).size should be (3) + } + + it should "create proper imports per #316" in { + val model = new SwaggerParser().read("src/test/resources/2_0/postBodyTest.json") + val codegen = new ObjcClientCodegen() + + val animalPaths = model.getPaths() + val animalOps = animalPaths.get("/animals") + animalOps.getPost() should not be (null) + val animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost()) + animalCo.imports.size should be (1) + animalCo.imports.contains("SWGAnimal") should equal (true) + + val insectPaths = model.getPaths() + val insectOps = insectPaths.get("/insects") + insectOps.getPost() should not be (null) + val insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost()) + insectCo.imports.size should be (1) + insectCo.imports.contains("SWGInsect") should equal (true) + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala b/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala new file mode 100644 index 000000000000..8051e84e660a --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala @@ -0,0 +1,19 @@ +import com.wordnik.swagger.models._ +import io.swagger.parser._ + +import org.junit.runner.RunWith +import org.scalatest.junit.JUnitRunner +import org.scalatest.FlatSpec +import org.scalatest.Matchers + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class SwaggerMigratorTest extends FlatSpec with Matchers { + behavior of "SwaggerMigrator" + + it should "read a 1.2 spec" in { + val loader = new SwaggerParser() + loader.read("src/test/resources/1_2/petstore-1.2/api-docs") + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala new file mode 100644 index 000000000000..5e5034e5efc4 --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala @@ -0,0 +1,259 @@ +package php + +import com.wordnik.swagger.codegen.languages.PhpClientCodegen +import com.wordnik.swagger.util.Json +import com.wordnik.swagger.models._ +import com.wordnik.swagger.models.properties._ + +import io.swagger.parser.SwaggerParser + +import org.junit.runner.RunWith +import org.scalatest.junit.JUnitRunner +import org.scalatest.FlatSpec +import org.scalatest.Matchers + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class PhpModelTest extends FlatSpec with Matchers { + + it should "convert a simple php model" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name") + + val codegen = new PhpClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (3) + + val vars = cm.vars + vars.get(0).baseName should be ("id") + vars.get(0).datatype should be ("int") + vars.get(0).name should be ("id") + vars.get(0).defaultValue should be ("null") + vars.get(0).baseType should be ("int") + vars.get(0).hasMore should equal (true) + vars.get(0).required should equal (true) + vars.get(0).isPrimitiveType should equal (true) + vars.get(0).isNotContainer should equal (true) + + vars.get(1).baseName should be ("name") + vars.get(1).datatype should be ("string") + vars.get(1).name should be ("name") + vars.get(1).defaultValue should be ("null") + vars.get(1).baseType should be ("string") + vars.get(1).hasMore should equal (true) + vars.get(1).required should equal (true) + vars.get(0).isPrimitiveType should equal (true) + vars.get(1).isNotContainer should equal (true) + + vars.get(2).baseName should be ("createdAt") + vars.get(2).complexType should be (null) + vars.get(2).datatype should be ("DateTime") + vars.get(2).name should be ("createdAt") + vars.get(2).defaultValue should be ("null") + vars.get(2).baseType should be ("DateTime") + vars.get(2).hasMore should equal (null) + vars.get(2).required should equal (false) + vars.get(2).isNotContainer should equal (true) + + cm.imports.size() should be (0) + } + + it should "convert a model with list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty() + .items(new StringProperty())) + .required("id") + + val codegen = new PhpClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (2) + + val vars = cm.vars + vars.get(0).baseName should be ("id") + vars.get(0).datatype should be ("int") + vars.get(0).name should be ("id") + vars.get(0).defaultValue should be ("null") + vars.get(0).baseType should be ("int") + vars.get(0).hasMore should equal (true) + vars.get(0).required should equal (true) + vars.get(0).isPrimitiveType should equal (true) + vars.get(0).isNotContainer should equal (true) + + vars.get(1).baseName should be ("urls") + vars.get(1).datatype should be ("array[string]") + vars.get(1).name should be ("urls") + vars.get(1).baseType should be ("array") + vars.get(1).hasMore should be (null) + vars.get(1).containerType should equal ("array") + vars.get(1).required should equal (false) + vars.get(1).isPrimitiveType should equal (true) + vars.get(1).isContainer should equal (true) + } + + it should "convert a model with a map property" in { + val model = new ModelImpl() + .description("a sample model") + .property("translations", new MapProperty() + .additionalProperties(new StringProperty())) + .required("id") + + val codegen = new PhpClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("translations") + vars.get(0).datatype should be ("map[string,string]") + vars.get(0).name should be ("translations") + vars.get(0).baseType should be ("map") + vars.get(0).containerType should be ("map") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + vars.get(0).isPrimitiveType should equal (true) + } + + it should "convert a model with complex property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")) + + val codegen = new PhpClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).datatype should be ("Children") + vars.get(0).name should be ("children") + vars.get(0).baseType should be ("Children") + vars.get(0).required should equal (false) + vars.get(0).isNotContainer should equal (true) + } + + it should "convert a model with complex list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))) + + val codegen = new PhpClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).complexType should be ("Children") + vars.get(0).datatype should be ("array[Children]") + vars.get(0).name should be ("children") + vars.get(0).baseType should be ("array") + vars.get(0).containerType should be ("array") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + } + + it should "convert a model with complex map property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new MapProperty() + .additionalProperties(new RefProperty("#/definitions/Children"))) + + val codegen = new PhpClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + (cm.imports.asScala.toSet & Set("Children")).size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).complexType should be ("Children") + vars.get(0).datatype should be ("map[string,Children]") + vars.get(0).name should be ("children") + vars.get(0).baseType should be ("map") + vars.get(0).containerType should be ("map") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + vars.get(0).isNotContainer should be (null) + } + + it should "convert an array model" in { + val model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")) + val codegen = new PhpClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("an array model") + cm.vars.size should be (0) + cm.imports.size should be (1) + (cm.imports.asScala.toSet & Set("Children")).size should be (1) + } + + it should "convert an map model" in { + val model = new ModelImpl() + .description("an map model") + .additionalProperties(new RefProperty("#/definitions/Children")) + + val codegen = new PhpClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("an map model") + cm.vars.size should be (0) + cm.imports.size should be (2) + (cm.imports.asScala.toSet & Set("Children")).size should be (1) + } + + it should "create proper imports per #316" in { + val model = new SwaggerParser() + .read("src/test/resources/2_0/postBodyTest.json") + val codegen = new PhpClientCodegen() + + val animalPaths = model.getPaths() + val animalOps = animalPaths.get("/animals") + animalOps.getPost() should not be (null) + val animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost()) + animalCo.imports.size should be (1) + animalCo.imports.contains("Animal") should equal (true) + + val insectPaths = model.getPaths() + val insectOps = insectPaths.get("/insects") + insectOps.getPost() should not be (null) + val insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost()) + insectCo.imports.size should be (1) + insectCo.imports.contains("Insect") should equal (true) + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala b/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala new file mode 100644 index 000000000000..0c71983b1d5b --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala @@ -0,0 +1,241 @@ +package Java + +import com.wordnik.swagger.codegen.languages.ScalaClientCodegen +import com.wordnik.swagger.util.Json +import com.wordnik.swagger.models._ +import com.wordnik.swagger.models.properties._ + +import org.junit.runner.RunWith +import org.scalatest.junit.JUnitRunner +import org.scalatest.FlatSpec +import org.scalatest.Matchers + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class ScalaModelTest extends FlatSpec with Matchers { + + it should "convert a simple scala model" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name") + + val codegen = new ScalaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (3) + + val vars = cm.vars + vars.get(0).baseName should be ("id") + vars.get(0).getter should be ("getId") + vars.get(0).setter should be ("setId") + vars.get(0).datatype should be ("Long") + vars.get(0).name should be ("id") + vars.get(0).defaultValue should be ("null") + vars.get(0).baseType should be ("Long") + vars.get(0).hasMore should equal (true) + vars.get(0).required should equal (true) + vars.get(0).isNotContainer should equal (true) + + vars.get(1).baseName should be ("name") + vars.get(1).getter should be ("getName") + vars.get(1).setter should be ("setName") + vars.get(1).datatype should be ("String") + vars.get(1).name should be ("name") + vars.get(1).defaultValue should be ("null") + vars.get(1).baseType should be ("String") + vars.get(1).hasMore should equal (true) + vars.get(1).required should equal (true) + vars.get(1).isNotContainer should equal (true) + + vars.get(2).baseName should be ("createdAt") + vars.get(2).getter should be ("getCreatedAt") + vars.get(2).setter should be ("setCreatedAt") + vars.get(2).datatype should be ("DateTime") + vars.get(2).name should be ("createdAt") + vars.get(2).defaultValue should be ("null") + vars.get(2).baseType should be ("DateTime") + vars.get(2).hasMore should equal (null) + vars.get(2).required should equal (false) + vars.get(2).isNotContainer should equal (true) + } + + it should "convert a model with list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty() + .items(new StringProperty())) + .required("id") + + val codegen = new ScalaClientCodegen() + val cm = codegen.fromModel("sample", model) + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (2) + + val vars = cm.vars + vars.get(1).baseName should be ("urls") + vars.get(1).getter should be ("getUrls") + vars.get(1).setter should be ("setUrls") + vars.get(1).datatype should be ("List[String]") + vars.get(1).name should be ("urls") + vars.get(1).defaultValue should be ("new ListBuffer[String]() ") + vars.get(1).baseType should be ("List") + vars.get(1).containerType should be ("array") + vars.get(1).required should equal (false) + vars.get(1).isContainer should equal (true) + } + + it should "convert a model with a map property" in { + val model = new ModelImpl() + .description("a sample model") + .property("translations", new MapProperty() + .additionalProperties(new StringProperty())) + .required("id") + + val codegen = new ScalaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("translations") + vars.get(0).getter should be ("getTranslations") + vars.get(0).setter should be ("setTranslations") + vars.get(0).datatype should be ("Map[String, String]") + vars.get(0).name should be ("translations") + vars.get(0).defaultValue should be ("new HashMap[String, String]() ") + vars.get(0).baseType should be ("Map") + vars.get(0).containerType should be ("map") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + } + + it should "convert a model with complex properties" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")) + + val codegen = new ScalaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).getter should be ("getChildren") + vars.get(0).setter should be ("setChildren") + vars.get(0).datatype should be ("Children") + vars.get(0).name should be ("children") + vars.get(0).defaultValue should be ("null") + vars.get(0).baseType should be ("Children") + vars.get(0).required should equal (false) + vars.get(0).isNotContainer should equal (true) + } + + it should "convert a model with complex list property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))) + + val codegen = new ScalaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).complexType should be ("Children") + vars.get(0).getter should be ("getChildren") + vars.get(0).setter should be ("setChildren") + vars.get(0).datatype should be ("List[Children]") + vars.get(0).name should be ("children") + vars.get(0).defaultValue should be ("new ListBuffer[Children]() ") + vars.get(0).baseType should be ("List") + vars.get(0).containerType should be ("array") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + } + + it should "convert a model with complex map property" in { + val model = new ModelImpl() + .description("a sample model") + .property("children", new MapProperty() + .additionalProperties(new RefProperty("#/definitions/Children"))) + + val codegen = new ScalaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("a sample model") + cm.vars.size should be (1) + (cm.imports.asScala.toSet & Set("Children")).size should be (1) + + val vars = cm.vars + vars.get(0).baseName should be ("children") + vars.get(0).complexType should be ("Children") + vars.get(0).getter should be ("getChildren") + vars.get(0).setter should be ("setChildren") + vars.get(0).datatype should be ("Map[String, Children]") + vars.get(0).name should be ("children") + vars.get(0).defaultValue should be ("new HashMap[String, Children]() ") + vars.get(0).baseType should be ("Map") + vars.get(0).containerType should be ("map") + vars.get(0).required should equal (false) + vars.get(0).isContainer should equal (true) + vars.get(0).isNotContainer should be (null) + } + + it should "convert an array model" in { + val model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")) + val codegen = new ScalaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("an array model") + cm.vars.size should be (0) + cm.parent should be ("ListBuffer[Children]") + cm.imports.size should be (3) + (cm.imports.asScala.toSet & Set("List", "ListBuffer", "Children")).size should be (3) + } + + it should "convert an map model" in { + val model = new ModelImpl() + .description("an map model") + .additionalProperties(new RefProperty("#/definitions/Children")) + + val codegen = new ScalaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be ("sample") + cm.classname should be ("Sample") + cm.description should be ("an map model") + cm.vars.size should be (0) + cm.parent should be ("HashMap[String, Children]") + cm.imports.size should be (2) + (cm.imports.asScala.toSet & Set("HashMap", "Children")).size should be (2) + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/staticDocs/StaticOperationTest.scala b/modules/swagger-codegen/src/test/scala/staticDocs/StaticOperationTest.scala new file mode 100644 index 000000000000..f46201faa5b2 --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/staticDocs/StaticOperationTest.scala @@ -0,0 +1,65 @@ +package staticDocs + +import com.wordnik.swagger.codegen.languages.StaticDocCodegen +import com.wordnik.swagger.util.Json +import com.wordnik.swagger.models._ +import com.wordnik.swagger.models.properties._ + +import org.junit.runner.RunWith +import org.scalatest.junit.JUnitRunner +import org.scalatest.FlatSpec +import org.scalatest.Matchers + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class StaticOperationTest extends FlatSpec with Matchers { + it should "convert a string parameter" in { + val property = new StringProperty() + + val codegen = new StaticDocCodegen() + val cp = codegen.fromProperty("property", property) + + cp.baseName should be ("property") + cp.datatype should be ("String") + cp.name should be ("property") + cp.baseType should be ("string") + cp.isNotContainer should equal (true) + } + + it should "convert a complex parameter" in { + val property = new RefProperty("Children") + + val codegen = new StaticDocCodegen() + val cp = codegen.fromProperty("property", property) + + cp.baseName should be ("property") + cp.complexType should be ("Children") + cp.getter should be ("getProperty") + cp.setter should be ("setProperty") + cp.datatype should be ("Children") + cp.name should be ("property") + cp.defaultValue should be ("null") + cp.baseType should be ("Children") + cp.isNotContainer should equal (true) + } + + it should "convert a complex list parameter" in { + val property = new ArrayProperty(). + items(new RefProperty("Children")) + + val codegen = new StaticDocCodegen() + val cp = codegen.fromProperty("property", property) + + cp.baseName should be ("property") + cp.complexType should be ("Children") + cp.getter should be ("getProperty") + cp.setter should be ("setProperty") + cp.datatype should be ("List") + cp.name should be ("property") + cp.baseType should be ("array") + cp.containerType should be ("array") + cp.isContainer should equal (true) + + } +} \ No newline at end of file diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml new file mode 100644 index 000000000000..653ea278617a --- /dev/null +++ b/modules/swagger-generator/pom.xml @@ -0,0 +1,240 @@ + + 4.0.0 + + com.wordnik + swagger-codegen-project + 2.1.2-M1 + ../.. + + com.wordnik + swagger-generator + war + swagger-generator + 1.0.0 + + src/main/java + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + net.alchim31.maven + scala-maven-plugin + + + scala-test-compile + process-test-resources + + testCompile + + + + + + incremental + + + -Xmx384m + + + -target:jvm-1.6 + -deprecation + + + + run-scalatest + org.scalatest.tools.Runner + + -p + ${project.build.testOutputDirectory} + + + -Xmx512m + + + + + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty-version} + + + / + + target/${project.artifactId}-${project.version} + 8079 + stopit + + 8002 + 60000 + + + + + start-jetty + pre-integration-test + + run + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + + + + com.wordnik + swagger-jersey2-jaxrs + ${swagger-core-version} + + + com.wordnik + swagger-codegen + ${project.parent.version} + + + ch.qos.logback + logback-classic + ${logback-version} + + + ch.qos.logback + logback-core + ${logback-version} + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + javax.servlet + servlet-api + ${servlet-api-version} + + + org.glassfish.jersey.containers + jersey-container-servlet-core + ${jersey2-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey2-version} + + + net.lingala.zip4j + zip4j + ${zip-version} + + + org.eclipse.jetty + jetty-server + ${jetty-version} + + + org.eclipse.jetty + jetty-start + ${jetty-version} + + + org.eclipse.jetty + jetty-xml + ${jetty-version} + + + org.eclipse.jetty + jetty-webapp + ${jetty-version} + + + org.eclipse.jetty + jetty-deploy + ${jetty-version} + + + + org.scalatest + scalatest_2.11 + ${scala-test-version} + test + + + org.scala-lang + scala-library + ${scala-version} + test + + + org.scala-lang + scala-compiler + ${scala-version} + test + + + + 2.3.4 + 2.5 + 1.0.1 + 4.8.1 + 1.0.0 + 2.4 + 1.6.3 + 2.5 + 1.3.2 + 9.0.7.v20131107 + 2.4.1 + 1.5.1-M1 + + 3.1.5 + 2.10.0 + + diff --git a/modules/swagger-generator/sample.json b/modules/swagger-generator/sample.json new file mode 100644 index 000000000000..463b7006ec2e --- /dev/null +++ b/modules/swagger-generator/sample.json @@ -0,0 +1,479 @@ +{ + "opts": {}, + "spec": { + "swagger": "2.0", + "title": "Petstore Sample API", + "info": { + "description": "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", + "title": "Petstore Sample API", + "contact": { + "name": "Wordnik API Team" + }, + "license": { + "name": "MIT", + "url": "http://github.com/gruntjs/grunt/blob/master/LICENSE-MIT" + } + }, + "host": "petstore.swagger.io", + "basePath": "/api", + "paths": { + "/pet": { + "put": { + "tags": [ + "pet" + ], + "parameters": [ + { + "name": "body", + "in": "body", + "description": "Pet object that needs to be added to the store", + "required": false, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Validation exception" + }, + "404": { + "description": "Pet not found" + }, + "400": { + "description": "Invalid ID supplied" + } + } + }, + "post": { + "tags": [ + "pet" + ], + "parameters": [ + { + "name": "body", + "in": "body", + "description": "Pet object that needs to be added to the store", + "required": false, + "schema": { + "$ref": "#/definitions/Tag" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + } + } + }, + "/user/createWithList": { + "post": { + "tags": [ + "user" + ], + "parameters": [ + { + "name": "body", + "in": "body", + "description": "List of user object", + "required": false + } + ] + } + }, + "/store/order/{orderId}": { + "get": { + "tags": [ + "store" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "Order not found" + }, + "400": { + "description": "Invalid ID supplied" + } + } + }, + "delete": { + "tags": [ + "store" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of the order that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "Order not found" + }, + "400": { + "description": "Invalid ID supplied" + } + } + } + }, + "/user/createWithArray": { + "post": { + "tags": [ + "user" + ], + "parameters": [ + { + "name": "body", + "in": "body", + "description": "List of user object", + "required": false, + "schema": { + "$ref": "#/definitions/User" + } + } + ] + } + }, + "/store/order": { + "post": { + "tags": [ + "store" + ], + "parameters": [ + { + "name": "body", + "in": "body", + "description": "order placed for purchasing the pet", + "required": false, + "schema": { + "$ref": "#/definitions/Order" + } + } + ], + "responses": { + "400": { + "description": "Invalid Order" + } + } + } + }, + "/pet/findByStatus": { + "get": { + "tags": [ + "pet" + ], + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Status values that need to be considered for filter", + "required": false, + "type": "string" + } + ], + "responses": { + "400": { + "description": "Invalid status value" + } + } + } + }, + "/user/{username}": { + "get": { + "tags": [ + "user" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be fetched. Use user1 for testing. ", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid username supplied" + } + } + }, + "put": { + "tags": [ + "user" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "name that need to be deleted", + "required": true, + "type": "string" + }, + { + "name": "body", + "in": "body", + "description": "Updated user object", + "required": false, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid user supplied" + } + } + }, + "delete": { + "tags": [ + "user" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid username supplied" + } + } + } + }, + "/pet/findByTags": { + "get": { + "tags": [ + "pet" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "Tags to filter by", + "required": false, + "type": "string" + } + ], + "responses": { + "400": { + "description": "Invalid tag value" + } + } + } + }, + "/user": { + "post": { + "tags": [ + "user" + ], + "parameters": [ + { + "name": "body", + "in": "body", + "description": "Created user object", + "required": false, + "schema": { + "$ref": "#/definitions/User" + } + } + ] + } + }, + "/pet/{petId}": { + "get": { + "tags": [ + "pet" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "Pet not found" + }, + "400": { + "description": "Invalid ID supplied" + } + } + } + }, + "/user/logout": { + "get": { + "tags": [ + "user" + ] + } + }, + "/user/login": { + "get": { + "tags": [ + "user" + ], + "parameters": [ + { + "name": "username", + "in": "query", + "description": "The user name for login", + "required": false, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The password for login in clear text", + "required": false, + "type": "string" + } + ], + "responses": { + "400": { + "description": "Invalid username/password supplied" + } + } + } + } + }, + "definitions": { + "User": { + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "lastName": { + "type": "string" + }, + "username": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "email": { + "type": "string" + }, + "userStatus": { + "type": "integer", + "format": "int32" + }, + "firstName": { + "type": "string" + }, + "password": { + "type": "string" + } + } + }, + "Category": { + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string" + } + } + }, + "Pet": { + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "tags": { + "type": "array", + "items": { + "$ref": "#/definitions/Tag" + } + }, + "category": { + "$ref": "#/definitions/Category" + }, + "status": { + "type": "string" + }, + "name": { + "type": "string" + }, + "photoUrls": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "Tag": { + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "name": { + "type": "string" + } + } + }, + "Order": { + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "petId": { + "type": "integer", + "format": "int32" + }, + "status": { + "type": "string" + }, + "complete": { + "type": "boolean" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "shipDate": { + "type": "string", + "format": "date-time" + } + } + } + } + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/Bootstrap.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/Bootstrap.java new file mode 100644 index 000000000000..7035b60d1f7a --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/Bootstrap.java @@ -0,0 +1,45 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 com.wordnik.swagger.generator; + +import com.wordnik.swagger.models.*; + +import javax.servlet.http.HttpServlet; +import javax.servlet.ServletContext; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; + +public class Bootstrap extends HttpServlet { + public void init(ServletConfig config) throws ServletException { + ServletContext context = config.getServletContext(); + + DynamicSwaggerConfig bc = new DynamicSwaggerConfig(); + bc.setBasePath("/api"); + bc.setTitle("Swagger Generator"); + bc.setDescription("This is an online swagger codegen server. You can find out more " + + "at https://github.com/swagger-api/swagger-codegen or on irc.freenode.net, #swagger." + + "http://helloreverb.com/terms/"); + bc.setTermsOfServiceUrl("http://helloreverb.com/terms/"); + bc.setContact("apiteam@swagger.io"); + bc.setLicense("Apache 2.0"); + bc.setVersion("1.0.0"); + bc.setHost("generator.swagger.io"); + bc.setLicenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html"); + bc.setResourcePackage("com.wordnik.swagger.generator.resource"); + bc.setScan(true); + } +} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/DynamicSwaggerConfig.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/DynamicSwaggerConfig.java new file mode 100644 index 000000000000..60983c230ac8 --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/DynamicSwaggerConfig.java @@ -0,0 +1,69 @@ +package com.wordnik.swagger.generator; + +import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.parameters.*; +import com.wordnik.swagger.models.properties.*; +import com.wordnik.swagger.codegen.*; + +import com.wordnik.swagger.util.Json; + +import com.wordnik.swagger.jaxrs.config.BeanConfig; + +import java.util.*; + +public class DynamicSwaggerConfig extends BeanConfig { + static List clients = new ArrayList(); + static List servers = new ArrayList(); + static { + List extensions = Codegen.getExtensions(); + for(CodegenConfig config : extensions) { + if(config.getTag().equals(CodegenType.CLIENT) || config.getTag().equals(CodegenType.DOCUMENTATION)) { + clients.add(config.getName()); + } + else if(config.getTag().equals(CodegenType.SERVER)) { + servers.add(config.getName()); + } + } + } + + @Override + public Swagger configure(Swagger swagger) { + Path clientPath = swagger.getPaths().get("/gen/clients/{language}"); + // update the path description based on what clients are available via SPI + if(clientPath != null) { + Operation post = clientPath.getPost(); + Parameter framework = post.getParameters().get(0); + if(framework instanceof PathParameter) { + PathParameter param = (PathParameter) framework; + StringBuilder b = new StringBuilder(); + for(String client : clients) { + if(b.toString().length() > 0) + b.append(", "); + b.append(client); + } + param.setDescription("available clients: " + b.toString()); + } + } + + Path serverPath = swagger.getPaths().get("/gen/servers/{framework}"); + // update the path description based on what servers are available via SPI + if(serverPath != null) { + Operation post = serverPath.getPost(); + Parameter framework = post.getParameters().get(0); + if(framework instanceof PathParameter) { + PathParameter param = (PathParameter) framework; + StringBuilder b = new StringBuilder(); + for(String server : servers) { + if(b.toString().length() > 0) + b.append(", "); + b.append(server); + } + param.setDescription("available clients: " + b.toString()); + } + } + + return swagger.info(getInfo()) + .host(getHost()) + .basePath("/api"); + } +} \ No newline at end of file diff --git a/src/main/scala/com/wordnik/swagger/codegen/spec/SwaggerSpec.scala b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/ApiException.java similarity index 70% rename from src/main/scala/com/wordnik/swagger/codegen/spec/SwaggerSpec.scala rename to modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/ApiException.java index a958ba3d6937..1383c791aac3 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/spec/SwaggerSpec.scala +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/ApiException.java @@ -1,5 +1,5 @@ /** - * Copyright 2014 Wordnik, Inc. + * Copyright 2015 Reverb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,9 +14,12 @@ * limitations under the License. */ -package com.wordnik.swagger.codegen.spec +package com.wordnik.swagger.generator.exception; -object SwaggerSpec { - val primitives = List("int", "string", "long", "double", "float", "boolean", "void") - val containers = List("List", "Map", "Set", "Array") +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } } diff --git a/samples/client/wordnik-api/php/wordnik/models/StringValue.php b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/BadRequestException.java similarity index 66% rename from samples/client/wordnik-api/php/wordnik/models/StringValue.php rename to modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/BadRequestException.java index 16b37d612d9c..c0883b30edaa 100644 --- a/samples/client/wordnik-api/php/wordnik/models/StringValue.php +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/BadRequestException.java @@ -1,6 +1,5 @@ - 'string' - - ); - - public $word; // string +public class BadRequestException extends ApiException { + private int code; + public BadRequestException (int code, String msg) { + super(code, msg); + this.code = code; } - +} diff --git a/samples/client/wordnik-api/php/wordnik/models/ExampleUsage.php b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/NotFoundException.java similarity index 66% rename from samples/client/wordnik-api/php/wordnik/models/ExampleUsage.php rename to modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/NotFoundException.java index 9f1a8db5561f..e9a302b2f1e5 100644 --- a/samples/client/wordnik-api/php/wordnik/models/ExampleUsage.php +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/exception/NotFoundException.java @@ -1,6 +1,5 @@ - 'string' - - ); - - public $text; // string +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; } - +} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ApiResponse.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ApiResponse.java new file mode 100644 index 000000000000..1dfc431b073f --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ApiResponse.java @@ -0,0 +1,84 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 com.wordnik.swagger.generator.model; + +import javax.xml.bind.annotation.XmlTransient; + +@javax.xml.bind.annotation.XmlRootElement +public class ApiResponse { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponse(){} + + public ApiResponse(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/samples/client/wordnik-api/php/wordnik/models/DefinitionSearchResults.php b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/Generated.java similarity index 56% rename from samples/client/wordnik-api/php/wordnik/models/DefinitionSearchResults.php rename to modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/Generated.java index 8d08ce968d88..6436498ac3fa 100644 --- a/samples/client/wordnik-api/php/wordnik/models/DefinitionSearchResults.php +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/Generated.java @@ -1,6 +1,5 @@ - 'array[Definition]', - 'totalResults' => 'int' +public class Generated { + private String filename; + private String friendlyName; - ); - - public $results; // array[Definition] - public $totalResults; // int + public String getFilename() { + return filename; + } + public void setFilename(String filename) { + this.filename = filename; } + public String getFriendlyName() { + return friendlyName; + } + public void setFriendlyName(String friendlyName) { + this.friendlyName = friendlyName; + } +} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/GeneratorInput.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/GeneratorInput.java new file mode 100644 index 000000000000..9c5a2aa15ce5 --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/GeneratorInput.java @@ -0,0 +1,44 @@ +package com.wordnik.swagger.generator.model; + +import com.wordnik.swagger.annotations.ApiModelProperty; +import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; + +import com.fasterxml.jackson.databind.*; + +import java.util.*; + +public class GeneratorInput { + private JsonNode spec; + private Map options; + private String swaggerUrl; + private SecuritySchemeDefinition auth; + + @ApiModelProperty(dataType="Object") + public JsonNode getSpec() { + return spec; + } + public void setSpec(JsonNode spec) { + this.spec = spec; + } + + public Map getOptions() { + return options; + } + public void setOptions(Map options) { + this.options = options; + } + + public String getSwaggerUrl() { + return swaggerUrl; + } + public void setSwaggerUrl(String url) { + this.swaggerUrl = url; + } + + public SecuritySchemeDefinition getSecurityDefinition() { + return auth; + } + public void setSecurityDefinition(SecuritySchemeDefinition auth) { + this.auth = auth; + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/InputOption.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/InputOption.java new file mode 100644 index 000000000000..deee8e23c693 --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/InputOption.java @@ -0,0 +1,65 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 com.wordnik.swagger.generator.model; + +public class InputOption { + private String name; + private String description; + private Boolean required; + private String defaultValue; + + public InputOption() {} + + public InputOption(String name, String description, String defaultValue, Boolean required) { + this.name = name; + this.description = description; + this.defaultValue = defaultValue; + this.required = required; + } + + public void setName(String name) { + this.name = name; + } + + public String getName() { + return name; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getDescription() { + return description; + } + + public void setRequired(Boolean required) { + this.required = required; + } + + public Boolean getRequired() { + return required; + } + + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + public String getDefaultValue() { + return defaultValue; + } +} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ResponseCode.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ResponseCode.java new file mode 100644 index 000000000000..77271a6c72f0 --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/model/ResponseCode.java @@ -0,0 +1,26 @@ +package com.wordnik.swagger.generator.model; + +public class ResponseCode { + private String code; + private String link; + public ResponseCode() {} + + public ResponseCode(String code, String link) { + setCode(code); + setLink(link); + } + + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } + + public String getLink() { + return link; + } + public void setLink(String link) { + this.link = link; + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/online/Generator.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/online/Generator.java new file mode 100644 index 000000000000..6bbbfec4f7b1 --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/online/Generator.java @@ -0,0 +1,166 @@ +package com.wordnik.swagger.online; + +import io.swagger.parser.SwaggerParser; + +import com.wordnik.swagger.generator.exception.*; +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.Swagger; +import com.wordnik.swagger.generator.model.*; +import com.wordnik.swagger.util.Json; +import com.wordnik.swagger.generator.util.ZipUtil; + +import com.fasterxml.jackson.databind.JsonNode; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.List; +import java.util.ArrayList; + +public class Generator { + static Logger LOGGER = LoggerFactory.getLogger(Generator.class); + + public static String generateClient(String language, GeneratorInput opts) throws ApiException { + Swagger swagger; + LOGGER.debug("generate client for " + language); + if(opts == null) { + throw new BadRequestException(400, "No options were supplied"); + } + JsonNode node = opts.getSpec(); + if(node == null) { + if(opts.getSwaggerUrl() != null) { + swagger = new SwaggerParser().read(opts.getSwaggerUrl()); + } + else + throw new BadRequestException(400, "No swagger specification was supplied"); + } + else { + swagger = new SwaggerParser().read(node); + } + if(swagger == null) { + throw new BadRequestException(400, "The swagger specification supplied was not valid"); + } + + ClientOptInput clientOptInput = new ClientOptInput(); + ClientOpts clientOpts = new ClientOpts(); + String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + language + "-client"; + String outputFilename = outputFolder + "-bundle.zip"; + + clientOptInput + .opts(clientOpts) + .swagger(swagger); + + CodegenConfig codegenConfig = Codegen.getConfig(language); + if(codegenConfig == null) { + throw new BadRequestException(400, "Unsupported target " + language + " supplied"); + } + + codegenConfig.setOutputDir(outputFolder); + + Json.prettyPrint(clientOpts); + + clientOptInput.setConfig(codegenConfig); + + try{ + List files = new Codegen().opts(clientOptInput).generate(); + if(files.size() > 0) { + List filesToAdd = new ArrayList(); + filesToAdd.add(new File(outputFolder)); + ZipUtil zip = new ZipUtil(); + zip.compressFiles(filesToAdd, outputFilename); + } + else { + throw new BadRequestException(400, "A target generation was attempted, but no files were created!"); + } + } + catch (Exception e) { + throw new BadRequestException(500, "Unable to build target: " + e.getMessage()); + } + return outputFilename; + } + + public static String generateServer(String language, GeneratorInput opts) throws ApiException { + LOGGER.debug("generate server for " + language); + Swagger swagger; + if(opts == null) { + throw new BadRequestException(400, "No options were supplied"); + } + if(opts == null) { + throw new BadRequestException(400, "No options were supplied"); + } + JsonNode node = opts.getSpec(); + if(node == null) { + if(opts.getSwaggerUrl() != null) { + swagger = new SwaggerParser().read(opts.getSwaggerUrl()); + } + else + throw new BadRequestException(400, "No swagger specification was supplied"); + } + else { + swagger = new SwaggerParser().read(node); + } + if(swagger == null) { + throw new BadRequestException(400, "The swagger specification supplied was not valid"); + } + + ClientOptInput clientOptInput = new ClientOptInput(); + ClientOpts clientOpts = new ClientOpts(); + String outputFolder = getTmpFolder().getAbsolutePath() + File.separator + language + "-server"; + String outputFilename = outputFolder + "-bundle.zip"; + + clientOptInput + .opts(clientOpts) + .swagger(swagger); + + CodegenConfig codegenConfig = Codegen.getConfig(language); + if(codegenConfig == null) { + throw new BadRequestException(400, "Unsupported target " + language + " supplied"); + } + + codegenConfig.setOutputDir(outputFolder); + + Json.prettyPrint(clientOpts); + + clientOptInput.setConfig(codegenConfig); + + try{ + List files = new Codegen().opts(clientOptInput).generate(); + if(files.size() > 0) { + List filesToAdd = new ArrayList(); + filesToAdd.add(new File(outputFolder)); + ZipUtil zip = new ZipUtil(); + zip.compressFiles(filesToAdd, outputFilename); + } + else { + throw new BadRequestException(400, "A target generation was attempted, but no files were created!"); + } + } + catch (Exception e) { + throw new BadRequestException(500, "Unable to build target: " + e.getMessage()); + } + return outputFilename; + } + + public static InputOption clientOptions(String language) { + return null; + } + + public static InputOption serverOptions(String language) { + return null; + } + + protected static File getTmpFolder() { + try { + File outputFolder = File.createTempFile("codegen-", "-tmp"); + outputFolder.delete(); + outputFolder.mkdir(); + outputFolder.deleteOnExit(); + return outputFolder; + } + catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/ExceptionWriter.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/ExceptionWriter.java new file mode 100644 index 000000000000..f052c79f3114 --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/ExceptionWriter.java @@ -0,0 +1,50 @@ +package com.wordnik.swagger.generator.resource; + +import com.wordnik.swagger.generator.util.ValidationException; + +import com.wordnik.swagger.generator.exception.ApiException; +import com.wordnik.swagger.generator.exception.BadRequestException; +import com.wordnik.swagger.generator.exception.NotFoundException; +import com.wordnik.swagger.generator.model.ApiResponse; + +import javax.ws.rs.ext.*; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +@Provider +public class ExceptionWriter implements ExceptionMapper { + public Response toResponse(Exception exception) { + if (exception instanceof javax.ws.rs.WebApplicationException) { + javax.ws.rs.WebApplicationException e = (javax.ws.rs.WebApplicationException) exception; + return Response + .status(e.getResponse().getStatus()) + .entity(new ApiResponse(e.getResponse().getStatus(), + exception.getMessage())).build(); + } else if (exception instanceof com.fasterxml.jackson.core.JsonParseException) { + return Response.status(400) + .entity(new ApiResponse(400, "bad input")).build(); + } else if (exception instanceof ValidationException) { + ValidationException e = (ValidationException) exception; + return Response.status(Status.BAD_REQUEST).entity(e.getMessage()).build(); + } else if (exception instanceof NotFoundException) { + return Response + .status(Status.NOT_FOUND) + .entity(new ApiResponse(ApiResponse.ERROR, exception + .getMessage())).build(); + } else if (exception instanceof BadRequestException) { + return Response + .status(Status.BAD_REQUEST) + .entity(new ApiResponse(ApiResponse.ERROR, exception + .getMessage())).build(); + } else if (exception instanceof ApiException) { + return Response + .status(Status.BAD_REQUEST) + .entity(new ApiResponse(ApiResponse.ERROR, exception + .getMessage())).build(); + } else { + return Response.status(500) + .entity(new ApiResponse(500, "something bad happened")) + .build(); + } + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/SwaggerResource.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/SwaggerResource.java new file mode 100644 index 000000000000..2e3a480e1156 --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/resource/SwaggerResource.java @@ -0,0 +1,133 @@ +package com.wordnik.swagger.generator.resource; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.generator.util.*; +import com.wordnik.swagger.annotations.*; +import com.wordnik.swagger.generator.model.*; +import com.wordnik.swagger.generator.exception.BadRequestException; +import com.wordnik.swagger.online.Generator; + +import java.io.File; +import java.util.*; + +import javax.ws.rs.*; +import javax.ws.rs.core.*; + +@Path("/gen") +@Api(value = "/gen", description = "Resource for generating swagger components") +public class SwaggerResource { + private static Map fileMap = new HashMap(); + + static List clients = new ArrayList(); + static List servers = new ArrayList(); + static { + List extensions = Codegen.getExtensions(); + for(CodegenConfig config : extensions) { + if(config.getTag().equals(CodegenType.CLIENT) || config.getTag().equals(CodegenType.DOCUMENTATION)) { + clients.add(config.getName()); + } + else if(config.getTag().equals(CodegenType.SERVER)) { + servers.add(config.getName()); + } + } + } + + @GET + @Path("/download/{fileId}") + @Produces({"application/zip"}) + @ApiOperation(value = "Downloads a pre-generated file", + response = String.class) + public Response downloadFile(@PathParam("fileId") String fileId) throws Exception { + Generated g = fileMap.get(fileId); + System.out.println("looking for fileId " + fileId); + System.out.println("got filename " + g.getFilename()); + if(g.getFilename() != null) { + byte[] bytes = org.apache.commons.io.FileUtils.readFileToByteArray(new java.io.File(g.getFilename())); + + return Response.ok(bytes, "application/zip") + .header("Content-Disposition","attachment; filename=\"" + g.getFriendlyName() + "-generated.zip\"") + .header("Accept-Range", "bytes") + .header("Content-Length", bytes.length) + .build(); + } + else { + return Response.status(404).build(); + } + } + + @POST + @Path("/clients/{language}") + @Produces({"application/zip", "application/json"}) + @ApiOperation( + value = "Generates a client library based on the config") + public Response generateClient( + @ApiParam(value = "The target language for the client library", allowableValues = "android,java,php,objc,docs", required = true) @PathParam("language") String language, + @ApiParam(value = "Configuration for building the client library", required = true) GeneratorInput opts) throws Exception { + + String filename = Generator.generateClient(language, opts); + + if(filename != null) { + String code = String.valueOf(System.currentTimeMillis()); + Generated g = new Generated(); + g.setFilename(filename); + g.setFriendlyName(language + "-client"); + fileMap.put(code, g); + System.out.println(code + ", " + filename); + String link = "http://generator.swagger.io/api/gen/download/" + code; + return Response.ok().entity(new ResponseCode(code, link)).build(); + } + else { + return Response.status(500).build(); + } + } + + @GET + @Path("/clients") + @ApiOperation(value = "Gets languages supported by the client generator", + response = String.class, + responseContainer = "List") + public Response clientOptions() { + String[] languages = new String[clients.size()]; + languages = clients.toArray(languages); + return Response.ok().entity(languages).build(); + } + + @GET + @Path("/servers") + @ApiOperation(value = "Gets languages supported by the server generator", + response = String.class, + responseContainer = "List") + public Response serverOptions() { + String[] languages = new String[servers.size()]; + languages = servers.toArray(languages); + return Response.ok().entity(languages).build(); + } + + @POST + @Path("/servers/{framework}") + @ApiOperation(value = "Generates a server library for the supplied server framework", + notes = "The model representing this is not accurate, it needs to contain a consolidated JSON structure") + public Response generateServerForLanguage( + @ApiParam(value = "framework", allowableValues = "jaxrs,nodejs", required = true) @PathParam("framework") String framework, + @ApiParam(value = "parameters", required = true) GeneratorInput opts) + throws Exception { + if(framework == null) + throw new BadRequestException(400, "Framework is required"); + String filename = Generator.generateServer(framework, opts); + System.out.println("generated name: " + filename); + + if(filename != null) { + String code = String.valueOf(System.currentTimeMillis()); + Generated g = new Generated(); + g.setFilename(filename); + g.setFriendlyName(framework + "-server"); + fileMap.put(code, g); + System.out.println(code + ", " + filename); + String link = "http://generator.swagger.io/api/gen/download/" + code; + return Response.ok().entity(new ResponseCode(code, link)).build(); + } + else { + return Response.status(500).build(); + } + } +} diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ApiOriginFilter.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ApiOriginFilter.java new file mode 100644 index 000000000000..b9d279d20a85 --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ApiOriginFilter.java @@ -0,0 +1,42 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 com.wordnik.swagger.generator.util; + +import java.io.IOException; + +import javax.servlet.*; +import javax.servlet.http.HttpServletResponse; + +public class ApiOriginFilter implements javax.servlet.Filter { + @Override + public void doFilter(ServletRequest request, ServletResponse response, + FilterChain chain) throws IOException, ServletException { + HttpServletResponse res = (HttpServletResponse) response; + res.addHeader("Access-Control-Allow-Origin", "*"); + res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + res.addHeader("Access-Control-Allow-Headers", "Content-Type"); + chain.doFilter(request, response); + } + + @Override + public void destroy() { + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationException.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationException.java new file mode 100644 index 000000000000..19747367ca0f --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationException.java @@ -0,0 +1,27 @@ +package com.wordnik.swagger.generator.util; + +import java.util.List; + +public class ValidationException extends Exception { + private int code; + private String msg; + private List errors; + + public ValidationException(String msg) { + super(msg); + } + + public int getCode() { + return code; + } + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return msg; + } + public void setMessage(String msg) { + this.msg = msg; + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationMessage.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationMessage.java new file mode 100644 index 000000000000..b64633de2bd2 --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ValidationMessage.java @@ -0,0 +1,26 @@ +package com.wordnik.swagger.generator.util; + +public class ValidationMessage { + private String path, message, severity; + + public String getPath() { + return path; + } + public void setPath(String path) { + this.path = path; + } + + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + public String getSeverity() { + return severity; + } + public void setSeverity(String severity) { + this.severity = severity; + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ZipUtil.java b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ZipUtil.java new file mode 100644 index 000000000000..1d090bf96d39 --- /dev/null +++ b/modules/swagger-generator/src/main/java/com/wordnik/swagger/generator/util/ZipUtil.java @@ -0,0 +1,124 @@ +/** + * Copyright 2015 Reverb, Inc. + * + * 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 com.wordnik.swagger.generator.util; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** +* This utility compresses a list of files to standard ZIP format file. +* It is able to compresses all sub files and sub directories, recursively. +* @author Ha Minh Nam +* +*/ +public class ZipUtil { + /** + * A constants for buffer size used to read/write data + */ + private static final int BUFFER_SIZE = 4096; + + /** + * Compresses a collection of files to a destination zip file + * @param listFiles A collection of files and directories + * @param destZipFile The path of the destination zip file + * @throws FileNotFoundException + * @throws IOException + */ + public void compressFiles(List listFiles, String destZipFile) throws FileNotFoundException, IOException { + + ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile)); + + for (File file : listFiles) { + if (file.isDirectory()) { + addFolderToZip(file, file.getName(), zos); + } else { + addFileToZip(file, zos); + } + } + + zos.flush(); + zos.close(); + } + + /** + * Adds a directory to the current zip output stream + * @param folder the directory to be added + * @param parentFolder the path of parent directory + * @param zos the current zip output stream + * @throws FileNotFoundException + * @throws IOException + */ + private void addFolderToZip(File folder, String parentFolder, + ZipOutputStream zos) throws FileNotFoundException, IOException { + for (File file : folder.listFiles()) { + if (file.isDirectory()) { + addFolderToZip(file, parentFolder + "/" + file.getName(), zos); + continue; + } + + zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName())); + + BufferedInputStream bis = new BufferedInputStream( + new FileInputStream(file)); + + long bytesRead = 0; + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + + while ((read = bis.read(bytesIn)) != -1) { + zos.write(bytesIn, 0, read); + bytesRead += read; + } + + zos.closeEntry(); + + } + } + + /** + * Adds a file to the current zip output stream + * @param file the file to be added + * @param zos the current zip output stream + * @throws FileNotFoundException + * @throws IOException + */ + private void addFileToZip(File file, ZipOutputStream zos) + throws FileNotFoundException, IOException { + zos.putNextEntry(new ZipEntry(file.getName())); + + BufferedInputStream bis = new BufferedInputStream(new FileInputStream( + file)); + + long bytesRead = 0; + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + + while ((read = bis.read(bytesIn)) != -1) { + zos.write(bytesIn, 0, read); + bytesRead += read; + } + + zos.closeEntry(); + } +} \ No newline at end of file diff --git a/modules/swagger-generator/src/main/resources/logback.xml b/modules/swagger-generator/src/main/resources/logback.xml new file mode 100644 index 000000000000..f263bf8bde0b --- /dev/null +++ b/modules/swagger-generator/src/main/resources/logback.xml @@ -0,0 +1,12 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + diff --git a/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml b/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml new file mode 100644 index 000000000000..7b363b797ed7 --- /dev/null +++ b/modules/swagger-generator/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,50 @@ + + + + + jersey + org.glassfish.jersey.servlet.ServletContainer + + jersey.config.server.provider.packages + + com.wordnik.swagger.jaxrs.json, + com.wordnik.swagger.generator.resource + + + + jersey.config.server.provider.classnames + + com.wordnik.swagger.online.ExceptionWriter, + com.wordnik.swagger.jersey.listing.ApiListingResourceJSON, + com.wordnik.swagger.jersey.listing.JerseyApiDeclarationProvider, + com.wordnik.swagger.jersey.listing.JerseyResourceListingProvider + + + + jersey.config.server.wadl.disableWadl + true + + 1 + + + + jersey + /api/* + + + + ApiOriginFilter + com.wordnik.swagger.generator.util.ApiOriginFilter + + + Bootstrap + com.wordnik.swagger.generator.Bootstrap + 2 + + + ApiOriginFilter + /* + + \ No newline at end of file diff --git a/modules/swagger-generator/src/test/scala/GeneratorInputTest.scala b/modules/swagger-generator/src/test/scala/GeneratorInputTest.scala new file mode 100644 index 000000000000..b417ce322b6f --- /dev/null +++ b/modules/swagger-generator/src/test/scala/GeneratorInputTest.scala @@ -0,0 +1,19 @@ +import com.wordnik.swagger.online._ +import com.wordnik.swagger.generator.model._ +import com.wordnik.swagger.util.Json + +import org.junit.runner.RunWith +import org.scalatest.junit.JUnitRunner +import org.scalatest.FlatSpec +import org.scalatest.Matchers + +import scala.collection.JavaConverters._ + +@RunWith(classOf[JUnitRunner]) +class GeneratorInputTest extends FlatSpec with Matchers { + it should "write an object" in { + val obj = new GeneratorInput() + obj.setSwaggerUrl("http://petstore.swagger.io/v2/swagger.json") + Json.prettyPrint(obj) + } +} \ No newline at end of file diff --git a/package.json b/package.json deleted file mode 100644 index ea21c2110957..000000000000 --- a/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "name": "swagger-yaml", - "version": "2.0.1", - "description": "Converts yaml to swagger json", - "author": { - "name": "Tony Tam", - "email": "fehguy@gmail.com", - "url": "http://developer.wordnik.com" - }, - "license": "Apache", - "readmeFilename": "README.md", - "dependencies": { - "json2yaml": "~1.0", - "js-yaml": "~3.0" - } -} \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 000000000000..549fb1833052 --- /dev/null +++ b/pom.xml @@ -0,0 +1,365 @@ + + + org.sonatype.oss + oss-parent + 5 + + 4.0.0 + com.wordnik + swagger-codegen-project + pom + swagger-codegen-project + 2.1.2-M1 + https://github.com/swagger-api/swagger-codegen + + scm:git:git@github.com:swagger-api/swagger-codegen.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + fehguy + Tony Tam + fehguy@gmail.com + + + + github + https://github.com/swagger-api/swagger-core/issues + + + + swagger-swaggersocket + https://groups.google.com/forum/#!forum/swagger-swaggersocket + + + + + Apache License 2.0 + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + src/main/java + target/classes + + + org.jvnet.wagon-svn + wagon-svn + 1.8 + + + org.apache.maven.wagon + wagon-ssh-external + 1.0-alpha-6 + + + org.apache.maven.wagon + wagon-webdav + 1.0-beta-1 + + + install + target + ${project.artifactId}-${project.version} + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + attach-sources + verify + + jar-no-fork + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.7 + + true + 1.6 + UTF-8 + 1g + + http://java.sun.com/javase/6/docs/api/ + + ${javadoc.package.exclude} + + + + attach-javadocs + verify + + jar + + + + + + maven-compiler-plugin + 3.0 + + 1.6 + 1.6 + + + + org.apache.maven.plugins + maven-jar-plugin + 2.4 + + + + development + ${project.url} + ${project.version} + com.wordnik + + + + + + org.apache.maven.plugins + maven-site-plugin + 2.1 + + + org.apache.maven.plugins + maven-release-plugin + 2.1 + + + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + org.apache.maven.plugins + maven-gpg-plugin + + release + sign + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.7 + + true + 1.6 + UTF-8 + 1g + + http://java.sun.com/javase/6/docs/api/ + + ${javadoc.package.exclude} + + + + attach-javadocs + verify + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + attach-sources + verify + + jar-no-fork + + + + + + + + + + release-profile + + true + + + + + net.alchim31.maven + scala-maven-plugin + + + + compile + testCompile + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add-source + prepare-package + + add-source + + + + src/main/scala + + + + + + + + + + release-sign-artifacts + + + performRelease + true + + + + + + org.apache.maven.plugins + maven-gpg-plugin + + + sign-artifacts + verify + + sign + + + + + + + + + + modules/swagger-codegen + modules/swagger-codegen-distribution + modules/swagger-generator + + + target/site + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.9 + + true + true + + http://java.sun.com/javaee/5/docs/api + http://java.sun.com/j2se/1.5.0/docs/api + + + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + org.apache.maven.plugins + maven-jxr-plugin + 2.3 + + true + + + + org.apache.maven.plugins + maven-project-info-reports-plugin + 2.6 + + + + project-team + + + + + + + + + + junit + junit + ${junit-version} + test + + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 1.0.1 + 2.11.1 + 2.3.4 + 1.5.2-M1 + 2.1.4 + 2.3 + 1.2 + 4.8.1 + 1.0.0 + 2.4 + 1.6.3 + 3.1.5 + 2.10.4 + 1.9 + + diff --git a/project/build.properties b/project/build.properties deleted file mode 100644 index 507528966aa4..000000000000 --- a/project/build.properties +++ /dev/null @@ -1 +0,0 @@ -sbt.version=0.13.5 \ No newline at end of file diff --git a/project/plugins.sbt b/project/plugins.sbt deleted file mode 100644 index 5ae46f7e6891..000000000000 --- a/project/plugins.sbt +++ /dev/null @@ -1,5 +0,0 @@ -addSbtPlugin("com.typesafe.sbt" % "sbt-pgp" % "0.8.2") - -addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.9.1") - -resolvers += "Sonatype OSS Releases" at "https://oss.sonatype.org/content/repositories/releases" \ No newline at end of file diff --git a/samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala b/samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala deleted file mode 100644 index e3083d662037..000000000000 --- a/samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala +++ /dev/null @@ -1,50 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicAndroidJavaGenerator - -object AndroidJavaPetstoreCodegen extends BasicAndroidJavaGenerator { - def main(args: Array[String]) = generateClient(args) - - // location of templates - override def templateDir = "src/main/resources/android-java" - - // where to write generated code - override def destinationDir = "samples/client/petstore/android-java/src/main/java" - - // package for api invoker, error files - override def invokerPackage = Some("com.wordnik.client") - - // package for models - override def modelPackage = Some("com.wordnik.petstore.model") - - // package for api classes - override def apiPackage = Some("com.wordnik.petstore.api") - - additionalParams ++= Map( - "artifactId" -> "swagger-petstore", - "artifactVersion" -> "1.0.0", - "groupId" -> "com.wordnik") - - // supporting classes - override def supportingFiles = List( - ("apiInvoker.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiInvoker.java"), - ("httpPatch.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "HttpPatch.java"), - ("jsonUtil.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "JsonUtil.java"), - ("apiException.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiException.java"), - ("pom.mustache", "samples/client/petstore/android-java", "pom.xml") - ) -} diff --git a/samples/client/petstore/android-java/pom.xml b/samples/client/petstore/android-java/pom.xml index 8bcb398bbab0..ef2be59b188b 100644 --- a/samples/client/petstore/android-java/pom.xml +++ b/samples/client/petstore/android-java/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.wordnik - swagger-petstore + io.swagger + swagger-client jar - swagger-petstore + swagger-client 1.0.0 scm:git:git@github.com:wordnik/swagger-mustache.git @@ -107,6 +107,11 @@ + + com.wordnik + swagger-annotations + ${swagger-annotations-version} + com.fasterxml.jackson.core jackson-core @@ -131,24 +136,6 @@ ${httpclient-version} compile - - org.apache.httpcomponents - httpcore - ${httpclient-version} - compile - - - org.apache.httpcomponents - httpmime - ${httpclient-version} - compile - - - com.google.android - android - 4.1.1.4 - compile - @@ -158,13 +145,18 @@ test - + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + + 1.5.1-M1 2.1.4 4.8.1 1.0.0 4.8.1 - 4.3 + 4.0 - diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/PetApi.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/PetApi.java deleted file mode 100644 index 26d8ee16b9ae..000000000000 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/PetApi.java +++ /dev/null @@ -1,538 +0,0 @@ -package com.wordnik.petstore.api; - -import com.wordnik.client.ApiException; -import com.wordnik.client.ApiInvoker; -import com.wordnik.petstore.model.Pet; -import java.util.*; -import java.io.File; - -import org.apache.http.NameValuePair; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.entity.mime.*; -import org.apache.http.entity.mime.content.*; -import org.apache.http.entity.ContentType; - -import android.webkit.MimeTypeMap; - -public class PetApi { - String basePath = "http://petstore.swagger.wordnik.com/api"; - ApiInvoker apiInvoker = ApiInvoker.getInstance(); - - public void addHeader(String key, String value) { - getInvoker().addDefaultHeader(key, value); - } - - public ApiInvoker getInvoker() { - return apiInvoker; - } - - public void setBasePath(String basePath) { - this.basePath = basePath; - } - - public String getBasePath() { - return basePath; - } - - private static String getMimeType(File file) { - MimeTypeMap mime = MimeTypeMap.getSingleton(); - int index = file.getName().lastIndexOf('.')+1; - String ext = file.getName().substring(index).toLowerCase(); - return mime.getMimeTypeFromExtension(ext); - } - - //error info- code: 400 reason: "Invalid ID supplied" model: - //error info- code: 404 reason: "Pet not found" model: - //error info- code: 405 reason: "Validation exception" model: - public void updatePet (Pet body) throws ApiException { - Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = body; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 405 reason: "Invalid input" model: - public void addPet (Pet body) throws ApiException { - Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json","application/xml"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = body; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid status value" model: - public List findPetsByStatus (String status) throws ApiException { - Object postBody = null; - // verify required params are set - if(status == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - if(!"null".equals(String.valueOf(status))) - queryParams.put("status", String.valueOf(status)); - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); - if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid tag value" model: - public List findPetsByTags (String tags) throws ApiException { - Object postBody = null; - // verify required params are set - if(tags == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - if(!"null".equals(String.valueOf(tags))) - queryParams.put("tags", String.valueOf(tags)); - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); - if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - //error info- code: 405 reason: "Invalid input" model: - public void updatePetWithForm (String petId, String name, String status) throws ApiException { - Object postBody = null; - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/x-www-form-urlencoded"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - hasFields = true; - mp.add(new BasicNameValuePair("name", name)); - hasFields = true; - mp.add(new BasicNameValuePair("status", status)); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - hasFields = true; - builder.addTextBody("name", name.toString()); - hasFields = true; - builder.addTextBody("status", status.toString()); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid ID supplied" model: - //error info- code: 404 reason: "Pet not found" model: - public Pet getPetById (Long petId) throws ApiException { - Object postBody = null; - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); - if(response != null){ - return (Pet) ApiInvoker.deserialize(response, "", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid pet value" model: - public void deletePet (String petId) throws ApiException { - Object postBody = null; - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid tag value" model: - public List partialUpdate (String petId, Pet body) throws ApiException { - Object postBody = body; - // verify required params are set - if(petId == null || body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json","application/xml"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = body; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "PATCH", queryParams, postBody, headerParams, contentType); - if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - public void uploadFile (String additionalMetadata, File file) throws ApiException { - Object postBody = null; - // create path and map variables - String path = "/pet/uploadImage".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "multipart/form-data"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - hasFields = true; - mp.add(new BasicNameValuePair("additionalMetadata", additionalMetadata)); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - hasFields = true; - builder.addTextBody("additionalMetadata", additionalMetadata.toString()); - hasFields = true; - builder.addBinaryBody("file", file, ContentType.create(getMimeType(file)), file.getName()); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - } - diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/StoreApi.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/StoreApi.java deleted file mode 100644 index 89a9a9f1bbb0..000000000000 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/StoreApi.java +++ /dev/null @@ -1,206 +0,0 @@ -package com.wordnik.petstore.api; - -import com.wordnik.client.ApiException; -import com.wordnik.client.ApiInvoker; -import com.wordnik.petstore.model.Order; -import java.util.*; -import java.io.File; - -import org.apache.http.NameValuePair; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.entity.mime.*; -import org.apache.http.entity.mime.content.*; -import org.apache.http.entity.ContentType; - -import android.webkit.MimeTypeMap; - -public class StoreApi { - String basePath = "http://petstore.swagger.wordnik.com/api"; - ApiInvoker apiInvoker = ApiInvoker.getInstance(); - - public void addHeader(String key, String value) { - getInvoker().addDefaultHeader(key, value); - } - - public ApiInvoker getInvoker() { - return apiInvoker; - } - - public void setBasePath(String basePath) { - this.basePath = basePath; - } - - public String getBasePath() { - return basePath; - } - - private static String getMimeType(File file) { - MimeTypeMap mime = MimeTypeMap.getSingleton(); - int index = file.getName().lastIndexOf('.')+1; - String ext = file.getName().substring(index).toLowerCase(); - return mime.getMimeTypeFromExtension(ext); - } - - //error info- code: 400 reason: "Invalid order" model: - public void placeOrder (Order body) throws ApiException { - Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/store/order".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = body; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid ID supplied" model: - //error info- code: 404 reason: "Order not found" model: - public void deleteOrder (String orderId) throws ApiException { - Object postBody = null; - // verify required params are set - if(orderId == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid ID supplied" model: - //error info- code: 404 reason: "Order not found" model: - public Order getOrderById (String orderId) throws ApiException { - Object postBody = null; - // verify required params are set - if(orderId == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); - if(response != null){ - return (Order) ApiInvoker.deserialize(response, "", Order.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - } - diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/UserApi.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/UserApi.java deleted file mode 100644 index 739e55802d00..000000000000 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/UserApi.java +++ /dev/null @@ -1,468 +0,0 @@ -package com.wordnik.petstore.api; - -import com.wordnik.client.ApiException; -import com.wordnik.client.ApiInvoker; -import com.wordnik.petstore.model.User; -import java.util.*; -import java.io.File; - -import org.apache.http.NameValuePair; -import org.apache.http.message.BasicNameValuePair; -import org.apache.http.entity.mime.*; -import org.apache.http.entity.mime.content.*; -import org.apache.http.entity.ContentType; - -import android.webkit.MimeTypeMap; - -public class UserApi { - String basePath = "http://petstore.swagger.wordnik.com/api"; - ApiInvoker apiInvoker = ApiInvoker.getInstance(); - - public void addHeader(String key, String value) { - getInvoker().addDefaultHeader(key, value); - } - - public ApiInvoker getInvoker() { - return apiInvoker; - } - - public void setBasePath(String basePath) { - this.basePath = basePath; - } - - public String getBasePath() { - return basePath; - } - - private static String getMimeType(File file) { - MimeTypeMap mime = MimeTypeMap.getSingleton(); - int index = file.getName().lastIndexOf('.')+1; - String ext = file.getName().substring(index).toLowerCase(); - return mime.getMimeTypeFromExtension(ext); - } - - public void createUsersWithArrayInput (List body) throws ApiException { - Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = body; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - public void createUsersWithListInput (List body) throws ApiException { - Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user/createWithList".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = body; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid username supplied" model: - //error info- code: 404 reason: "User not found" model: - public void updateUser (String username, User body) throws ApiException { - Object postBody = body; - // verify required params are set - if(username == null || body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = body; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid username supplied" model: - //error info- code: 404 reason: "User not found" model: - public void deleteUser (String username) throws ApiException { - Object postBody = null; - // verify required params are set - if(username == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid username supplied" model: - //error info- code: 404 reason: "User not found" model: - public User getUserByName (String username) throws ApiException { - Object postBody = null; - // verify required params are set - if(username == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); - if(response != null){ - return (User) ApiInvoker.deserialize(response, "", User.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid username and password combination" model: - public String loginUser (String username, String password) throws ApiException { - Object postBody = null; - // verify required params are set - if(username == null || password == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user/login".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - if(!"null".equals(String.valueOf(username))) - queryParams.put("username", String.valueOf(username)); - if(!"null".equals(String.valueOf(password))) - queryParams.put("password", String.valueOf(password)); - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); - if(response != null){ - return (String) ApiInvoker.deserialize(response, "", String.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - public void logoutUser () throws ApiException { - Object postBody = null; - // create path and map variables - String path = "/user/logout".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = null; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - public void createUser (User body) throws ApiException { - Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("application/x-www-form-urlencoded")) { - boolean hasFields = false; - List mp = new ArrayList(); - if(hasFields) - postBody = mp; - } - else if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - MultipartEntityBuilder builder = MultipartEntityBuilder.create(); - builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); - if(hasFields) - postBody = builder; - } - else { - postBody = body; - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - } - diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/client/ApiException.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiException.java similarity index 93% rename from samples/client/petstore/java/src/main/java/com/wordnik/client/ApiException.java rename to samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiException.java index a0131b5cf8c4..31bc8a0978ad 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/client/ApiException.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiException.java @@ -1,4 +1,4 @@ -package com.wordnik.client; +package io.swagger.client; public class ApiException extends Exception { int code = 0; @@ -26,4 +26,4 @@ public class ApiException extends Exception { public void setMessage(String message) { this.message = message; } -} +} \ No newline at end of file diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java similarity index 95% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/ApiInvoker.java rename to samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index fb2ba7f8ce52..6306e0734a96 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -1,4 +1,4 @@ -package com.wordnik.client.common; +package io.swagger.client; import com.fasterxml.jackson.core.JsonGenerator.Feature; @@ -184,6 +184,18 @@ public class ApiInvoker { } response = client.execute(delete); } + else if ("PATCH".equals(method)) { + HttpPatch patch = new HttpPatch(url); + + if (body != null) { + patch.setHeader("Content-Type", contentType); + patch.setEntity(new StringEntity(serialize(body), "UTF-8")); + } + for(String key : headers.keySet()) { + patch.setHeader(key, headers.get(key)); + } + response = client.execute(patch); + } int code = response.getStatusLine().getStatusCode(); String responseString = null; @@ -269,4 +281,3 @@ public class ApiInvoker { } } } - diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/HttpPatch.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/HttpPatch.java similarity index 90% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/client/HttpPatch.java rename to samples/client/petstore/android-java/src/main/java/io/swagger/client/HttpPatch.java index 07c94381d3b4..cb97056dbc94 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/HttpPatch.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/HttpPatch.java @@ -1,4 +1,4 @@ -package com.wordnik.client; +package io.swagger.client; import org.apache.http.client.methods.*; @@ -13,4 +13,4 @@ public class HttpPatch extends HttpPost { public String getMethod() { return METHOD_PATCH; } -} +} \ No newline at end of file diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/JsonUtil.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/JsonUtil.java similarity index 94% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/client/JsonUtil.java rename to samples/client/petstore/android-java/src/main/java/io/swagger/client/JsonUtil.java index 3d96fa3ac71c..90b99b48ec88 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/JsonUtil.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/JsonUtil.java @@ -1,4 +1,4 @@ -package com.wordnik.client; +package io.swagger.client; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; @@ -18,4 +18,3 @@ public class JsonUtil { return mapper; } } - diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 000000000000..7b58b8e5e024 --- /dev/null +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,339 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; + +import io.swagger.client.model.*; + +import java.util.*; + +import io.swagger.client.model.Pet; +import java.io.File; + +import java.util.Map; +import java.util.HashMap; +import java.io.File; + +public class PetApi { + String basePath = "http://petstore.swagger.io/v2"; + ApiInvoker apiInvoker = ApiInvoker.getInstance(); + + public void addHeader(String key, String value) { + getInvoker().addDefaultHeader(key, value); + } + + public ApiInvoker getInvoker() { + return apiInvoker; + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public String getBasePath() { + return basePath; + } + + + + public void updatePet (Pet body) throws ApiException { + Object postBody = body; + + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void addPet (Pet body) throws ApiException { + Object postBody = body; + + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public List findPetsByStatus (List status) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(status))) + queryParams.put("status", String.valueOf(status)); + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "array", Pet.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public List findPetsByTags (List tags) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(tags))) + queryParams.put("tags", String.valueOf(tags)); + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "array", Pet.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public Pet getPetById (Long petId) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (Pet) ApiInvoker.deserialize(response, "", Pet.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public void updatePetWithForm (String petId, String name, String status) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void deletePet (String api_key, Long petId) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + headerParams.put("api_key", api_key); + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + +} diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 000000000000..bdbce53ba3f6 --- /dev/null +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,186 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; + +import io.swagger.client.model.*; + +import java.util.*; + +import java.util.Map; +import io.swagger.client.model.Order; + +import java.util.Map; +import java.util.HashMap; +import java.io.File; + +public class StoreApi { + String basePath = "http://petstore.swagger.io/v2"; + ApiInvoker apiInvoker = ApiInvoker.getInstance(); + + public void addHeader(String key, String value) { + getInvoker().addDefaultHeader(key, value); + } + + public ApiInvoker getInvoker() { + return apiInvoker; + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public String getBasePath() { + return basePath; + } + + + + public Map getInventory () throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/store/inventory".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (Map) ApiInvoker.deserialize(response, "map", Map.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public Order placeOrder (Order body) throws ApiException { + Object postBody = body; + + + + // create path and map variables + String path = "/store/order".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (Order) ApiInvoker.deserialize(response, "", Order.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public Order getOrderById (String orderId) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (Order) ApiInvoker.deserialize(response, "", Order.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public void deleteOrder (String orderId) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + +} diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 000000000000..0328a002bf24 --- /dev/null +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,338 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; + +import io.swagger.client.model.*; + +import java.util.*; + +import io.swagger.client.model.User; +import java.util.*; + +import java.util.Map; +import java.util.HashMap; +import java.io.File; + +public class UserApi { + String basePath = "http://petstore.swagger.io/v2"; + ApiInvoker apiInvoker = ApiInvoker.getInstance(); + + public void addHeader(String key, String value) { + getInvoker().addDefaultHeader(key, value); + } + + public ApiInvoker getInvoker() { + return apiInvoker; + } + + public void setBasePath(String basePath) { + this.basePath = basePath; + } + + public String getBasePath() { + return basePath; + } + + + + public void createUser (User body) throws ApiException { + Object postBody = body; + + + + // create path and map variables + String path = "/user".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void createUsersWithArrayInput (List body) throws ApiException { + Object postBody = body; + + + + // create path and map variables + String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void createUsersWithListInput (List body) throws ApiException { + Object postBody = body; + + + + // create path and map variables + String path = "/user/createWithList".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public String loginUser (String username, String password) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/user/login".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(username))) + queryParams.put("username", String.valueOf(username)); + if(!"null".equals(String.valueOf(password))) + queryParams.put("password", String.valueOf(password)); + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (String) ApiInvoker.deserialize(response, "", String.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public void logoutUser () throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/user/logout".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public User getUserByName (String username) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (User) ApiInvoker.deserialize(response, "", User.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public void updateUser (String username, User body) throws ApiException { + Object postBody = body; + + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void deleteUser (String username) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + +} diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Category.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java similarity index 59% rename from samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Category.java rename to samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java index aa9303084bbd..3a7a84f89bb0 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Category.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java @@ -1,8 +1,21 @@ -package com.wordnik.petstore.model; +package io.swagger.client.model; -public class Category { + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Category { + private Long id = null; private String name = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -10,6 +23,11 @@ public class Category { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("name") public String getName() { return name; } @@ -17,14 +35,16 @@ public class Category { this.name = name; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Category {\n"); + sb.append(" id: ").append(id).append("\n"); sb.append(" name: ").append(name).append("\n"); sb.append("}\n"); return sb.toString(); } } - diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 000000000000..f516f66e1fe4 --- /dev/null +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,111 @@ +package io.swagger.client.model; + +import java.util.Date; + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + public enum StatusEnum { + placed, approved, delivered, + }; + private StatusEnum status = null; + private Boolean complete = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(required = false, value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" petId: ").append(petId).append("\n"); + sb.append(" quantity: ").append(quantity).append("\n"); + sb.append(" shipDate: ").append(shipDate).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" complete: ").append(complete).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Pet.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java similarity index 52% rename from samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Pet.java rename to samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java index b5a577d1a863..297e1360c70a 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Pet.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java @@ -1,18 +1,31 @@ -package com.wordnik.petstore.model; +package io.swagger.client.model; +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; import java.util.*; -import com.wordnik.petstore.model.Category; -import com.wordnik.petstore.model.Tag; -public class Pet { - /* unique identifier for the pet */ + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Pet { + private Long id = null; private Category category = null; private String name = null; - private List photoUrls = new ArrayList(); - private List tags = new ArrayList(); - /* pet status in the store */ - private String status = null; - //public enum statusEnum { available, pending, sold, }; + private List photoUrls = new ArrayList() ; + private List tags = new ArrayList() ; + public enum StatusEnum { + available, pending, sold, + }; + private StatusEnum status = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -20,6 +33,11 @@ public class Pet { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("category") public Category getCategory() { return category; } @@ -27,6 +45,11 @@ public class Pet { this.category = category; } + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("name") public String getName() { return name; } @@ -34,6 +57,11 @@ public class Pet { this.name = name; } + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } @@ -41,6 +69,11 @@ public class Pet { this.photoUrls = photoUrls; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("tags") public List getTags() { return tags; } @@ -48,17 +81,26 @@ public class Pet { this.tags = tags; } - public String getStatus() { + + /** + * pet status in the store + **/ + @ApiModelProperty(required = false, value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { return status; } - public void setStatus(String status) { + public void setStatus(StatusEnum status) { this.status = status; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Pet {\n"); + sb.append(" id: ").append(id).append("\n"); sb.append(" category: ").append(category).append("\n"); sb.append(" name: ").append(name).append("\n"); @@ -69,4 +111,3 @@ public class Pet { return sb.toString(); } } - diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Tag.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java similarity index 59% rename from samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Tag.java rename to samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java index 1134153c88cd..d9bf765477b3 100644 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Tag.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java @@ -1,8 +1,21 @@ -package com.wordnik.client.model; +package io.swagger.client.model; -public class Tag { + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Tag { + private Long id = null; private String name = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -10,6 +23,11 @@ public class Tag { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("name") public String getName() { return name; } @@ -17,14 +35,16 @@ public class Tag { this.name = name; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Tag {\n"); + sb.append(" id: ").append(id).append("\n"); sb.append(" name: ").append(name).append("\n"); sb.append("}\n"); return sb.toString(); } } - diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/User.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java similarity index 66% rename from samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/User.java rename to samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java index 4b28758addea..d82288e8c251 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/User.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java @@ -1,16 +1,27 @@ -package com.wordnik.petstore.model; +package io.swagger.client.model; -public class User { + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class User { + private Long id = null; - private String firstName = null; private String username = null; + private String firstName = null; private String lastName = null; private String email = null; private String password = null; private String phone = null; - /* User Status */ private Integer userStatus = null; - //public enum userStatusEnum { 1-registered, 2-active, 3-closed, }; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -18,13 +29,11 @@ public class User { this.id = id; } - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("username") public String getUsername() { return username; } @@ -32,6 +41,23 @@ public class User { this.username = username; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("lastName") public String getLastName() { return lastName; } @@ -39,6 +65,11 @@ public class User { this.lastName = lastName; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("email") public String getEmail() { return email; } @@ -46,6 +77,11 @@ public class User { this.email = email; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("password") public String getPassword() { return password; } @@ -53,6 +89,11 @@ public class User { this.password = password; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("phone") public String getPhone() { return phone; } @@ -60,6 +101,12 @@ public class User { this.phone = phone; } + + /** + * User Status + **/ + @ApiModelProperty(required = false, value = "User Status") + @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } @@ -67,13 +114,16 @@ public class User { this.userStatus = userStatus; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class User {\n"); + sb.append(" id: ").append(id).append("\n"); - sb.append(" firstName: ").append(firstName).append("\n"); sb.append(" username: ").append(username).append("\n"); + sb.append(" firstName: ").append(firstName).append("\n"); sb.append(" lastName: ").append(lastName).append("\n"); sb.append(" email: ").append(email).append("\n"); sb.append(" password: ").append(password).append("\n"); @@ -83,4 +133,3 @@ public class User { return sb.toString(); } } - diff --git a/samples/client/petstore/async-scala/build.sbt b/samples/client/petstore/async-scala/build.sbt new file mode 100644 index 000000000000..43a13d0af07d --- /dev/null +++ b/samples/client/petstore/async-scala/build.sbt @@ -0,0 +1,11 @@ +organization := "" + +name := "-client" + +libraryDependencies += "com.wordnik.swagger" %% "swagger-async-httpclient" % "0.3.5" + +libraryDependencies += "joda-time" % "joda-time" % "2.3" + +libraryDependencies += "org.joda" % "joda-convert" % "1.3.1" + +libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.0.13" % "provided" diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/SwaggerClient.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/SwaggerClient.scala new file mode 100644 index 000000000000..94b3d65f3df3 --- /dev/null +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/SwaggerClient.scala @@ -0,0 +1,27 @@ +package io.swagger.client + +import io.swagger.client.api._ + +import com.wordnik.swagger.client._ + +import java.io.Closeable + +class SwaggerClient(config: SwaggerConfig) extends Closeable { + val locator = config.locator + val name = config.name + + private[this] val client = transportClient + + protected def transportClient: TransportClient = new RestClient(config) + + val user = new UserApi(client, config) + + val pet = new PetApi(client, config) + + val store = new StoreApi(client, config) + + + def close() { + client.close() + } +} \ No newline at end of file diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala new file mode 100644 index 000000000000..3ac13f724dcb --- /dev/null +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -0,0 +1,193 @@ +package io.swagger.client.api + +import io.swagger.client.model.Pet +import java.io.File +import com.wordnik.swagger.client._ +import scala.concurrent.{ Future, Await } +import scala.concurrent.duration._ +import collection.mutable + +class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { + + + def updatePet(body: Pet)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def addPet(body: Pet)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def findPetsByStatus(status: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { + // create path and map variables + val path = (addFmt("/pet/findByStatus")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + if(status != null) queryParams += "status" -> status.toString + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def findPetsByTags(tags: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { + // create path and map variables + val path = (addFmt("/pet/findByTags")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + if(tags != null) queryParams += "tags" -> tags.toString + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def updatePetWithForm(petId: String, + name: String, + status: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def deletePet(api_key: String, + petId: Long)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + headerParams += "api_key" -> api_key.toString + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def uploadFile(petId: Long, + additionalMetadata: String, + file: File)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}/uploadImage") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + +} diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala new file mode 100644 index 000000000000..60011e73b6da --- /dev/null +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -0,0 +1,99 @@ +package io.swagger.client.api + +import io.swagger.client.model.Order +import com.wordnik.swagger.client._ +import scala.concurrent.{ Future, Await } +import scala.concurrent.duration._ +import collection.mutable + +class StoreApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { + + + def getInventory()(implicit reader: ClientResponseReader[Map[String, Integer]]): Future[Map[String, Integer]] = { + // create path and map variables + val path = (addFmt("/store/inventory")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def placeOrder(body: Order)(implicit reader: ClientResponseReader[Order], writer: RequestWriter[Order]): Future[Order] = { + // create path and map variables + val path = (addFmt("/store/order")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def getOrderById(orderId: String)(implicit reader: ClientResponseReader[Order]): Future[Order] = { + // create path and map variables + val path = (addFmt("/store/order/{orderId}") + replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/store/order/{orderId}") + replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + +} diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala new file mode 100644 index 000000000000..778d1cae177f --- /dev/null +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -0,0 +1,188 @@ +package io.swagger.client.api + +import io.swagger.client.model.User +import com.wordnik.swagger.client._ +import scala.concurrent.{ Future, Await } +import scala.concurrent.duration._ +import collection.mutable + +class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { + + + def createUser(body: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def createUsersWithArrayInput(body: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/createWithArray")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def createUsersWithListInput(body: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/createWithList")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def loginUser(username: String, + password: String)(implicit reader: ClientResponseReader[String]): Future[String] = { + // create path and map variables + val path = (addFmt("/user/login")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + if(username != null) queryParams += "username" -> username.toString + if(password != null) queryParams += "password" -> password.toString + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def logoutUser()(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/logout")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll ("\\{" + "username" + "\\}",username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def updateUser(username: String, + body: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll ("\\{" + "username" + "\\}",username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll ("\\{" + "username" + "\\}",username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + +} diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Category.scala new file mode 100644 index 000000000000..1b410e7c59ea --- /dev/null +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Category.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + +case class Category ( + id: Long, + name: String + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Order.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Order.scala new file mode 100644 index 000000000000..f7a10a449657 --- /dev/null +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Order.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + +case class Order ( + id: Long, + petId: Long, + quantity: Integer, + shipDate: DateTime, + status: String, // Order Status + complete: Boolean + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Pet.scala new file mode 100644 index 000000000000..7e76c72914b1 --- /dev/null +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + +case class Pet ( + id: Long, + category: Category, + name: String, + photoUrls: List[String], + tags: List[Tag], + status: String // pet status in the store + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Tag.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Tag.scala new file mode 100644 index 000000000000..9dfe60d36f8b --- /dev/null +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Tag.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + +case class Tag ( + id: Long, + name: String + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/User.scala new file mode 100644 index 000000000000..598adae451ad --- /dev/null +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/User.scala @@ -0,0 +1,16 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + +case class User ( + id: Long, + username: String, + firstName: String, + lastName: String, + email: String, + password: String, + phone: String, + userStatus: Integer // User Status + +) diff --git a/samples/client/petstore/java/JavaPetstoreCodegen.scala b/samples/client/petstore/java/JavaPetstoreCodegen.scala deleted file mode 100644 index 1e23a176813b..000000000000 --- a/samples/client/petstore/java/JavaPetstoreCodegen.scala +++ /dev/null @@ -1,49 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicJavaGenerator - -object JavaPetstoreCodegen extends BasicJavaGenerator { - def main(args: Array[String]) = generateClient(args) - - // location of templates - override def templateDir = "src/main/resources/Java" - - // where to write generated code - override def destinationDir = "samples/client/petstore/java/src/main/java" - - // package for api invoker, error files - override def invokerPackage = Some("com.wordnik.client") - - // package for models - override def modelPackage = Some("com.wordnik.petstore.model") - - // package for api classes - override def apiPackage = Some("com.wordnik.petstore.api") - - additionalParams ++= Map( - "artifactId" -> "swagger-petstore", - "artifactVersion" -> "1.0.0", - "groupId" -> "com.wordnik") - - // supporting classes - override def supportingFiles = - List( - ("apiInvoker.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiInvoker.java"), - ("JsonUtil.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "JsonUtil.java"), - ("apiException.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiException.java"), - ("pom.mustache", "samples/client/petstore/java", "pom.xml")) -} diff --git a/samples/client/petstore/java/pom.xml b/samples/client/petstore/java/pom.xml index 2f685c3927b8..10b1a29476f4 100644 --- a/samples/client/petstore/java/pom.xml +++ b/samples/client/petstore/java/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.wordnik - swagger-petstore + io.swagger + swagger-client jar - swagger-petstore + swagger-client 1.0.0 scm:git:git@github.com:wordnik/swagger-mustache.git @@ -107,35 +107,35 @@ + + com.wordnik + swagger-annotations + ${swagger-annotations-version} + com.sun.jersey jersey-client ${jersey-version} - compile com.sun.jersey.contribs jersey-multipart ${jersey-version} - compile com.fasterxml.jackson.core jackson-core ${jackson-version} - compile com.fasterxml.jackson.core jackson-annotations ${jackson-version} - compile com.fasterxml.jackson.core jackson-databind ${jackson-version} - compile com.fasterxml.jackson.datatype @@ -146,7 +146,6 @@ joda-time joda-time ${jodatime-version} - compile @@ -157,8 +156,8 @@ test - + 1.5.0-M1 1.7 2.1.4 2.3 @@ -167,4 +166,3 @@ 4.8.1 - diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Order.java b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Order.java deleted file mode 100644 index c44ea0f38cc1..000000000000 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Order.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.wordnik.petstore.model; - -import java.util.Date; -public class Order { - private Long id = null; - private Long petId = null; - private Integer quantity = null; - /* Order Status */ - private String status = null; - //public enum statusEnum { placed, approved, delivered, }; - private Date shipDate = null; - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - public Long getPetId() { - return petId; - } - public void setPetId(Long petId) { - this.petId = petId; - } - - public Integer getQuantity() { - return quantity; - } - public void setQuantity(Integer quantity) { - this.quantity = quantity; - } - - public String getStatus() { - return status; - } - public void setStatus(String status) { - this.status = status; - } - - public Date getShipDate() { - return shipDate; - } - public void setShipDate(Date shipDate) { - this.shipDate = shipDate; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Order {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" petId: ").append(petId).append("\n"); - sb.append(" quantity: ").append(quantity).append("\n"); - sb.append(" status: ").append(status).append("\n"); - sb.append(" shipDate: ").append(shipDate).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} - diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiException.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java similarity index 93% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiException.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java index a0131b5cf8c4..31bc8a0978ad 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiException.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiException.java @@ -1,4 +1,4 @@ -package com.wordnik.client; +package io.swagger.client; public class ApiException extends Exception { int code = 0; @@ -26,4 +26,4 @@ public class ApiException extends Exception { public void setMessage(String message) { this.message = message; } -} +} \ No newline at end of file diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/client/ApiInvoker.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java similarity index 96% rename from samples/client/petstore/java/src/main/java/com/wordnik/client/ApiInvoker.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java index 7843d0a512f2..966a141c03de 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/client/ApiInvoker.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java @@ -1,4 +1,4 @@ -package com.wordnik.client; +package io.swagger.client; import com.fasterxml.jackson.core.JsonGenerator.Feature; import com.fasterxml.jackson.databind.*; @@ -51,8 +51,11 @@ public class ApiInvoker { } public static Object deserialize(String json, String containerType, Class cls) throws ApiException { + if(null != containerType) { + containerType = containerType.toLowerCase(); + } try{ - if("List".equals(containerType)) { + if("list".equals(containerType) || "array".equals(containerType)) { JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls); List response = (List) JsonUtil.getJsonMapper().readValue(json, typeInfo); return response; @@ -185,4 +188,3 @@ public class ApiInvoker { return hostMap.get(host); } } - diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/client/JsonUtil.java b/samples/client/petstore/java/src/main/java/io/swagger/client/JsonUtil.java similarity index 95% rename from samples/client/petstore/java/src/main/java/com/wordnik/client/JsonUtil.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/JsonUtil.java index da0fca7816e1..8e7e686dd0ce 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/client/JsonUtil.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/JsonUtil.java @@ -1,4 +1,4 @@ -package com.wordnik.client; +package io.swagger.client; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; @@ -21,4 +21,3 @@ public class JsonUtil { return mapper; } } - diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/PetApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java similarity index 67% rename from samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/PetApi.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java index 5331ebfac9a0..53c1d55fb680 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/PetApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java @@ -1,276 +1,45 @@ -package com.wordnik.petstore.api; +package io.swagger.client.api; -import com.wordnik.client.ApiException; -import com.wordnik.client.ApiInvoker; +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; + +import io.swagger.client.model.*; + +import java.util.*; + +import io.swagger.client.model.Pet; +import java.io.File; -import com.wordnik.petstore.model.Pet; import com.sun.jersey.multipart.FormDataMultiPart; import javax.ws.rs.core.MediaType; import java.io.File; -import java.util.*; +import java.util.Map; +import java.util.HashMap; public class PetApi { - String basePath = "http://petstore.swagger.wordnik.com/api"; + String basePath = "http://petstore.swagger.io/v2"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public ApiInvoker getInvoker() { return apiInvoker; } - + public void setBasePath(String basePath) { this.basePath = basePath; } - + public String getBasePath() { return basePath; } - //error info- code: 400 reason: "Invalid ID supplied" model: - //error info- code: 404 reason: "Pet not found" model: - public Pet getPetById (Long petId) throws ApiException { - Object postBody = null; - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return (Pet) ApiInvoker.deserialize(response, "", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - //error info- code: 405 reason: "Invalid input" model: - public void updatePetWithForm (String petId, String name, String status) throws ApiException { - Object postBody = null; - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "application/x-www-form-urlencoded"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - hasFields = true; - mp.field("name", name, MediaType.MULTIPART_FORM_DATA_TYPE); - hasFields = true; - mp.field("status", status, MediaType.MULTIPART_FORM_DATA_TYPE); - if(hasFields) - postBody = mp; - } - else { - formParams.put("name", name);formParams.put("status", status);} - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid pet value" model: - public void deletePet (String petId) throws ApiException { - Object postBody = null; - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid tag value" model: - public List partialUpdate (String petId, Pet body) throws ApiException { - Object postBody = body; - // verify required params are set - if(petId == null || body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "application/json","application/xml"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "PATCH", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - //error info- code: 405 reason: "Invalid input" model: - public void addPet (Pet body) throws ApiException { - Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "application/json","application/xml"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid ID supplied" model: - //error info- code: 404 reason: "Pet not found" model: - //error info- code: 405 reason: "Validation exception" model: + + public void updatePet (Pet body) throws ApiException { Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } + + // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -279,19 +48,24 @@ public class PetApi { Map headerParams = new HashMap(); Map formParams = new HashMap(); + + String[] contentTypes = { - "application/json"}; + "application/json","application/xml" + }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if(contentType.startsWith("multipart/form-data")) { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); + if(hasFields) postBody = mp; } else { - } + + } try { String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType); @@ -310,129 +84,38 @@ public class PetApi { } } } - //error info- code: 400 reason: "Invalid status value" model: - public List findPetsByStatus (String status) throws ApiException { - Object postBody = null; - // verify required params are set - if(status == null ) { - throw new ApiException(400, "missing required params"); - } + + + public void addPet (Pet body) throws ApiException { + Object postBody = body; + + // create path and map variables - String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + String path = "/pet".replaceAll("\\{format\\}","json"); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); Map formParams = new HashMap(); - if(!"null".equals(String.valueOf(status))) - queryParams.put("status", String.valueOf(status)); + + String[] contentTypes = { - "application/json"}; + "application/json","application/xml" + }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if(contentType.startsWith("multipart/form-data")) { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); + if(hasFields) postBody = mp; } else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } + } - } - //error info- code: 400 reason: "Invalid tag value" model: - public List findPetsByTags (String tags) throws ApiException { - Object postBody = null; - // verify required params are set - if(tags == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - if(!"null".equals(String.valueOf(tags))) - queryParams.put("tags", String.valueOf(tags)); - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - public void uploadFile (String additionalMetadata, File file) throws ApiException { - Object postBody = null; - // create path and map variables - String path = "/pet/uploadImage".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "multipart/form-data"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - hasFields = true; - mp.field("additionalMetadata", additionalMetadata, MediaType.MULTIPART_FORM_DATA_TYPE); - hasFields = true; - mp.field("file", file, MediaType.MULTIPART_FORM_DATA_TYPE); - if(hasFields) - postBody = mp; - } - else { - formParams.put("additionalMetadata", additionalMetadata);} try { String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); @@ -451,5 +134,330 @@ public class PetApi { } } } - } + + + public List findPetsByStatus (List status) throws ApiException { + Object postBody = null; + + // create path and map variables + String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + if(!"null".equals(String.valueOf(status))) + queryParams.put("status", String.valueOf(status)); + + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "array", Pet.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public List findPetsByTags (List tags) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + if(!"null".equals(String.valueOf(tags))) + queryParams.put("tags", String.valueOf(tags)); + + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "array", Pet.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public Pet getPetById (Long petId) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return (Pet) ApiInvoker.deserialize(response, "", Pet.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public void updatePetWithForm (String petId, String name, String status) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + hasFields = true; + mp.field("name", name, MediaType.MULTIPART_FORM_DATA_TYPE); + + hasFields = true; + mp.field("status", status, MediaType.MULTIPART_FORM_DATA_TYPE); + + if(hasFields) + postBody = mp; + } + else { + formParams.put("name", name); + formParams.put("status", status); + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void deletePet (String api_key, Long petId) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + headerParams.put("api_key", api_key); + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + String[] contentTypes = { + "multipart/form-data" + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + hasFields = true; + mp.field("additionalMetadata", additionalMetadata, MediaType.MULTIPART_FORM_DATA_TYPE); + + hasFields = true; + mp.field("file", file, MediaType.MULTIPART_FORM_DATA_TYPE); + + if(hasFields) + postBody = mp; + } + else { + formParams.put("additionalMetadata", additionalMetadata); + + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + +} diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/StoreApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java similarity index 64% rename from samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/StoreApi.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java index 6346fd6bd6ab..1da751915478 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/StoreApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,39 +1,95 @@ -package com.wordnik.petstore.api; +package io.swagger.client.api; -import com.wordnik.client.ApiException; -import com.wordnik.client.ApiInvoker; +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; + +import io.swagger.client.model.*; + +import java.util.*; + +import java.util.Map; +import io.swagger.client.model.Order; -import com.wordnik.petstore.model.Order; import com.sun.jersey.multipart.FormDataMultiPart; import javax.ws.rs.core.MediaType; import java.io.File; -import java.util.*; +import java.util.Map; +import java.util.HashMap; public class StoreApi { - String basePath = "http://petstore.swagger.wordnik.com/api"; + String basePath = "http://petstore.swagger.io/v2"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public ApiInvoker getInvoker() { return apiInvoker; } - + public void setBasePath(String basePath) { this.basePath = basePath; } - + public String getBasePath() { return basePath; } - //error info- code: 400 reason: "Invalid order" model: - public void placeOrder (Order body) throws ApiException { - Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); + + + public Map getInventory () throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/store/inventory".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; } + else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return (Map) ApiInvoker.deserialize(response, "map", Map.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public Order placeOrder (Order body) throws ApiException { + Object postBody = body; + + // create path and map variables String path = "/store/order".replaceAll("\\{format\\}","json"); @@ -42,66 +98,126 @@ public class StoreApi { Map headerParams = new HashMap(); Map formParams = new HashMap(); + + String[] contentTypes = { - "application/json"}; + + }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if(contentType.startsWith("multipart/form-data")) { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); + if(hasFields) postBody = mp; } else { - } + + } try { String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return ; + return (Order) ApiInvoker.deserialize(response, "", Order.class); } else { - return ; + return null; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return ; + return null; } else { throw ex; } } } - //error info- code: 400 reason: "Invalid ID supplied" model: - //error info- code: 404 reason: "Order not found" model: - public void deleteOrder (String orderId) throws ApiException { + + + public Order getOrderById (String orderId) throws ApiException { Object postBody = null; - // verify required params are set - if(orderId == null ) { - throw new ApiException(400, "missing required params"); - } + + // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); Map formParams = new HashMap(); + + String[] contentTypes = { - "application/json"}; + + }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if(contentType.startsWith("multipart/form-data")) { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); + if(hasFields) postBody = mp; } else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return (Order) ApiInvoker.deserialize(response, "", Order.class); } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public void deleteOrder (String orderId) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } try { String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); @@ -120,52 +236,5 @@ public class StoreApi { } } } - //error info- code: 400 reason: "Invalid ID supplied" model: - //error info- code: 404 reason: "Order not found" model: - public Order getOrderById (String orderId) throws ApiException { - Object postBody = null; - // verify required params are set - if(orderId == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return (Order) ApiInvoker.deserialize(response, "", Order.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - } - + +} diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/UserApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java similarity index 81% rename from samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/UserApi.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java index 15c43547461c..2da4c6ae32e4 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/UserApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java @@ -1,61 +1,377 @@ -package com.wordnik.petstore.api; +package io.swagger.client.api; -import com.wordnik.client.ApiException; -import com.wordnik.client.ApiInvoker; +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; + +import io.swagger.client.model.*; + +import java.util.*; + +import io.swagger.client.model.User; +import java.util.*; -import com.wordnik.petstore.model.User; import com.sun.jersey.multipart.FormDataMultiPart; import javax.ws.rs.core.MediaType; import java.io.File; -import java.util.*; +import java.util.Map; +import java.util.HashMap; public class UserApi { - String basePath = "http://petstore.swagger.wordnik.com/api"; + String basePath = "http://petstore.swagger.io/v2"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public ApiInvoker getInvoker() { return apiInvoker; } - + public void setBasePath(String basePath) { this.basePath = basePath; } - + public String getBasePath() { return basePath; } - //error info- code: 400 reason: "Invalid username supplied" model: - //error info- code: 404 reason: "User not found" model: - public void updateUser (String username, User body) throws ApiException { + + + public void createUser (User body) throws ApiException { Object postBody = body; - // verify required params are set - if(username == null || body == null ) { - throw new ApiException(400, "missing required params"); - } + + // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + String path = "/user".replaceAll("\\{format\\}","json"); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); Map formParams = new HashMap(); + + String[] contentTypes = { - "application/json"}; + + }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if(contentType.startsWith("multipart/form-data")) { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); + if(hasFields) postBody = mp; } else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return ; } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void createUsersWithArrayInput (List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void createUsersWithListInput (List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithList".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public String loginUser (String username, String password) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/login".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + if(!"null".equals(String.valueOf(username))) + queryParams.put("username", String.valueOf(username)); + if(!"null".equals(String.valueOf(password))) + queryParams.put("password", String.valueOf(password)); + + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return (String) ApiInvoker.deserialize(response, "", String.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public void logoutUser () throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/logout".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public User getUserByName (String username) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + if(response != null){ + return (User) ApiInvoker.deserialize(response, "", User.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public void updateUser (String username, User body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + String[] contentTypes = { + + }; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } try { String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType); @@ -74,35 +390,39 @@ public class UserApi { } } } - //error info- code: 400 reason: "Invalid username supplied" model: - //error info- code: 404 reason: "User not found" model: + + public void deleteUser (String username) throws ApiException { Object postBody = null; - // verify required params are set - if(username == null ) { - throw new ApiException(400, "missing required params"); - } + + // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); Map formParams = new HashMap(); + + String[] contentTypes = { - "application/json"}; + + }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; if(contentType.startsWith("multipart/form-data")) { boolean hasFields = false; FormDataMultiPart mp = new FormDataMultiPart(); + if(hasFields) postBody = mp; } else { - } + + } try { String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); @@ -121,278 +441,5 @@ public class UserApi { } } } - //error info- code: 400 reason: "Invalid username supplied" model: - //error info- code: 404 reason: "User not found" model: - public User getUserByName (String username) throws ApiException { - Object postBody = null; - // verify required params are set - if(username == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return (User) ApiInvoker.deserialize(response, "", User.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - //error info- code: 400 reason: "Invalid username and password combination" model: - public String loginUser (String username, String password) throws ApiException { - Object postBody = null; - // verify required params are set - if(username == null || password == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user/login".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - if(!"null".equals(String.valueOf(username))) - queryParams.put("username", String.valueOf(username)); - if(!"null".equals(String.valueOf(password))) - queryParams.put("password", String.valueOf(password)); - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return (String) ApiInvoker.deserialize(response, "", String.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - public void logoutUser () throws ApiException { - Object postBody = null; - // create path and map variables - String path = "/user/logout".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - public void createUsersWithArrayInput (List body) throws ApiException { - Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - public void createUsersWithListInput (List body) throws ApiException { - Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user/createWithList".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - public void createUser (User body) throws ApiException { - Object postBody = body; - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/user".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - String[] contentTypes = { - "application/json"}; - - String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - if(hasFields) - postBody = mp; - } - else { - } - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - } - + +} diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Category.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java similarity index 59% rename from samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Category.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java index 5db61363817a..3a7a84f89bb0 100644 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Category.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Category.java @@ -1,8 +1,21 @@ -package com.wordnik.client.model; +package io.swagger.client.model; -public class Category { + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Category { + private Long id = null; private String name = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -10,6 +23,11 @@ public class Category { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("name") public String getName() { return name; } @@ -17,14 +35,16 @@ public class Category { this.name = name; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Category {\n"); + sb.append(" id: ").append(id).append("\n"); sb.append(" name: ").append(name).append("\n"); sb.append("}\n"); return sb.toString(); } } - diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 000000000000..f516f66e1fe4 --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,111 @@ +package io.swagger.client.model; + +import java.util.Date; + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Order { + + private Long id = null; + private Long petId = null; + private Integer quantity = null; + private Date shipDate = null; + public enum StatusEnum { + placed, approved, delivered, + }; + private StatusEnum status = null; + private Boolean complete = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("petId") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("quantity") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("shipDate") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(required = false, value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" petId: ").append(petId).append("\n"); + sb.append(" quantity: ").append(quantity).append("\n"); + sb.append(" shipDate: ").append(shipDate).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" complete: ").append(complete).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Pet.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java similarity index 52% rename from samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Pet.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java index fe237edb479a..297e1360c70a 100644 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Pet.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java @@ -1,23 +1,31 @@ -package com.wordnik.client.model; +package io.swagger.client.model; +import io.swagger.client.model.Category; +import io.swagger.client.model.Tag; import java.util.*; -import com.wordnik.client.model.Category; -import com.wordnik.client.model.Tag; -public class Pet { - private List tags = new ArrayList(); + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Pet { + private Long id = null; private Category category = null; - /* pet status in the store */ - private String status = null; private String name = null; - private List photoUrls = new ArrayList(); - public List getTags() { - return tags; - } - public void setTags(List tags) { - this.tags = tags; - } + private List photoUrls = new ArrayList() ; + private List tags = new ArrayList() ; + public enum StatusEnum { + available, pending, sold, + }; + private StatusEnum status = null; + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -25,6 +33,11 @@ public class Pet { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("category") public Category getCategory() { return category; } @@ -32,13 +45,11 @@ public class Pet { this.category = category; } - public String getStatus() { - return status; - } - public void setStatus(String status) { - this.status = status; - } - + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("name") public String getName() { return name; } @@ -46,6 +57,11 @@ public class Pet { this.name = name; } + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } @@ -53,18 +69,45 @@ public class Pet { this.photoUrls = photoUrls; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("tags") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(required = false, value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Pet {\n"); - sb.append(" tags: ").append(tags).append("\n"); + sb.append(" id: ").append(id).append("\n"); sb.append(" category: ").append(category).append("\n"); - sb.append(" status: ").append(status).append("\n"); sb.append(" name: ").append(name).append("\n"); sb.append(" photoUrls: ").append(photoUrls).append("\n"); + sb.append(" tags: ").append(tags).append("\n"); + sb.append(" status: ").append(status).append("\n"); sb.append("}\n"); return sb.toString(); } } - diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Tag.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java similarity index 59% rename from samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Tag.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java index 886a5a6513be..d9bf765477b3 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Tag.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Tag.java @@ -1,8 +1,21 @@ -package com.wordnik.petstore.model; +package io.swagger.client.model; -public class Tag { + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Tag { + private Long id = null; private String name = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -10,6 +23,11 @@ public class Tag { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("name") public String getName() { return name; } @@ -17,14 +35,16 @@ public class Tag { this.name = name; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Tag {\n"); + sb.append(" id: ").append(id).append("\n"); sb.append(" name: ").append(name).append("\n"); sb.append("}\n"); return sb.toString(); } } - diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/User.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java similarity index 66% rename from samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/User.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java index e1199accc3cf..d82288e8c251 100644 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/User.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/User.java @@ -1,15 +1,27 @@ -package com.wordnik.client.model; +package io.swagger.client.model; -public class User { + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class User { + private Long id = null; - private String lastName = null; - private String phone = null; private String username = null; - private String email = null; - /* User Status */ - private Integer userStatus = null; private String firstName = null; + private String lastName = null; + private String email = null; private String password = null; + private String phone = null; + private Integer userStatus = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -17,20 +29,11 @@ public class User { this.id = id; } - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getPhone() { - return phone; - } - public void setPhone(String phone) { - this.phone = phone; - } - + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("username") public String getUsername() { return username; } @@ -38,20 +41,11 @@ public class User { this.username = username; } - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - - public Integer getUserStatus() { - return userStatus; - } - public void setUserStatus(Integer userStatus) { - this.userStatus = userStatus; - } - + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("firstName") public String getFirstName() { return firstName; } @@ -59,6 +53,35 @@ public class User { this.firstName = firstName; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("lastName") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("email") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("password") public String getPassword() { return password; } @@ -66,20 +89,47 @@ public class User { this.password = password; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("phone") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(required = false, value = "User Status") + @JsonProperty("userStatus") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class User {\n"); + sb.append(" id: ").append(id).append("\n"); - sb.append(" lastName: ").append(lastName).append("\n"); - sb.append(" phone: ").append(phone).append("\n"); sb.append(" username: ").append(username).append("\n"); - sb.append(" email: ").append(email).append("\n"); - sb.append(" userStatus: ").append(userStatus).append("\n"); sb.append(" firstName: ").append(firstName).append("\n"); + sb.append(" lastName: ").append(lastName).append("\n"); + sb.append(" email: ").append(email).append("\n"); sb.append(" password: ").append(password).append("\n"); + sb.append(" phone: ").append(phone).append("\n"); + sb.append(" userStatus: ").append(userStatus).append("\n"); sb.append("}\n"); return sb.toString(); } } - diff --git a/samples/client/petstore/objc/ObjcPetstoreCodegen.scala b/samples/client/petstore/objc/ObjcPetstoreCodegen.scala deleted file mode 100644 index 5fc062a4515f..000000000000 --- a/samples/client/petstore/objc/ObjcPetstoreCodegen.scala +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicObjcGenerator - -object ObjcPetstoreCodegen extends BasicObjcGenerator { - def main(args: Array[String]) = generateClient(args) - - // where to write generated code - val outputFolder = "samples/client/petstore/objc/" - override def destinationDir = outputFolder + java.io.File.separator + "client" - - override def templateDir = "objc" - - additionalParams ++= Map("projectName" -> "PetstoreClient") - - // supporting classes - override def supportingFiles = - List( - ("SWGObject.h", destinationDir, "SWGObject.h"), - ("SWGObject.m", destinationDir, "SWGObject.m"), - ("SWGApiClient.h", destinationDir, "SWGApiClient.h"), - ("SWGApiClient.m", destinationDir, "SWGApiClient.m"), - ("SWGFile.h", destinationDir, "SWGFile.h"), - ("SWGFile.m", destinationDir, "SWGFile.m"), - ("SWGDate.h", destinationDir, "SWGDate.h"), - ("SWGDate.m", destinationDir, "SWGDate.m"), - ("Podfile.mustache", outputFolder, "Podfile") - ) -} diff --git a/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout b/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout index 66f3c15bca7c..fafd21fb8eba 100644 --- a/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout +++ b/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout @@ -10,29 +10,29 @@ PetstoreClient IDESourceControlProjectOriginsDictionary - 92840518-904D-4771-AA3D-9AF52CA48B71 + E5BBF0AA85077C865C95437976D06D819733A208 ssh://github.com/wordnik/swagger-codegen.git IDESourceControlProjectPath samples/client/petstore/objc/PetstoreClient.xcworkspace IDESourceControlProjectRelativeInstallPathDictionary - 92840518-904D-4771-AA3D-9AF52CA48B71 + E5BBF0AA85077C865C95437976D06D819733A208 ../../../../.. IDESourceControlProjectURL ssh://github.com/wordnik/swagger-codegen.git IDESourceControlProjectVersion - 110 + 111 IDESourceControlProjectWCCIdentifier - 92840518-904D-4771-AA3D-9AF52CA48B71 + E5BBF0AA85077C865C95437976D06D819733A208 IDESourceControlProjectWCConfigurations IDESourceControlRepositoryExtensionIdentifierKey public.vcs.git IDESourceControlWCCIdentifierKey - 92840518-904D-4771-AA3D-9AF52CA48B71 + E5BBF0AA85077C865C95437976D06D819733A208 IDESourceControlWCCName swagger-codegen diff --git a/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata/tony.xcuserdatad/UserInterfaceState.xcuserstate b/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata/tony.xcuserdatad/UserInterfaceState.xcuserstate deleted file mode 100644 index 86db4ca5035c..000000000000 Binary files a/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata/tony.xcuserdatad/UserInterfaceState.xcuserstate and /dev/null differ diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj index 65087ed0f36a..349c3f59a88b 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj @@ -36,6 +36,8 @@ EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85E11811D3AE00F06E69 /* SWGUser.m */; }; EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */; }; EAEA85F11811D8F100F06E69 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = EAEA85F01811D8F100F06E69 /* libPods.a */; }; + EAFBEABB1A925B8500A27431 /* test-1.png in Resources */ = {isa = PBXBuildFile; fileRef = EAFBEABA1A925B8500A27431 /* test-1.png */; }; + EAFBEABE1A92C42700A27431 /* SWGApiResponse.m in Sources */ = {isa = PBXBuildFile; fileRef = EAFBEABD1A92C42700A27431 /* SWGApiResponse.m */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -50,7 +52,8 @@ /* Begin PBXFileReference section */ 73DA4F1067C343C3962F1542 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; }; - EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.xcconfig; path = ../Pods/Pods.xcconfig; sourceTree = ""; }; + A425648B5C0A4849C7668069 /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = ""; }; + E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = ""; }; EA6699961811D2FA00A70D03 /* PetstoreClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PetstoreClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; EA6699991811D2FA00A70D03 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; @@ -95,7 +98,10 @@ EAEA85E11811D3AE00F06E69 /* SWGUser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGUser.m; sourceTree = ""; }; EAEA85E21811D3AE00F06E69 /* SWGUserApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGUserApi.h; sourceTree = ""; }; EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGUserApi.m; sourceTree = ""; }; - EAEA85F01811D8F100F06E69 /* libPods.a */ = {isa = PBXFileReference; lastKnownFileType = file; name = libPods.a; path = "../Pods/build/Debug-iphoneos/libPods.a"; sourceTree = ""; }; + EAEA85F01811D8F100F06E69 /* libPods.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; name = libPods.a; path = "../Pods/build/Debug-iphoneos/libPods.a"; sourceTree = ""; }; + EAFBEABA1A925B8500A27431 /* test-1.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "test-1.png"; sourceTree = ""; }; + EAFBEABC1A92C42700A27431 /* SWGApiResponse.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGApiResponse.h; sourceTree = ""; }; + EAFBEABD1A92C42700A27431 /* SWGApiResponse.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiResponse.m; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -124,6 +130,15 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 1A15B3DE4358A178ABAEC251 /* Pods */ = { + isa = PBXGroup; + children = ( + E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */, + A425648B5C0A4849C7668069 /* Pods.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; EA66998D1811D2FA00A70D03 = { isa = PBXGroup; children = ( @@ -132,7 +147,7 @@ EA6699C11811D2FB00A70D03 /* PetstoreClientTests */, EA6699981811D2FA00A70D03 /* Frameworks */, EA6699971811D2FA00A70D03 /* Products */, - EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */, + 1A15B3DE4358A178ABAEC251 /* Pods */, ); sourceTree = ""; }; @@ -176,6 +191,7 @@ EA6699A01811D2FA00A70D03 /* Supporting Files */ = { isa = PBXGroup; children = ( + EAFBEABA1A925B8500A27431 /* test-1.png */, EA6699A11811D2FA00A70D03 /* PetstoreClient-Info.plist */, EA6699A21811D2FA00A70D03 /* InfoPlist.strings */, EA6699A51811D2FA00A70D03 /* main.m */, @@ -205,6 +221,8 @@ EAEA85CB1811D3AE00F06E69 /* client */ = { isa = PBXGroup; children = ( + EAFBEABC1A92C42700A27431 /* SWGApiResponse.h */, + EAFBEABD1A92C42700A27431 /* SWGApiResponse.m */, EAEA85CC1811D3AE00F06E69 /* SWGApiClient.h */, EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */, EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */, @@ -315,6 +333,7 @@ EA6699B01811D2FA00A70D03 /* Main_iPad.storyboard in Resources */, EA6699B51811D2FA00A70D03 /* Images.xcassets in Resources */, EA6699AD1811D2FA00A70D03 /* Main_iPhone.storyboard in Resources */, + EAFBEABB1A925B8500A27431 /* test-1.png in Resources */, EA6699A41811D2FA00A70D03 /* InfoPlist.strings in Resources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -357,7 +376,7 @@ ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "\"${SRCROOT}/../Pods/Pods-resources.sh\"\n"; + shellScript = "\"${SRCROOT}/../Pods/Target Support Files/Pods/Pods-resources.sh\"\n"; showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ @@ -372,6 +391,7 @@ EA6699B31811D2FA00A70D03 /* ViewController.m in Sources */, EA6699AA1811D2FA00A70D03 /* AppDelegate.m in Sources */, EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */, + EAFBEABE1A92C42700A27431 /* SWGApiResponse.m in Sources */, EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */, EAEA85EB1811D3AE00F06E69 /* SWGPetApi.m in Sources */, EAEA85E61811D3AE00F06E69 /* SWGDate.m in Sources */, @@ -515,7 +535,7 @@ }; EA6699CC1811D2FB00A70D03 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */; + baseConfigurationReference = E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; @@ -529,7 +549,7 @@ }; EA6699CD1811D2FB00A70D03 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */; + baseConfigurationReference = A425648B5C0A4849C7668069 /* Pods.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/AppIcon.appiconset/Contents.json b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/AppIcon.appiconset/Contents.json index 91bf9c14a730..b7f3352ee7c8 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/AppIcon.appiconset/Contents.json +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/AppIcon.appiconset/Contents.json @@ -15,6 +15,11 @@ "size" : "60x60", "scale" : "2x" }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, { "idiom" : "ipad", "size" : "29x29", diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m index d8e593c5079b..ebdb5a42e99d 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m @@ -22,9 +22,36 @@ SWGPetApi * api = [[SWGPetApi alloc] init]; - [api getPetByIdWithCompletionBlock:@10 completionHandler:^(SWGPet *output, NSError *error) { - NSLog(@"%@", [output asDictionary]); - }]; +// [api getPetByIdWithCompletionBlock:@10 completionHandler:^(SWGPet *output, NSError *error) { +// NSLog(@"%@", [output asDictionary]); +// [output set_id:@101]; +// [api addPetWithCompletionBlock:output completionHandler:^(NSError *error) { +// NSLog(@"Done!"); +// }]; + + // load data into file +// }]; + NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test-1" ofType:@"png"]; + NSData *myData = [NSData dataWithContentsOfFile:filePath]; + + SWGFile *file = [[SWGFile alloc] initWithNameData:@"test-2.png" mimeType:@"image/png" data:myData]; + [api uploadFileWithCompletionBlock:@1 + additionalMetadata:@"some metadata" + file:file + completionHandler:^(NSError *error) { + if(error) { + NSLog(@"%@", error); + } + } +// completionHandler:^(SWGApiResponse *output, NSError *error) { +// if(error) { +// NSLog(@"%@", error); +// } +// else { +// NSLog(@"%@", [output asDictionary]); +// } +// } + ]; } - (void)didReceiveMemoryWarning diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/test-1.png b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/test-1.png new file mode 100644 index 000000000000..1da243e1d23a Binary files /dev/null and b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/test-1.png differ diff --git a/samples/client/petstore/objc/Podfile b/samples/client/petstore/objc/Podfile index 36e97d70a75d..e6b8aab6518e 100644 --- a/samples/client/petstore/objc/Podfile +++ b/samples/client/petstore/objc/Podfile @@ -1,4 +1,3 @@ platform :ios, '6.0' -xcodeproj 'PetstoreClient/PetstoreClient.xcodeproj' -pod 'AFNetworking', '~> 1.0' - +xcodeproj 'swaggerClient/swaggerClient.xcodeproj' +pod 'AFNetworking', '~> 2.1' diff --git a/samples/client/petstore/objc/Podfile.lock b/samples/client/petstore/objc/Podfile.lock index f52a69324dba..a3466a082961 100644 --- a/samples/client/petstore/objc/Podfile.lock +++ b/samples/client/petstore/objc/Podfile.lock @@ -1,10 +1,30 @@ PODS: - - AFNetworking (1.3.3) + - AFNetworking (2.5.1): + - AFNetworking/NSURLConnection (= 2.5.1) + - AFNetworking/NSURLSession (= 2.5.1) + - AFNetworking/Reachability (= 2.5.1) + - AFNetworking/Security (= 2.5.1) + - AFNetworking/Serialization (= 2.5.1) + - AFNetworking/UIKit (= 2.5.1) + - AFNetworking/NSURLConnection (2.5.1): + - AFNetworking/Reachability + - AFNetworking/Security + - AFNetworking/Serialization + - AFNetworking/NSURLSession (2.5.1): + - AFNetworking/Reachability + - AFNetworking/Security + - AFNetworking/Serialization + - AFNetworking/Reachability (2.5.1) + - AFNetworking/Security (2.5.1) + - AFNetworking/Serialization (2.5.1) + - AFNetworking/UIKit (2.5.1): + - AFNetworking/NSURLConnection + - AFNetworking/NSURLSession DEPENDENCIES: - - AFNetworking (~> 1.0) + - AFNetworking (~> 2.1) SPEC CHECKSUMS: - AFNetworking: 0700ec7a58c36ad217173e167f6e4df7270df66b + AFNetworking: 8bee59492a6ff15d69130efa4d0dc67e0094a52a -COCOAPODS: 0.25.0 +COCOAPODS: 0.35.0 diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.h deleted file mode 100644 index 3826b6f2f5cb..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.h +++ /dev/null @@ -1,641 +0,0 @@ -// AFHTTPClient.h -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import "AFURLConnectionOperation.h" - -#import - -/** - `AFHTTPClient` captures the common patterns of communicating with an web application over HTTP. It encapsulates information like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations. - - ## Automatic Content Parsing - - Instances of `AFHTTPClient` may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in `enqueueHTTPRequestOperationWithRequest:success:failure`. - - ## Subclassing Notes - - In most cases, one should create an `AFHTTPClient` subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application. - - ## Methods to Override - - To change the behavior of all url request construction for an `AFHTTPClient` subclass, override `requestWithMethod:path:parameters`. - - To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `HTTPRequestOperationWithRequest:success:failure`. - - ## Default Headers - - By default, `AFHTTPClient` sets the following HTTP headers: - - - `Accept-Language: (comma-delimited preferred languages), en-us;q=0.8` - - `User-Agent: (generated user agent)` - - You can override these HTTP headers or define new ones using `setDefaultHeader:value:`. - - ## URL Construction Using Relative Paths - - Both `-requestWithMethod:path:parameters:` and `-multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:` construct URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`. Below are a few examples of how `baseURL` and relative paths interact: - - NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; - [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo - [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz - [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo - [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo - [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ - [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ - - Also important to note is that a trailing slash will be added to any `baseURL` without one, which would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. - - ## NSCoding / NSCopying Conformance - - `AFHTTPClient` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however: - - - Archives and copies of HTTP clients will be initialized with an empty operation queue. - - NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set. - */ - -#ifdef _SYSTEMCONFIGURATION_H -typedef enum { - AFNetworkReachabilityStatusUnknown = -1, - AFNetworkReachabilityStatusNotReachable = 0, - AFNetworkReachabilityStatusReachableViaWWAN = 1, - AFNetworkReachabilityStatusReachableViaWiFi = 2, -} AFNetworkReachabilityStatus; -#else -#pragma message("SystemConfiguration framework not found in project, or not included in precompiled header. Network reachability functionality will not be available.") -#endif - -#ifndef __UTTYPE__ -#if __IPHONE_OS_VERSION_MIN_REQUIRED -#pragma message("MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.") -#else -#pragma message("CoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.") -#endif -#endif - -typedef enum { - AFFormURLParameterEncoding, - AFJSONParameterEncoding, - AFPropertyListParameterEncoding, -} AFHTTPClientParameterEncoding; - -@class AFHTTPRequestOperation; -@protocol AFMultipartFormData; - -@interface AFHTTPClient : NSObject - -///--------------------------------------- -/// @name Accessing HTTP Client Properties -///--------------------------------------- - -/** - The url used as the base for paths specified in methods such as `getPath:parameters:success:failure` - */ -@property (readonly, nonatomic, strong) NSURL *baseURL; - -/** - The string encoding used in constructing url requests. This is `NSUTF8StringEncoding` by default. - */ -@property (nonatomic, assign) NSStringEncoding stringEncoding; - -/** - The `AFHTTPClientParameterEncoding` value corresponding to how parameters are encoded into a request body for request methods other than `GET`, `HEAD` or `DELETE`. This is `AFFormURLParameterEncoding` by default. - - @warning Some nested parameter structures, such as a keyed array of hashes containing inconsistent keys (i.e. `@{@"": @[@{@"a" : @(1)}, @{@"b" : @(2)}]}`), cannot be unambiguously represented in query strings. It is strongly recommended that an unambiguous encoding, such as `AFJSONParameterEncoding`, is used when posting complicated or nondeterministic parameter structures. - */ -@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding; - -/** - The operation queue which manages operations enqueued by the HTTP client. - */ -@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue; - -/** - The reachability status from the device to the current `baseURL` of the `AFHTTPClient`. - - @warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). - */ -#ifdef _SYSTEMCONFIGURATION_H -@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; -#endif - -/** - Default SSL pinning mode for each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:`. - */ -@property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode defaultSSLPinningMode; - -/** - Whether each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:` should accept an invalid SSL certificate. - - If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is set, this property defaults to `YES` for backwards compatibility. Otherwise, this property defaults to `NO`. - */ -@property (nonatomic, assign) BOOL allowsInvalidSSLCertificate; - -///--------------------------------------------- -/// @name Creating and Initializing HTTP Clients -///--------------------------------------------- - -/** - Creates and initializes an `AFHTTPClient` object with the specified base URL. - - @param url The base URL for the HTTP client. This argument must not be `nil`. - - @return The newly-initialized HTTP client - */ -+ (instancetype)clientWithBaseURL:(NSURL *)url; - -/** - Initializes an `AFHTTPClient` object with the specified base URL. - - This is the designated initializer. - - @param url The base URL for the HTTP client. This argument must not be `nil`. - - @return The newly-initialized HTTP client - */ -- (id)initWithBaseURL:(NSURL *)url; - -///----------------------------------- -/// @name Managing Reachability Status -///----------------------------------- - -/** - Sets a callback to be executed when the network availability of the `baseURL` host changes. - - @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. - - @warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). - */ -#ifdef _SYSTEMCONFIGURATION_H -- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block; -#endif - -///------------------------------- -/// @name Managing HTTP Operations -///------------------------------- - -/** - Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request. - - When `enqueueHTTPRequestOperationWithRequest:success:failure` is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to create an operation using `initWithURLRequest:` and do `setCompletionBlockWithSuccess:failure:`. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the list. - - @param operationClass The subclass of `AFHTTPRequestOperation` to register - - @return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` is not a subclass of `AFHTTPRequestOperation`. - */ -- (BOOL)registerHTTPOperationClass:(Class)operationClass; - -/** - Unregisters the specified subclass of `AFHTTPRequestOperation` from the chain of classes consulted when `-requestWithMethod:path:parameters` is called. - - @param operationClass The subclass of `AFHTTPRequestOperation` to register - */ -- (void)unregisterHTTPOperationClass:(Class)operationClass; - -///---------------------------------- -/// @name Managing HTTP Header Values -///---------------------------------- - -/** - Returns the value for the HTTP headers set in request objects created by the HTTP client. - - @param header The HTTP header to return the default value for - - @return The default value for the HTTP header, or `nil` if unspecified - */ -- (NSString *)defaultValueForHeader:(NSString *)header; - -/** - Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header. - - @param header The HTTP header to set a default value for - @param value The value set as default for the specified header, or `nil - */ -- (void)setDefaultHeader:(NSString *)header - value:(NSString *)value; - -/** - Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header. - - @param username The HTTP basic auth username - @param password The HTTP basic auth password - */ -- (void)setAuthorizationHeaderWithUsername:(NSString *)username - password:(NSString *)password; - -/** - Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a token-based authentication value, such as an OAuth access token. This overwrites any existing value for this header. - - @param token The authentication token - */ -- (void)setAuthorizationHeaderWithToken:(NSString *)token; - - -/** - Clears any existing value for the "Authorization" HTTP header. - */ -- (void)clearAuthorizationHeader; - -///------------------------------- -/// @name Managing URL Credentials -///------------------------------- - -/** - Set the default URL credential to be set for request operations. - - @param credential The URL credential - */ -- (void)setDefaultCredential:(NSURLCredential *)credential; - -///------------------------------- -/// @name Creating Request Objects -///------------------------------- - -/** - Creates an `NSMutableURLRequest` object with the specified HTTP method and path. - - If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body. - - @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`. - @param path The path to be appended to the HTTP client's base URL and used as the request URL. If `nil`, no path will be appended to the base URL. - @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. - - @return An `NSMutableURLRequest` object - */ -- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - path:(NSString *)path - parameters:(NSDictionary *)parameters; - -/** - Creates an `NSMutableURLRequest` object with the specified HTTP method and path, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2 - - Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream. - - @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`. - @param path The path to be appended to the HTTP client's base URL and used as the request URL. - @param parameters The parameters to be encoded and set in the request HTTP body. - @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. This can be used to upload files, encode HTTP body as JSON or XML, or specify multiple values for the same parameter, as one might for array values. - - @return An `NSMutableURLRequest` object - */ -- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method - path:(NSString *)path - parameters:(NSDictionary *)parameters - constructingBodyWithBlock:(void (^)(id formData))block; - -///------------------------------- -/// @name Creating HTTP Operations -///------------------------------- - -/** - Creates an `AFHTTPRequestOperation`. - - In order to determine what kind of operation is created, each registered subclass conforming to the `AFHTTPClient` protocol is consulted (in reverse order of when they were specified) to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to generate an operation using `HTTPRequestOperationWithRequest:success:failure:`. - - @param urlRequest The request object to be loaded asynchronously during execution of the operation. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred. - */ -- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -///---------------------------------------- -/// @name Managing Enqueued HTTP Operations -///---------------------------------------- - -/** - Enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue. - - @param operation The HTTP request operation to be enqueued. - */ -- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation; - -/** - Cancels all operations in the HTTP client's operation queue whose URLs match the specified HTTP method and path. - - This method only cancels `AFHTTPRequestOperations` whose request URL matches the HTTP client base URL with the path appended. For complete control over the lifecycle of enqueued operations, you can access the `operationQueue` property directly, which allows you to, for instance, cancel operations filtered by a predicate, or simply use `-cancelAllRequests`. Note that the operation queue may include non-HTTP operations, so be sure to check the type before attempting to directly introspect an operation's `request` property. - - @param method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`. If `nil`, all request operations with URLs matching the path will be cancelled. - @param path The path appended to the HTTP client base URL to match against the cancelled requests. If `nil`, no path will be appended to the base URL. - */ -- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path; - -///--------------------------------------- -/// @name Batching HTTP Request Operations -///--------------------------------------- - -/** - Creates and enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue for each specified request object into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes. - - Operations are created by passing the specified `NSURLRequest` objects in `requests`, using `-HTTPRequestOperationWithRequest:success:failure:`, with `nil` for both the `success` and `failure` parameters. - - @param urlRequests The `NSURLRequest` objects used to create and enqueue operations. - @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations. - @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations. - */ -- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests - progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock - completionBlock:(void (^)(NSArray *operations))completionBlock; - -/** - Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes. - - @param operations The request operations used to be batched and enqueued. - @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations. - @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations. - */ -- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations - progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock - completionBlock:(void (^)(NSArray *operations))completionBlock; - -///--------------------------- -/// @name Making HTTP Requests -///--------------------------- - -/** - Creates an `AFHTTPRequestOperation` with a `GET` request, and enqueues it to the HTTP client's operation queue. - - @param path The path to be appended to the HTTP client's base URL and used as the request URL. - @param parameters The parameters to be encoded and appended as the query string for the request URL. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (void)getPath:(NSString *)path - parameters:(NSDictionary *)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates an `AFHTTPRequestOperation` with a `POST` request, and enqueues it to the HTTP client's operation queue. - - @param path The path to be appended to the HTTP client's base URL and used as the request URL. - @param parameters The parameters to be encoded and set in the request HTTP body. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (void)postPath:(NSString *)path - parameters:(NSDictionary *)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates an `AFHTTPRequestOperation` with a `PUT` request, and enqueues it to the HTTP client's operation queue. - - @param path The path to be appended to the HTTP client's base URL and used as the request URL. - @param parameters The parameters to be encoded and set in the request HTTP body. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (void)putPath:(NSString *)path - parameters:(NSDictionary *)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates an `AFHTTPRequestOperation` with a `DELETE` request, and enqueues it to the HTTP client's operation queue. - - @param path The path to be appended to the HTTP client's base URL and used as the request URL. - @param parameters The parameters to be encoded and appended as the query string for the request URL. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (void)deletePath:(NSString *)path - parameters:(NSDictionary *)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -/** - Creates an `AFHTTPRequestOperation` with a `PATCH` request, and enqueues it to the HTTP client's operation queue. - - @param path The path to be appended to the HTTP client's base URL and used as the request URL. - @param parameters The parameters to be encoded and set in the request HTTP body. - @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. - @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred. - - @see -HTTPRequestOperationWithRequest:success:failure: - */ -- (void)patchPath:(NSString *)path - parameters:(NSDictionary *)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; -@end - -///---------------- -/// @name Constants -///---------------- - -/** - ## Network Reachability - - The following constants are provided by `AFHTTPClient` as possible network reachability statuses. - - enum { - AFNetworkReachabilityStatusUnknown, - AFNetworkReachabilityStatusNotReachable, - AFNetworkReachabilityStatusReachableViaWWAN, - AFNetworkReachabilityStatusReachableViaWiFi, - } - - `AFNetworkReachabilityStatusUnknown` - The `baseURL` host reachability is not known. - - `AFNetworkReachabilityStatusNotReachable` - The `baseURL` host cannot be reached. - - `AFNetworkReachabilityStatusReachableViaWWAN` - The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. - - `AFNetworkReachabilityStatusReachableViaWiFi` - The `baseURL` host can be reached via a Wi-Fi connection. - - ### Keys for Notification UserInfo Dictionary - - Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. - - `AFNetworkingReachabilityNotificationStatusItem` - A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. - The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. - - ## Parameter Encoding - - The following constants are provided by `AFHTTPClient` as possible methods for serializing parameters into query string or message body values. - - enum { - AFFormURLParameterEncoding, - AFJSONParameterEncoding, - AFPropertyListParameterEncoding, - } - - `AFFormURLParameterEncoding` - Parameters are encoded into field/key pairs in the URL query string for `GET` `HEAD` and `DELETE` requests, and in the message body otherwise. Dictionary keys are sorted with the `caseInsensitiveCompare:` selector of their description, in order to mitigate the possibility of ambiguous query strings being generated non-deterministically. See the warning for the `parameterEncoding` property for additional information. - - `AFJSONParameterEncoding` - Parameters are encoded into JSON in the message body. - - `AFPropertyListParameterEncoding` - Parameters are encoded into a property list in the message body. - */ - -///---------------- -/// @name Functions -///---------------- - -/** - Returns a query string constructed by a set of parameters, using the specified encoding. - - Query strings are constructed by collecting each key-value pair, percent escaping a string representation of the key-value pair, and then joining the pairs with "&". - - If a query string pair has a an `NSArray` for its value, each member of the array will be represented in the format `field[]=value1&field[]value2`. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the `-description` method. The constructed query string does not include the ? character used to delimit the query component. - - @param parameters The parameters used to construct the query string - @param encoding The encoding to use in constructing the query string. If you are uncertain of the correct encoding, you should use UTF-8 (`NSUTF8StringEncoding`), which is the encoding designated by RFC 3986 as the correct encoding for use in URLs. - - @return A percent-escaped query string - */ -extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding); - -///-------------------- -/// @name Notifications -///-------------------- - -/** - Posted when network reachability changes. - This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability. - - @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). - */ -#ifdef _SYSTEMCONFIGURATION_H -extern NSString * const AFNetworkingReachabilityDidChangeNotification; -extern NSString * const AFNetworkingReachabilityNotificationStatusItem; -#endif - -#pragma mark - - -extern NSUInteger const kAFUploadStream3GSuggestedPacketSize; -extern NSTimeInterval const kAFUploadStream3GSuggestedDelay; - -/** - The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPClient -multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`. - */ -@protocol AFMultipartFormData - -/** - Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary. - - The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively. - - @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - @param error If an error occurs, upon return contains an `NSError` object that describes the problem. - - @return `YES` if the file data was successfully appended, otherwise `NO`. - */ -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - error:(NSError * __autoreleasing *)error; - -/** - Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. - - @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`. - @param mimeType The declared MIME type of the file data. This parameter must not be `nil`. - @param error If an error occurs, upon return contains an `NSError` object that describes the problem. - - @return `YES` if the file data was successfully appended otherwise `NO`. - */ -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType - error:(NSError * __autoreleasing *)error; - -/** - Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary. - - @param inputStream The input stream to be appended to the form data - @param name The name to be associated with the specified input stream. This parameter must not be `nil`. - @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`. - @param length The length of the specified input stream in bytes. - @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. - */ -- (void)appendPartWithInputStream:(NSInputStream *)inputStream - name:(NSString *)name - fileName:(NSString *)fileName - length:(unsigned long long)length - mimeType:(NSString *)mimeType; - -/** - Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. - - @param data The data to be encoded and appended to the form data. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - @param fileName The filename to be associated with the specified data. This parameter must not be `nil`. - @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. - */ -- (void)appendPartWithFileData:(NSData *)data - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType; - -/** - Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary. - - @param data The data to be encoded and appended to the form data. - @param name The name to be associated with the specified data. This parameter must not be `nil`. - */ - -- (void)appendPartWithFormData:(NSData *)data - name:(NSString *)name; - - -/** - Appends HTTP headers, followed by the encoded data and the multipart form boundary. - - @param headers The HTTP headers to be appended to the form data. - @param body The data to be encoded and appended to the form data. - */ -- (void)appendPartWithHeaders:(NSDictionary *)headers - body:(NSData *)body; - -/** - Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream. - - When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, as of iOS 6, there is no definite way to distinguish between a 3G, EDGE, or LTE connection. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth. - - @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 32kb. - @param delay Duration of delay each time a packet is read. By default, no delay is set. - */ -- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes - delay:(NSTimeInterval)delay; - -@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.m deleted file mode 100644 index 43b74a154de6..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.m +++ /dev/null @@ -1,1396 +0,0 @@ -// AFHTTPClient.m -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import "AFHTTPClient.h" -#import "AFHTTPRequestOperation.h" - -#import - -#ifdef _SYSTEMCONFIGURATION_H -#import -#import -#import -#import -#import -#endif - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import -#endif - -#ifdef _SYSTEMCONFIGURATION_H -NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; -NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; - -typedef SCNetworkReachabilityRef AFNetworkReachabilityRef; -typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); -#else -typedef id AFNetworkReachabilityRef; -#endif - -typedef void (^AFCompletionBlock)(void); - -static NSString * AFBase64EncodedStringFromString(NSString *string) { - NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]; - NSUInteger length = [data length]; - NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; - - uint8_t *input = (uint8_t *)[data bytes]; - uint8_t *output = (uint8_t *)[mutableData mutableBytes]; - - for (NSUInteger i = 0; i < length; i += 3) { - NSUInteger value = 0; - for (NSUInteger j = i; j < (i + 3); j++) { - value <<= 8; - if (j < length) { - value |= (0xFF & input[j]); - } - } - - static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - - NSUInteger idx = (i / 3) * 4; - output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F]; - output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F]; - output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '='; - output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '='; - } - - return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding]; -} - -static NSString * const kAFCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*"; - -static NSString * AFPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { - static NSString * const kAFCharactersToLeaveUnescapedInQueryStringPairKey = @"[]."; - - return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); -} - -static NSString * AFPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { - return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); -} - -#pragma mark - - -@interface AFQueryStringPair : NSObject -@property (readwrite, nonatomic, strong) id field; -@property (readwrite, nonatomic, strong) id value; - -- (id)initWithField:(id)field value:(id)value; - -- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding; -@end - -@implementation AFQueryStringPair -@synthesize field = _field; -@synthesize value = _value; - -- (id)initWithField:(id)field value:(id)value { - self = [super init]; - if (!self) { - return nil; - } - - self.field = field; - self.value = value; - - return self; -} - -- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding { - if (!self.value || [self.value isEqual:[NSNull null]]) { - return AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding); - } else { - return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding), AFPercentEscapedQueryStringValueFromStringWithEncoding([self.value description], stringEncoding)]; - } -} - -@end - -#pragma mark - - -extern NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); -extern NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); - -NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) { - NSMutableArray *mutablePairs = [NSMutableArray array]; - for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { - [mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]]; - } - - return [mutablePairs componentsJoinedByString:@"&"]; -} - -NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) { - return AFQueryStringPairsFromKeyAndValue(nil, dictionary); -} - -NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) { - NSMutableArray *mutableQueryStringComponents = [NSMutableArray array]; - - if ([value isKindOfClass:[NSDictionary class]]) { - NSDictionary *dictionary = value; - // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries - NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(caseInsensitiveCompare:)]; - for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { - id nestedValue = [dictionary objectForKey:nestedKey]; - if (nestedValue) { - [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; - } - } - } else if ([value isKindOfClass:[NSArray class]]) { - NSArray *array = value; - for (id nestedValue in array) { - [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)]; - } - } else if ([value isKindOfClass:[NSSet class]]) { - NSSet *set = value; - for (id obj in set) { - [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)]; - } - } else { - [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; - } - - return mutableQueryStringComponents; -} - -@interface AFStreamingMultipartFormData : NSObject -- (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest - stringEncoding:(NSStringEncoding)encoding; - -- (NSMutableURLRequest *)requestByFinalizingMultipartFormData; -@end - -#pragma mark - - -@interface AFHTTPClient () -@property (readwrite, nonatomic, strong) NSURL *baseURL; -@property (readwrite, nonatomic, strong) NSMutableArray *registeredHTTPOperationClassNames; -@property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders; -@property (readwrite, nonatomic, strong) NSURLCredential *defaultCredential; -@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue; -#ifdef _SYSTEMCONFIGURATION_H -@property (readwrite, nonatomic, assign) AFNetworkReachabilityRef networkReachability; -@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; -@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; -#endif - -#ifdef _SYSTEMCONFIGURATION_H -- (void)startMonitoringNetworkReachability; -- (void)stopMonitoringNetworkReachability; -#endif -@end - -@implementation AFHTTPClient -@synthesize baseURL = _baseURL; -@synthesize stringEncoding = _stringEncoding; -@synthesize parameterEncoding = _parameterEncoding; -@synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames; -@synthesize defaultHeaders = _defaultHeaders; -@synthesize defaultCredential = _defaultCredential; -@synthesize operationQueue = _operationQueue; -#ifdef _SYSTEMCONFIGURATION_H -@synthesize networkReachability = _networkReachability; -@synthesize networkReachabilityStatus = _networkReachabilityStatus; -@synthesize networkReachabilityStatusBlock = _networkReachabilityStatusBlock; -#endif -@synthesize defaultSSLPinningMode = _defaultSSLPinningMode; -@synthesize allowsInvalidSSLCertificate = _allowsInvalidSSLCertificate; - -+ (instancetype)clientWithBaseURL:(NSURL *)url { - return [[self alloc] initWithBaseURL:url]; -} - -- (id)init { - @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"%@ Failed to call designated initializer. Invoke `initWithBaseURL:` instead.", NSStringFromClass([self class])] userInfo:nil]; -} - -- (id)initWithBaseURL:(NSURL *)url { - NSParameterAssert(url); - - self = [super init]; - if (!self) { - return nil; - } - - // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected - if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { - url = [url URLByAppendingPathComponent:@""]; - } - - self.baseURL = url; - - self.stringEncoding = NSUTF8StringEncoding; - self.parameterEncoding = AFFormURLParameterEncoding; - - self.registeredHTTPOperationClassNames = [NSMutableArray array]; - - self.defaultHeaders = [NSMutableDictionary dictionary]; - - // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 - NSMutableArray *acceptLanguagesComponents = [NSMutableArray array]; - [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - float q = 1.0f - (idx * 0.1f); - [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]]; - *stop = q <= 0.5f; - }]; - [self setDefaultHeader:@"Accept-Language" value:[acceptLanguagesComponents componentsJoinedByString:@", "]]; - - NSString *userAgent = nil; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 - userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0f)]; -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) - userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; -#endif -#pragma clang diagnostic pop - if (userAgent) { - if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) { - NSMutableString *mutableUserAgent = [userAgent mutableCopy]; - CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, kCFStringTransformToLatin, false); - userAgent = mutableUserAgent; - } - [self setDefaultHeader:@"User-Agent" value:userAgent]; - } - -#ifdef _SYSTEMCONFIGURATION_H - self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; - [self startMonitoringNetworkReachability]; -#endif - - self.operationQueue = [[NSOperationQueue alloc] init]; - [self.operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount]; - - // #ifdef included for backwards-compatibility -#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ - self.allowsInvalidSSLCertificate = YES; -#endif - - return self; -} - -- (void)dealloc { -#ifdef _SYSTEMCONFIGURATION_H - [self stopMonitoringNetworkReachability]; -#endif -} - -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, defaultHeaders: %@, registeredOperationClasses: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.defaultHeaders, self.registeredHTTPOperationClassNames, self.operationQueue]; -} - -#pragma mark - - -#ifdef _SYSTEMCONFIGURATION_H -static BOOL AFURLHostIsIPAddress(NSURL *url) { - struct sockaddr_in sa_in; - struct sockaddr_in6 sa_in6; - - return [url host] && (inet_pton(AF_INET, [[url host] UTF8String], &sa_in) == 1 || inet_pton(AF_INET6, [[url host] UTF8String], &sa_in6) == 1); -} - -static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { - BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); - BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); - BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); - BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); - BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); - - AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; - if (isNetworkReachable == NO) { - status = AFNetworkReachabilityStatusNotReachable; - } -#if TARGET_OS_IPHONE - else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { - status = AFNetworkReachabilityStatusReachableViaWWAN; - } -#endif - else { - status = AFNetworkReachabilityStatusReachableViaWiFi; - } - - return status; -} - -static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { - AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); - AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info; - if (block) { - block(status); - } - - dispatch_async(dispatch_get_main_queue(), ^{ - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:status] forKey:AFNetworkingReachabilityNotificationStatusItem]]; - }); -} - -static const void * AFNetworkReachabilityRetainCallback(const void *info) { - return Block_copy(info); -} - -static void AFNetworkReachabilityReleaseCallback(const void *info) { - if (info) { - Block_release(info); - } -} - -- (void)startMonitoringNetworkReachability { - [self stopMonitoringNetworkReachability]; - - if (!self.baseURL) { - return; - } - - self.networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [[self.baseURL host] UTF8String]); - - if (!self.networkReachability) { - return; - } - - __weak __typeof(&*self)weakSelf = self; - AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { - __strong __typeof(&*weakSelf)strongSelf = weakSelf; - if (!strongSelf) { - return; - } - - strongSelf.networkReachabilityStatus = status; - if (strongSelf.networkReachabilityStatusBlock) { - strongSelf.networkReachabilityStatusBlock(status); - } - }; - - SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; - SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); - - /* Network reachability monitoring does not establish a baseline for IP addresses as it does for hostnames, so if the base URL host is an IP address, the initial reachability callback is manually triggered. - */ - if (AFURLHostIsIPAddress(self.baseURL)) { - SCNetworkReachabilityFlags flags; - SCNetworkReachabilityGetFlags(self.networkReachability, &flags); - dispatch_async(dispatch_get_main_queue(), ^{ - AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); - callback(status); - }); - } - - SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); -} - -- (void)stopMonitoringNetworkReachability { - if (self.networkReachability) { - SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); - - CFRelease(_networkReachability); - _networkReachability = NULL; - } -} - -- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { - self.networkReachabilityStatusBlock = block; -} -#endif - -#pragma mark - - -- (BOOL)registerHTTPOperationClass:(Class)operationClass { - if (![operationClass isSubclassOfClass:[AFHTTPRequestOperation class]]) { - return NO; - } - - NSString *className = NSStringFromClass(operationClass); - [self.registeredHTTPOperationClassNames removeObject:className]; - [self.registeredHTTPOperationClassNames insertObject:className atIndex:0]; - - return YES; -} - -- (void)unregisterHTTPOperationClass:(Class)operationClass { - NSString *className = NSStringFromClass(operationClass); - [self.registeredHTTPOperationClassNames removeObject:className]; -} - -#pragma mark - - -- (NSString *)defaultValueForHeader:(NSString *)header { - return [self.defaultHeaders valueForKey:header]; -} - -- (void)setDefaultHeader:(NSString *)header value:(NSString *)value { - [self.defaultHeaders setValue:value forKey:header]; -} - -- (void)setAuthorizationHeaderWithUsername:(NSString *)username password:(NSString *)password { - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; - [self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)]]; -} - -- (void)setAuthorizationHeaderWithToken:(NSString *)token { - [self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Token token=\"%@\"", token]]; -} - -- (void)clearAuthorizationHeader { - [self.defaultHeaders removeObjectForKey:@"Authorization"]; -} - -#pragma mark - - -- (NSMutableURLRequest *)requestWithMethod:(NSString *)method - path:(NSString *)path - parameters:(NSDictionary *)parameters -{ - NSParameterAssert(method); - - if (!path) { - path = @""; - } - - NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL]; - NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; - [request setHTTPMethod:method]; - [request setAllHTTPHeaderFields:self.defaultHeaders]; - - if (parameters) { - if ([method isEqualToString:@"GET"] || [method isEqualToString:@"HEAD"] || [method isEqualToString:@"DELETE"]) { - url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding)]]; - [request setURL:url]; - } else { - NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding)); - NSError *error = nil; - - switch (self.parameterEncoding) { - case AFFormURLParameterEncoding:; - [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; - [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding) dataUsingEncoding:self.stringEncoding]]; - break; - case AFJSONParameterEncoding:; - [request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; - [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:(NSJSONWritingOptions)0 error:&error]]; - break; - case AFPropertyListParameterEncoding:; - [request setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; - [request setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:NSPropertyListXMLFormat_v1_0 options:0 error:&error]]; - break; - } - - if (error) { - NSLog(@"%@ %@: %@", [self class], NSStringFromSelector(_cmd), error); - } - } - } - - return request; -} - -- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method - path:(NSString *)path - parameters:(NSDictionary *)parameters - constructingBodyWithBlock:(void (^)(id formData))block -{ - NSParameterAssert(method); - NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]); - - NSMutableURLRequest *request = [self requestWithMethod:method path:path parameters:nil]; - - __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:request stringEncoding:self.stringEncoding]; - - if (parameters) { - for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { - NSData *data = nil; - if ([pair.value isKindOfClass:[NSData class]]) { - data = pair.value; - } else if ([pair.value isEqual:[NSNull null]]) { - data = [NSData data]; - } else { - data = [[pair.value description] dataUsingEncoding:self.stringEncoding]; - } - - if (data) { - [formData appendPartWithFormData:data name:[pair.field description]]; - } - } - } - - if (block) { - block(formData); - } - - return [formData requestByFinalizingMultipartFormData]; -} - -- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - AFHTTPRequestOperation *operation = nil; - - for (NSString *className in self.registeredHTTPOperationClassNames) { - Class operationClass = NSClassFromString(className); - if (operationClass && [operationClass canProcessRequest:urlRequest]) { - operation = [(AFHTTPRequestOperation *)[operationClass alloc] initWithRequest:urlRequest]; - break; - } - } - - if (!operation) { - operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; - } - - [operation setCompletionBlockWithSuccess:success failure:failure]; - - operation.credential = self.defaultCredential; - operation.SSLPinningMode = self.defaultSSLPinningMode; - operation.allowsInvalidSSLCertificate = self.allowsInvalidSSLCertificate; - - return operation; -} - -#pragma mark - - -- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation { - [self.operationQueue addOperation:operation]; -} - -- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method - path:(NSString *)path -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - NSString *pathToBeMatched = [[[self requestWithMethod:(method ?: @"GET") path:path parameters:nil] URL] path]; -#pragma clang diagnostic pop - - for (NSOperation *operation in [self.operationQueue operations]) { - if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) { - continue; - } - - BOOL hasMatchingMethod = !method || [method isEqualToString:[[(AFHTTPRequestOperation *)operation request] HTTPMethod]]; - BOOL hasMatchingPath = [[[[(AFHTTPRequestOperation *)operation request] URL] path] isEqual:pathToBeMatched]; - - if (hasMatchingMethod && hasMatchingPath) { - [operation cancel]; - } - } -} - -- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests - progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock - completionBlock:(void (^)(NSArray *operations))completionBlock -{ - NSMutableArray *mutableOperations = [NSMutableArray array]; - for (NSURLRequest *request in urlRequests) { - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:nil failure:nil]; - [mutableOperations addObject:operation]; - } - - [self enqueueBatchOfHTTPRequestOperations:mutableOperations progressBlock:progressBlock completionBlock:completionBlock]; -} - -- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations - progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock - completionBlock:(void (^)(NSArray *operations))completionBlock -{ - __block dispatch_group_t dispatchGroup = dispatch_group_create(); - NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{ - dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{ - if (completionBlock) { - completionBlock(operations); - } - }); -#if !OS_OBJECT_USE_OBJC - dispatch_release(dispatchGroup); -#endif - }]; - - for (AFHTTPRequestOperation *operation in operations) { - AFCompletionBlock originalCompletionBlock = [operation.completionBlock copy]; - __weak __typeof(&*operation)weakOperation = operation; - operation.completionBlock = ^{ - __strong __typeof(&*weakOperation)strongOperation = weakOperation; -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_queue_t queue = strongOperation.successCallbackQueue ?: dispatch_get_main_queue(); -#pragma clang diagnostic pop - dispatch_group_async(dispatchGroup, queue, ^{ - if (originalCompletionBlock) { - originalCompletionBlock(); - } - - NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx, BOOL __unused *stop) { - return [op isFinished]; - }] count]; - - if (progressBlock) { - progressBlock(numberOfFinishedOperations, [operations count]); - } - - dispatch_group_leave(dispatchGroup); - }); - }; - - dispatch_group_enter(dispatchGroup); - [batchedOperation addDependency:operation]; - } - [self.operationQueue addOperations:operations waitUntilFinished:NO]; - [self.operationQueue addOperation:batchedOperation]; -} - -#pragma mark - - -- (void)getPath:(NSString *)path - parameters:(NSDictionary *)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - [self enqueueHTTPRequestOperation:operation]; -} - -- (void)postPath:(NSString *)path - parameters:(NSDictionary *)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - [self enqueueHTTPRequestOperation:operation]; -} - -- (void)putPath:(NSString *)path - parameters:(NSDictionary *)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:parameters]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - [self enqueueHTTPRequestOperation:operation]; -} - -- (void)deletePath:(NSString *)path - parameters:(NSDictionary *)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:parameters]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - [self enqueueHTTPRequestOperation:operation]; -} - -- (void)patchPath:(NSString *)path - parameters:(NSDictionary *)parameters - success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - NSURLRequest *request = [self requestWithMethod:@"PATCH" path:path parameters:parameters]; - AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; - [self enqueueHTTPRequestOperation:operation]; -} - -#pragma mark - NSCoding - -- (id)initWithCoder:(NSCoder *)aDecoder { - NSURL *baseURL = [aDecoder decodeObjectForKey:@"baseURL"]; - - self = [self initWithBaseURL:baseURL]; - if (!self) { - return nil; - } - - self.stringEncoding = [aDecoder decodeIntegerForKey:@"stringEncoding"]; - self.parameterEncoding = (AFHTTPClientParameterEncoding) [aDecoder decodeIntegerForKey:@"parameterEncoding"]; - self.registeredHTTPOperationClassNames = [aDecoder decodeObjectForKey:@"registeredHTTPOperationClassNames"]; - self.defaultHeaders = [aDecoder decodeObjectForKey:@"defaultHeaders"]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder { - [aCoder encodeObject:self.baseURL forKey:@"baseURL"]; - [aCoder encodeInteger:(NSInteger)self.stringEncoding forKey:@"stringEncoding"]; - [aCoder encodeInteger:self.parameterEncoding forKey:@"parameterEncoding"]; - [aCoder encodeObject:self.registeredHTTPOperationClassNames forKey:@"registeredHTTPOperationClassNames"]; - [aCoder encodeObject:self.defaultHeaders forKey:@"defaultHeaders"]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPClient *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL]; - - HTTPClient.stringEncoding = self.stringEncoding; - HTTPClient.parameterEncoding = self.parameterEncoding; - HTTPClient.registeredHTTPOperationClassNames = [self.registeredHTTPOperationClassNames mutableCopyWithZone:zone]; - HTTPClient.defaultHeaders = [self.defaultHeaders mutableCopyWithZone:zone]; -#ifdef _SYSTEMCONFIGURATION_H - HTTPClient.networkReachabilityStatusBlock = self.networkReachabilityStatusBlock; -#endif - return HTTPClient; -} - -@end - -#pragma mark - - -static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY"; - -static NSString * const kAFMultipartFormCRLF = @"\r\n"; - -static NSInteger const kAFStreamToStreamBufferSize = 1024 * 1024; //1 meg default - -static inline NSString * AFMultipartFormInitialBoundary() { - return [NSString stringWithFormat:@"--%@%@", kAFMultipartFormBoundary, kAFMultipartFormCRLF]; -} - -static inline NSString * AFMultipartFormEncapsulationBoundary() { - return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, kAFMultipartFormBoundary, kAFMultipartFormCRLF]; -} - -static inline NSString * AFMultipartFormFinalBoundary() { - return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, kAFMultipartFormBoundary, kAFMultipartFormCRLF]; -} - -static inline NSString * AFContentTypeForPathExtension(NSString *extension) { -#ifdef __UTTYPE__ - NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); - NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); - if (!contentType) { - return @"application/octet-stream"; - } else { - return contentType; - } -#else - return @"application/octet-stream"; -#endif -} - -NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; -NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; - -@interface AFHTTPBodyPart : NSObject -@property (nonatomic, assign) NSStringEncoding stringEncoding; -@property (nonatomic, strong) NSDictionary *headers; -@property (nonatomic, strong) id body; -@property (nonatomic, assign) unsigned long long bodyContentLength; -@property (nonatomic, strong) NSInputStream *inputStream; - -@property (nonatomic, assign) BOOL hasInitialBoundary; -@property (nonatomic, assign) BOOL hasFinalBoundary; - -@property (nonatomic, readonly, getter = hasBytesAvailable) BOOL bytesAvailable; -@property (nonatomic, readonly) unsigned long long contentLength; - -- (NSInteger)read:(uint8_t *)buffer - maxLength:(NSUInteger)length; -@end - -@interface AFMultipartBodyStream : NSInputStream -@property (nonatomic, assign) NSUInteger numberOfBytesInPacket; -@property (nonatomic, assign) NSTimeInterval delay; -@property (nonatomic, strong) NSInputStream *inputStream; -@property (nonatomic, readonly) unsigned long long contentLength; -@property (nonatomic, readonly, getter = isEmpty) BOOL empty; - -- (id)initWithStringEncoding:(NSStringEncoding)encoding; -- (void)setInitialAndFinalBoundaries; -- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; -@end - -#pragma mark - - -@interface AFStreamingMultipartFormData () -@property (readwrite, nonatomic, copy) NSMutableURLRequest *request; -@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; -@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; -@end - -@implementation AFStreamingMultipartFormData -@synthesize request = _request; -@synthesize bodyStream = _bodyStream; -@synthesize stringEncoding = _stringEncoding; - -- (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest - stringEncoding:(NSStringEncoding)encoding -{ - self = [super init]; - if (!self) { - return nil; - } - - self.request = urlRequest; - self.stringEncoding = encoding; - self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding]; - - return self; -} - -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - error:(NSError * __autoreleasing *)error -{ - NSParameterAssert(fileURL); - NSParameterAssert(name); - - NSString *fileName = [fileURL lastPathComponent]; - NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]); - - return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error]; -} - -- (BOOL)appendPartWithFileURL:(NSURL *)fileURL - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType - error:(NSError * __autoreleasing *)error -{ - NSParameterAssert(fileURL); - NSParameterAssert(name); - NSParameterAssert(fileName); - NSParameterAssert(mimeType); - - if (![fileURL isFileURL]) { - NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil) forKey:NSLocalizedFailureReasonErrorKey]; - if (error != NULL) { - *error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; - } - - return NO; - } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) { - NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil) forKey:NSLocalizedFailureReasonErrorKey]; - if (error != NULL) { - *error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; - } - - return NO; - } - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; - [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; - - AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = mutableHeaders; - bodyPart.body = fileURL; - - NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:nil]; - bodyPart.bodyContentLength = [[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue]; - - [self.bodyStream appendHTTPBodyPart:bodyPart]; - - return YES; -} - - -- (void)appendPartWithInputStream:(NSInputStream *)inputStream - name:(NSString *)name - fileName:(NSString *)fileName - length:(unsigned long long)length - mimeType:(NSString *)mimeType -{ - NSParameterAssert(name); - NSParameterAssert(fileName); - NSParameterAssert(mimeType); - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; - [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; - - - AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = mutableHeaders; - bodyPart.body = inputStream; - - bodyPart.bodyContentLength = length; - - [self.bodyStream appendHTTPBodyPart:bodyPart]; -} - -- (void)appendPartWithFileData:(NSData *)data - name:(NSString *)name - fileName:(NSString *)fileName - mimeType:(NSString *)mimeType -{ - NSParameterAssert(name); - NSParameterAssert(fileName); - NSParameterAssert(mimeType); - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; - [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; - - [self appendPartWithHeaders:mutableHeaders body:data]; -} - -- (void)appendPartWithFormData:(NSData *)data - name:(NSString *)name -{ - NSParameterAssert(name); - - NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; - [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"]; - - [self appendPartWithHeaders:mutableHeaders body:data]; -} - -- (void)appendPartWithHeaders:(NSDictionary *)headers - body:(NSData *)body -{ - NSParameterAssert(body); - - AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = headers; - bodyPart.bodyContentLength = [body length]; - bodyPart.body = body; - - [self.bodyStream appendHTTPBodyPart:bodyPart]; -} - -- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes - delay:(NSTimeInterval)delay -{ - self.bodyStream.numberOfBytesInPacket = numberOfBytes; - self.bodyStream.delay = delay; -} - -- (NSMutableURLRequest *)requestByFinalizingMultipartFormData { - if ([self.bodyStream isEmpty]) { - return self.request; - } - - // Reset the initial and final boundaries to ensure correct Content-Length - [self.bodyStream setInitialAndFinalBoundaries]; - - [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", kAFMultipartFormBoundary] forHTTPHeaderField:@"Content-Type"]; - [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"]; - [self.request setHTTPBodyStream:self.bodyStream]; - - return self.request; -} - -@end - -#pragma mark - - -@interface AFMultipartBodyStream () -@property (nonatomic, assign) NSStreamStatus streamStatus; -@property (nonatomic, strong) NSError *streamError; -@property (nonatomic, assign) NSStringEncoding stringEncoding; -@property (nonatomic, strong) NSMutableArray *HTTPBodyParts; -@property (nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator; -@property (nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart; -@property (nonatomic, strong) NSOutputStream *outputStream; -@property (nonatomic, strong) NSMutableData *buffer; -@end - -@implementation AFMultipartBodyStream -@synthesize streamStatus = _streamStatus; -@synthesize streamError = _streamError; -@synthesize stringEncoding = _stringEncoding; -@synthesize HTTPBodyParts = _HTTPBodyParts; -@synthesize HTTPBodyPartEnumerator = _HTTPBodyPartEnumerator; -@synthesize currentHTTPBodyPart = _currentHTTPBodyPart; -@synthesize inputStream = _inputStream; -@synthesize outputStream = _outputStream; -@synthesize buffer = _buffer; -@synthesize numberOfBytesInPacket = _numberOfBytesInPacket; -@synthesize delay = _delay; - -- (id)initWithStringEncoding:(NSStringEncoding)encoding { - self = [super init]; - if (!self) { - return nil; - } - - self.stringEncoding = encoding; - self.HTTPBodyParts = [NSMutableArray array]; - self.numberOfBytesInPacket = NSIntegerMax; - - return self; -} - -- (void)setInitialAndFinalBoundaries { - if ([self.HTTPBodyParts count] > 0) { - for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { - bodyPart.hasInitialBoundary = NO; - bodyPart.hasFinalBoundary = NO; - } - - [[self.HTTPBodyParts objectAtIndex:0] setHasInitialBoundary:YES]; - [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; - } -} - -- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart { - [self.HTTPBodyParts addObject:bodyPart]; -} - -- (BOOL)isEmpty { - return [self.HTTPBodyParts count] == 0; -} - -#pragma mark - NSInputStream - -- (NSInteger)read:(uint8_t *)buffer - maxLength:(NSUInteger)length -{ - if ([self streamStatus] == NSStreamStatusClosed) { - return 0; - } - - NSInteger totalNumberOfBytesRead = 0; - - while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { - if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { - if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { - break; - } - } else { - NSUInteger maxLength = length - (NSUInteger)totalNumberOfBytesRead; - NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; - if (numberOfBytesRead == -1) { - self.streamError = self.currentHTTPBodyPart.inputStream.streamError; - break; - } else { - totalNumberOfBytesRead += numberOfBytesRead; - - if (self.delay > 0.0f) { - [NSThread sleepForTimeInterval:self.delay]; - } - } - } - } - - return totalNumberOfBytesRead; -} - -- (BOOL)getBuffer:(__unused uint8_t **)buffer - length:(__unused NSUInteger *)len -{ - return NO; -} - -- (BOOL)hasBytesAvailable { - return [self streamStatus] == NSStreamStatusOpen; -} - -#pragma mark - NSStream - -- (void)open { - if (self.streamStatus == NSStreamStatusOpen) { - return; - } - - self.streamStatus = NSStreamStatusOpen; - - [self setInitialAndFinalBoundaries]; - self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator]; -} - -- (void)close { - self.streamStatus = NSStreamStatusClosed; -} - -- (id)propertyForKey:(__unused NSString *)key { - return nil; -} - -- (BOOL)setProperty:(__unused id)property - forKey:(__unused NSString *)key -{ - return NO; -} - -- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop - forMode:(__unused NSString *)mode -{} - -- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop - forMode:(__unused NSString *)mode -{} - -- (unsigned long long)contentLength { - unsigned long long length = 0; - for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { - length += [bodyPart contentLength]; - } - - return length; -} - -#pragma mark - Undocumented CFReadStream Bridged Methods - -- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop - forMode:(__unused CFStringRef)aMode -{} - -- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop - forMode:(__unused CFStringRef)aMode -{} - -- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags - callback:(__unused CFReadStreamClientCallBack)inCallback - context:(__unused CFStreamClientContext *)inContext { - return NO; -} - -#pragma mark - NSCopying - --(id)copyWithZone:(NSZone *)zone { - AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; - - for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { - [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]]; - } - - [bodyStreamCopy setInitialAndFinalBoundaries]; - - return bodyStreamCopy; -} - -@end - -#pragma mark - - -typedef enum { - AFEncapsulationBoundaryPhase = 1, - AFHeaderPhase = 2, - AFBodyPhase = 3, - AFFinalBoundaryPhase = 4, -} AFHTTPBodyPartReadPhase; - -@interface AFHTTPBodyPart () { - AFHTTPBodyPartReadPhase _phase; - NSInputStream *_inputStream; - unsigned long long _phaseReadOffset; -} - -- (BOOL)transitionToNextPhase; -- (NSInteger)readData:(NSData *)data - intoBuffer:(uint8_t *)buffer - maxLength:(NSUInteger)length; -@end - -@implementation AFHTTPBodyPart -@synthesize stringEncoding = _stringEncoding; -@synthesize headers = _headers; -@synthesize body = _body; -@synthesize bodyContentLength = _bodyContentLength; -@synthesize inputStream = _inputStream; -@synthesize hasInitialBoundary = _hasInitialBoundary; -@synthesize hasFinalBoundary = _hasFinalBoundary; - -- (id)init { - self = [super init]; - if (!self) { - return nil; - } - - [self transitionToNextPhase]; - - return self; -} - -- (void)dealloc { - if (_inputStream) { - [_inputStream close]; - _inputStream = nil; - } -} - -- (NSInputStream *)inputStream { - if (!_inputStream) { - if ([self.body isKindOfClass:[NSData class]]) { - _inputStream = [NSInputStream inputStreamWithData:self.body]; - } else if ([self.body isKindOfClass:[NSURL class]]) { - _inputStream = [NSInputStream inputStreamWithURL:self.body]; - } else if ([self.body isKindOfClass:[NSInputStream class]]) { - _inputStream = self.body; - } - } - - return _inputStream; -} - -- (NSString *)stringForHeaders { - NSMutableString *headerString = [NSMutableString string]; - for (NSString *field in [self.headers allKeys]) { - [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]]; - } - [headerString appendString:kAFMultipartFormCRLF]; - - return [NSString stringWithString:headerString]; -} - -- (unsigned long long)contentLength { - unsigned long long length = 0; - - NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary() : AFMultipartFormEncapsulationBoundary()) dataUsingEncoding:self.stringEncoding]; - length += [encapsulationBoundaryData length]; - - NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; - length += [headersData length]; - - length += _bodyContentLength; - - NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding] : [NSData data]); - length += [closingBoundaryData length]; - - return length; -} - -- (BOOL)hasBytesAvailable { - // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer - if (_phase == AFFinalBoundaryPhase) { - return YES; - } - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wcovered-switch-default" - switch (self.inputStream.streamStatus) { - case NSStreamStatusNotOpen: - case NSStreamStatusOpening: - case NSStreamStatusOpen: - case NSStreamStatusReading: - case NSStreamStatusWriting: - return YES; - case NSStreamStatusAtEnd: - case NSStreamStatusClosed: - case NSStreamStatusError: - default: - return NO; - } -#pragma clang diagnostic pop -} - -- (NSInteger)read:(uint8_t *)buffer - maxLength:(NSUInteger)length -{ - NSUInteger totalNumberOfBytesRead = 0; - - if (_phase == AFEncapsulationBoundaryPhase) { - NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary() : AFMultipartFormEncapsulationBoundary()) dataUsingEncoding:self.stringEncoding]; - totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - } - - if (_phase == AFHeaderPhase) { - NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; - totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - } - - if (_phase == AFBodyPhase) { - NSInteger numberOfBytesRead = 0; - - numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - if (numberOfBytesRead == -1) { - return -1; - } else { - totalNumberOfBytesRead += numberOfBytesRead; - - if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) { - [self transitionToNextPhase]; - } - } - } - - if (_phase == AFFinalBoundaryPhase) { - NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding] : [NSData data]); - totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; - } - - return totalNumberOfBytesRead; -} - -- (NSInteger)readData:(NSData *)data - intoBuffer:(uint8_t *)buffer - maxLength:(NSUInteger)length -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); - [data getBytes:buffer range:range]; -#pragma clang diagnostic pop - - _phaseReadOffset += range.length; - - if (((NSUInteger)_phaseReadOffset) >= [data length]) { - [self transitionToNextPhase]; - } - - return (NSInteger)range.length; -} - -- (BOOL)transitionToNextPhase { - if (![[NSThread currentThread] isMainThread]) { - [self performSelectorOnMainThread:@selector(transitionToNextPhase) withObject:nil waitUntilDone:YES]; - return YES; - } - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wcovered-switch-default" - switch (_phase) { - case AFEncapsulationBoundaryPhase: - _phase = AFHeaderPhase; - break; - case AFHeaderPhase: - [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; - [self.inputStream open]; - _phase = AFBodyPhase; - break; - case AFBodyPhase: - [self.inputStream close]; - _phase = AFFinalBoundaryPhase; - break; - case AFFinalBoundaryPhase: - default: - _phase = AFEncapsulationBoundaryPhase; - break; - } - _phaseReadOffset = 0; -#pragma clang diagnostic pop - - return YES; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; - - bodyPart.stringEncoding = self.stringEncoding; - bodyPart.headers = self.headers; - bodyPart.bodyContentLength = self.bodyContentLength; - bodyPart.body = self.body; - - return bodyPart; -} - -@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h deleted file mode 100644 index b40e3d506712..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h +++ /dev/null @@ -1,133 +0,0 @@ -// AFHTTPRequestOperation.h -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import "AFURLConnectionOperation.h" - -/** - `AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request. - */ -@interface AFHTTPRequestOperation : AFURLConnectionOperation - -///---------------------------------------------- -/// @name Getting HTTP URL Connection Information -///---------------------------------------------- - -/** - The last HTTP response received by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSHTTPURLResponse *response; - -///---------------------------------------------------------- -/// @name Managing And Checking For Acceptable HTTP Responses -///---------------------------------------------------------- - -/** - A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`. - */ -@property (nonatomic, readonly) BOOL hasAcceptableStatusCode; - -/** - A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`. - */ -@property (nonatomic, readonly) BOOL hasAcceptableContentType; - -/** - The callback dispatch queue on success. If `NULL` (default), the main queue is used. - */ -@property (nonatomic, assign) dispatch_queue_t successCallbackQueue; - -/** - The callback dispatch queue on failure. If `NULL` (default), the main queue is used. - */ -@property (nonatomic, assign) dispatch_queue_t failureCallbackQueue; - -///------------------------------------------------------------ -/// @name Managing Acceptable HTTP Status Codes & Content Types -///------------------------------------------------------------ - -/** - Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html - - By default, this is the range 200 to 299, inclusive. - */ -+ (NSIndexSet *)acceptableStatusCodes; - -/** - Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants. - - @param statusCodes The status codes to be added to the set of acceptable HTTP status codes - */ -+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes; - -/** - Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17 - - By default, this is `nil`. - */ -+ (NSSet *)acceptableContentTypes; - -/** - Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendants. - - @param contentTypes The content types to be added to the set of acceptable MIME types - */ -+ (void)addAcceptableContentTypes:(NSSet *)contentTypes; - - -///----------------------------------------------------- -/// @name Determining Whether A Request Can Be Processed -///----------------------------------------------------- - -/** - A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`. - - @param urlRequest The request that is determined to be supported or not supported for this class. - */ -+ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest; - -///----------------------------------------------------------- -/// @name Setting Completion Block Success / Failure Callbacks -///----------------------------------------------------------- - -/** - Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed. - - This method should be overridden in subclasses in order to specify the response object passed into the success block. - - @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request. - @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request. - */ -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; - -@end - -///---------------- -/// @name Functions -///---------------- - -/** - Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header. - */ -extern NSSet * AFContentTypesFromHTTPHeader(NSString *string); - diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m deleted file mode 100644 index 84f2badb6940..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m +++ /dev/null @@ -1,327 +0,0 @@ -// AFHTTPRequestOperation.m -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFHTTPRequestOperation.h" -#import - -// Workaround for change in imp_implementationWithBlock() with Xcode 4.5 -#if defined(__IPHONE_6_0) || defined(__MAC_10_8) -#define AF_CAST_TO_BLOCK id -#else -#define AF_CAST_TO_BLOCK __bridge void * -#endif - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wstrict-selector-match" - -NSSet * AFContentTypesFromHTTPHeader(NSString *string) { - if (!string) { - return nil; - } - - NSArray *mediaRanges = [string componentsSeparatedByString:@","]; - NSMutableSet *mutableContentTypes = [NSMutableSet setWithCapacity:mediaRanges.count]; - - [mediaRanges enumerateObjectsUsingBlock:^(NSString *mediaRange, __unused NSUInteger idx, __unused BOOL *stop) { - NSRange parametersRange = [mediaRange rangeOfString:@";"]; - if (parametersRange.location != NSNotFound) { - mediaRange = [mediaRange substringToIndex:parametersRange.location]; - } - - mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; - - if (mediaRange.length > 0) { - [mutableContentTypes addObject:mediaRange]; - } - }]; - - return [NSSet setWithSet:mutableContentTypes]; -} - -static void AFGetMediaTypeAndSubtypeWithString(NSString *string, NSString **type, NSString **subtype) { - if (!string) { - return; - } - - NSScanner *scanner = [NSScanner scannerWithString:string]; - [scanner setCharactersToBeSkipped:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; - [scanner scanUpToString:@"/" intoString:type]; - [scanner scanString:@"/" intoString:nil]; - [scanner scanUpToString:@";" intoString:subtype]; -} - -static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) { - NSMutableString *string = [NSMutableString string]; - - NSRange range = NSMakeRange([indexSet firstIndex], 1); - while (range.location != NSNotFound) { - NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location]; - while (nextIndex == range.location + range.length) { - range.length++; - nextIndex = [indexSet indexGreaterThanIndex:nextIndex]; - } - - if (string.length) { - [string appendString:@","]; - } - - if (range.length == 1) { - [string appendFormat:@"%lu", (long)range.location]; - } else { - NSUInteger firstIndex = range.location; - NSUInteger lastIndex = firstIndex + range.length - 1; - [string appendFormat:@"%lu-%lu", (long)firstIndex, (long)lastIndex]; - } - - range.location = nextIndex; - range.length = 1; - } - - return string; -} - -static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) { - Method originalMethod = class_getClassMethod(klass, selector); - IMP implementation = imp_implementationWithBlock((AF_CAST_TO_BLOCK)block); - class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod)); -} - -#pragma mark - - -@interface AFHTTPRequestOperation () -@property (readwrite, nonatomic, strong) NSURLRequest *request; -@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response; -@property (readwrite, nonatomic, strong) NSError *HTTPError; -@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; -@end - -@implementation AFHTTPRequestOperation -@synthesize HTTPError = _HTTPError; -@synthesize successCallbackQueue = _successCallbackQueue; -@synthesize failureCallbackQueue = _failureCallbackQueue; -@dynamic lock; -@dynamic request; -@dynamic response; - -- (void)dealloc { - if (_successCallbackQueue) { -#if !OS_OBJECT_USE_OBJC - dispatch_release(_successCallbackQueue); -#endif - _successCallbackQueue = NULL; - } - - if (_failureCallbackQueue) { -#if !OS_OBJECT_USE_OBJC - dispatch_release(_failureCallbackQueue); -#endif - _failureCallbackQueue = NULL; - } -} - -- (NSError *)error { - [self.lock lock]; - if (!self.HTTPError && self.response) { - if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) { - NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; - [userInfo setValue:self.responseString forKey:NSLocalizedRecoverySuggestionErrorKey]; - [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; - [userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey]; - [userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey]; - - if (![self hasAcceptableStatusCode]) { - NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; - [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected status code in (%@), got %d", @"AFNetworking", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey]; - self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo]; - } else if (![self hasAcceptableContentType]) { - // Don't invalidate content type if there is no content - if ([self.responseData length] > 0) { - [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected content type %@, got %@", @"AFNetworking", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey]; - self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; - } - } - } - } - [self.lock unlock]; - - if (self.HTTPError) { - return self.HTTPError; - } else { - return [super error]; - } -} - -- (NSStringEncoding)responseStringEncoding { - // When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP. Data in character sets other than "ISO-8859-1" or its subsets MUST be labeled with an appropriate charset value. - // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.4.1 - if (self.response && !self.response.textEncodingName && self.responseData && [self.response respondsToSelector:@selector(allHeaderFields)]) { - NSString *type = nil; - AFGetMediaTypeAndSubtypeWithString([[self.response allHeaderFields] valueForKey:@"Content-Type"], &type, nil); - - if ([type isEqualToString:@"text"]) { - return NSISOLatin1StringEncoding; - } - } - - return [super responseStringEncoding]; -} - -- (void)pause { - unsigned long long offset = 0; - if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { - offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue]; - } else { - offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length]; - } - - NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy]; - if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) { - [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"]; - } - [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"]; - self.request = mutableURLRequest; - - [super pause]; -} - -- (BOOL)hasAcceptableStatusCode { - if (!self.response) { - return NO; - } - - NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; - return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode]; -} - -- (BOOL)hasAcceptableContentType { - if (!self.response) { - return NO; - } - - // Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream". - // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html - NSString *contentType = [self.response MIMEType]; - if (!contentType) { - contentType = @"application/octet-stream"; - } - - return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType]; -} - -- (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue { - if (successCallbackQueue != _successCallbackQueue) { - if (_successCallbackQueue) { -#if !OS_OBJECT_USE_OBJC - dispatch_release(_successCallbackQueue); -#endif - _successCallbackQueue = NULL; - } - - if (successCallbackQueue) { -#if !OS_OBJECT_USE_OBJC - dispatch_retain(successCallbackQueue); -#endif - _successCallbackQueue = successCallbackQueue; - } - } -} - -- (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue { - if (failureCallbackQueue != _failureCallbackQueue) { - if (_failureCallbackQueue) { -#if !OS_OBJECT_USE_OBJC - dispatch_release(_failureCallbackQueue); -#endif - _failureCallbackQueue = NULL; - } - - if (failureCallbackQueue) { -#if !OS_OBJECT_USE_OBJC - dispatch_retain(failureCallbackQueue); -#endif - _failureCallbackQueue = failureCallbackQueue; - } - } -} - -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ - // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-retain-cycles" -#pragma clang diagnostic ignored "-Wgnu" - self.completionBlock = ^{ - if (self.error) { - if (failure) { - dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - if (success) { - dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ - success(self, self.responseData); - }); - } - } - }; -#pragma clang diagnostic pop -} - -#pragma mark - AFHTTPRequestOperation - -+ (NSIndexSet *)acceptableStatusCodes { - return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; -} - -+ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes { - NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]]; - [mutableStatusCodes addIndexes:statusCodes]; - AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(__unused id _self) { - return mutableStatusCodes; - }); -} - -+ (NSSet *)acceptableContentTypes { - return nil; -} - -+ (void)addAcceptableContentTypes:(NSSet *)contentTypes { - NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES]; - [mutableContentTypes unionSet:contentTypes]; - AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(__unused id _self) { - return mutableContentTypes; - }); -} - -+ (BOOL)canProcessRequest:(NSURLRequest *)request { - if ([[self class] isEqual:[AFHTTPRequestOperation class]]) { - return YES; - } - - return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])]; -} - -@end - -#pragma clang diagnostic pop diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.h deleted file mode 100644 index d5e659679db1..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.h +++ /dev/null @@ -1,113 +0,0 @@ -// AFImageRequestOperation.h -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import "AFHTTPRequestOperation.h" - -#import - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -#import -#endif - -/** - `AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and processing images. - - ## Acceptable Content Types - - By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: - - - `image/tiff` - - `image/jpeg` - - `image/gif` - - `image/png` - - `image/ico` - - `image/x-icon` - - `image/bmp` - - `image/x-bmp` - - `image/x-xbitmap` - - `image/x-win-bitmap` - */ -@interface AFImageRequestOperation : AFHTTPRequestOperation - -/** - An image constructed from the response data. If an error occurs during the request, `nil` will be returned, and the `error` property will be set to the error. - */ -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -@property (readonly, nonatomic, strong) UIImage *responseImage; -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -@property (readonly, nonatomic, strong) NSImage *responseImage; -#endif - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -/** - The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. - */ -@property (nonatomic, assign) CGFloat imageScale; - -/** - Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. - */ -@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; -#endif - -/** - Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. - - @param urlRequest The request object to be loaded asynchronously during execution of the operation. - @param success A block object to be executed when the request finishes successfully. This block has no return value and takes a single argument, the image created from the response data of the request. - - @return A new image request operation - */ -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(UIImage *image))success; -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSImage *image))success; -#endif - -/** - Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. - - @param urlRequest The request object to be loaded asynchronously during execution of the operation. - @param imageProcessingBlock A block object to be executed after the image request finishes successfully, but before the image is returned in the `success` block. This block takes a single argument, the image loaded from the response body, and returns the processed image. - @param success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the image created from the response data. - @param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation. - - @return A new image request operation - */ -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest - imageProcessingBlock:(UIImage *(^)(UIImage *image))imageProcessingBlock - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest - imageProcessingBlock:(NSImage *(^)(NSImage *image))imageProcessingBlock - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; -#endif - -@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.m deleted file mode 100644 index 7023b37afaa6..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.m +++ /dev/null @@ -1,321 +0,0 @@ -// AFImageRequestOperation.m -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFImageRequestOperation.h" - -static dispatch_queue_t image_request_operation_processing_queue() { - static dispatch_queue_t af_image_request_operation_processing_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", DISPATCH_QUEUE_CONCURRENT); - }); - - return af_image_request_operation_processing_queue; -} - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import - -static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { - UIImage *image = [[UIImage alloc] initWithData:data]; - - return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; -} - -static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { - if (!data || [data length] == 0) { - return nil; - } - - UIImage *image = AFImageWithDataAtScale(data, scale); - if (image.images) { - return image; - } - - CGImageRef imageRef = nil; - CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); - - if ([response.MIMEType isEqualToString:@"image/png"]) { - imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); - } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { - imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); - } - - if (!imageRef) { - imageRef = CGImageCreateCopy([image CGImage]); - - if (!imageRef) { - CGDataProviderRelease(dataProvider); - return image; - } - } - - CGDataProviderRelease(dataProvider); - - size_t width = CGImageGetWidth(imageRef); - size_t height = CGImageGetHeight(imageRef); - size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); - size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate() - CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); - CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); - - if (CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { - int alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); - if (alpha == kCGImageAlphaNone) { - bitmapInfo &= ~kCGBitmapAlphaInfoMask; - bitmapInfo |= kCGImageAlphaNoneSkipFirst; - } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { - bitmapInfo &= ~kCGBitmapAlphaInfoMask; - bitmapInfo |= kCGImageAlphaPremultipliedFirst; - } - } - - CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); - - CGColorSpaceRelease(colorSpace); - - if (!context) { - CGImageRelease(imageRef); - - return image; - } - - CGRect rect = CGRectMake(0.0f, 0.0f, width, height); - CGContextDrawImage(context, rect, imageRef); - CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context); - CGContextRelease(context); - - UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation]; - CGImageRelease(inflatedImageRef); - CGImageRelease(imageRef); - - return inflatedImage; -} -#endif - -@interface AFImageRequestOperation () -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -@property (readwrite, nonatomic, strong) UIImage *responseImage; -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -@property (readwrite, nonatomic, strong) NSImage *responseImage; -#endif -@end - -@implementation AFImageRequestOperation -@synthesize responseImage = _responseImage; -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -@synthesize imageScale = _imageScale; -#endif - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(UIImage *image))success -{ - return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) { - if (success) { - success(image); - } - } failure:nil]; -} -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSImage *image))success -{ - return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) { - if (success) { - success(image); - } - } failure:nil]; -} -#endif - - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest - imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure -{ - AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest]; - [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - if (success) { - UIImage *image = responseObject; - if (imageProcessingBlock) { - dispatch_async(image_request_operation_processing_queue(), ^(void) { - UIImage *processedImage = imageProcessingBlock(image); -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) { - success(operation.request, operation.response, processedImage); - }); -#pragma clang diagnostic pop - }); - } else { - success(operation.request, operation.response, image); - } - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if (failure) { - failure(operation.request, operation.response, error); - } - }]; - - - return requestOperation; -} -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -+ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest - imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure -{ - AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest]; - [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - if (success) { - NSImage *image = responseObject; - if (imageProcessingBlock) { - dispatch_async(image_request_operation_processing_queue(), ^(void) { - NSImage *processedImage = imageProcessingBlock(image); - - dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) { - success(operation.request, operation.response, processedImage); - }); - }); - } else { - success(operation.request, operation.response, image); - } - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if (failure) { - failure(operation.request, operation.response, error); - } - }]; - - return requestOperation; -} -#endif - -- (id)initWithRequest:(NSURLRequest *)urlRequest { - self = [super initWithRequest:urlRequest]; - if (!self) { - return nil; - } - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - self.imageScale = [[UIScreen mainScreen] scale]; - self.automaticallyInflatesResponseImage = YES; -#endif - - return self; -} - - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -- (UIImage *)responseImage { - if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) { - if (self.automaticallyInflatesResponseImage) { - self.responseImage = AFInflatedImageFromResponseWithDataAtScale(self.response, self.responseData, self.imageScale); - } else { - self.responseImage = AFImageWithDataAtScale(self.responseData, self.imageScale); - } - } - - return _responseImage; -} - -- (void)setImageScale:(CGFloat)imageScale { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wfloat-equal" - if (imageScale == _imageScale) { - return; - } -#pragma clang diagnostic pop - - _imageScale = imageScale; - - self.responseImage = nil; -} -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) -- (NSImage *)responseImage { - if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) { - // Ensure that the image is set to it's correct pixel width and height - NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData]; - self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; - [self.responseImage addRepresentation:bitimage]; - } - - return _responseImage; -} -#endif - -#pragma mark - AFHTTPRequestOperation - -+ (NSSet *)acceptableContentTypes { - return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; -} - -+ (BOOL)canProcessRequest:(NSURLRequest *)request { - static NSSet * _acceptablePathExtension = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil]; - }); - - return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request]; -} - -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-retain-cycles" -#pragma clang diagnostic ignored "-Wgnu" - - self.completionBlock = ^ { - dispatch_async(image_request_operation_processing_queue(), ^(void) { - if (self.error) { - if (failure) { - dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - if (success) { -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - UIImage *image = nil; -#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) - NSImage *image = nil; -#endif - - image = self.responseImage; - - dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ - success(self, image); - }); - } - } - }); - }; -#pragma clang diagnostic pop -} - -@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.h deleted file mode 100644 index 5493a40775fe..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.h +++ /dev/null @@ -1,71 +0,0 @@ -// AFJSONRequestOperation.h -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import "AFHTTPRequestOperation.h" - -/** - `AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with JSON response data. - - ## Acceptable Content Types - - By default, `AFJSONRequestOperation` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: - - - `application/json` - - `text/json` - - @warning JSON parsing will use the built-in `NSJSONSerialization` class. - */ -@interface AFJSONRequestOperation : AFHTTPRequestOperation - -///---------------------------- -/// @name Getting Response Data -///---------------------------- - -/** - A JSON object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error. - */ -@property (readonly, nonatomic, strong) id responseJSON; - -/** - Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". - */ -@property (nonatomic, assign) NSJSONReadingOptions JSONReadingOptions; - -///---------------------------------- -/// @name Creating Request Operations -///---------------------------------- - -/** - Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks. - - @param urlRequest The request object to be loaded asynchronously during execution of the operation - @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the JSON object created from the response data of request. - @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as JSON. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred. - - @return A new JSON request operation - */ -+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure; - -@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.m deleted file mode 100644 index fffc60c5907f..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.m +++ /dev/null @@ -1,150 +0,0 @@ -// AFJSONRequestOperation.m -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFJSONRequestOperation.h" - -static dispatch_queue_t json_request_operation_processing_queue() { - static dispatch_queue_t af_json_request_operation_processing_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", DISPATCH_QUEUE_CONCURRENT); - }); - - return af_json_request_operation_processing_queue; -} - -@interface AFJSONRequestOperation () -@property (readwrite, nonatomic, strong) id responseJSON; -@property (readwrite, nonatomic, strong) NSError *JSONError; -@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; -@end - -@implementation AFJSONRequestOperation -@synthesize responseJSON = _responseJSON; -@synthesize JSONReadingOptions = _JSONReadingOptions; -@synthesize JSONError = _JSONError; -@dynamic lock; - -+ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure -{ - AFJSONRequestOperation *requestOperation = [(AFJSONRequestOperation *)[self alloc] initWithRequest:urlRequest]; - [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - if (success) { - success(operation.request, operation.response, responseObject); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if (failure) { - failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]); - } - }]; - - return requestOperation; -} - - -- (id)responseJSON { - [self.lock lock]; - if (!_responseJSON && [self.responseData length] > 0 && [self isFinished] && !self.JSONError) { - NSError *error = nil; - - // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. - // See https://github.com/rails/rails/issues/1742 - if (self.responseString && ![self.responseString isEqualToString:@" "]) { - // Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character - // See http://stackoverflow.com/a/12843465/157142 - NSData *data = [self.responseString dataUsingEncoding:NSUTF8StringEncoding]; - - if (data) { - self.responseJSON = [NSJSONSerialization JSONObjectWithData:data options:self.JSONReadingOptions error:&error]; - } else { - NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; - [userInfo setValue:@"Operation responseData failed decoding as a UTF-8 string" forKey:NSLocalizedDescriptionKey]; - [userInfo setValue:[NSString stringWithFormat:@"Could not decode string: %@", self.responseString] forKey:NSLocalizedFailureReasonErrorKey]; - error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; - } - } - - self.JSONError = error; - } - [self.lock unlock]; - - return _responseJSON; -} - -- (NSError *)error { - if (_JSONError) { - return _JSONError; - } else { - return [super error]; - } -} - -#pragma mark - AFHTTPRequestOperation - -+ (NSSet *)acceptableContentTypes { - return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; -} - -+ (BOOL)canProcessRequest:(NSURLRequest *)request { - return [[[request URL] pathExtension] isEqualToString:@"json"] || [super canProcessRequest:request]; -} - -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-retain-cycles" -#pragma clang diagnostic ignored "-Wgnu" - - self.completionBlock = ^ { - if (self.error) { - if (failure) { - dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - dispatch_async(json_request_operation_processing_queue(), ^{ - id JSON = self.responseJSON; - - if (self.error) { - if (failure) { - dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - if (success) { - dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ - success(self, JSON); - }); - } - } - }); - } - }; -#pragma clang diagnostic pop -} - -@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h deleted file mode 100644 index 714193baf37d..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h +++ /dev/null @@ -1,75 +0,0 @@ -// AFNetworkActivityIndicatorManager.h -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import - -/** - `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a network request operation has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. - - You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: - - [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; - - By setting `isNetworkActivityIndicatorVisible` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. - - See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: - http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 - */ -@interface AFNetworkActivityIndicatorManager : NSObject - -/** - A Boolean value indicating whether the manager is enabled. - - If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. - */ -@property (nonatomic, assign, getter = isEnabled) BOOL enabled; - -/** - A Boolean value indicating whether the network activity indicator is currently displayed in the status bar. - */ -@property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible; - -/** - Returns the shared network activity indicator manager object for the system. - - @return The systemwide network activity indicator manager. - */ -+ (instancetype)sharedManager; - -/** - Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. - */ -- (void)incrementActivityCount; - -/** - Decrements the number of active network requests. If this number becomes zero before decrementing, this will stop animating the status bar network activity indicator. - */ -- (void)decrementActivityCount; - -@end - -#endif diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.m deleted file mode 100644 index 68cbd339691c..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.m +++ /dev/null @@ -1,157 +0,0 @@ -// AFNetworkActivityIndicatorManager.m -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFNetworkActivityIndicatorManager.h" - -#import "AFHTTPRequestOperation.h" - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17; - -@interface AFNetworkActivityIndicatorManager () -@property (readwrite, nonatomic, assign) NSInteger activityCount; -@property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer; -@property (readonly, nonatomic, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; - -- (void)updateNetworkActivityIndicatorVisibility; -- (void)updateNetworkActivityIndicatorVisibilityDelayed; -@end - -@implementation AFNetworkActivityIndicatorManager -@synthesize activityCount = _activityCount; -@synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer; -@synthesize enabled = _enabled; -@dynamic networkActivityIndicatorVisible; - -+ (instancetype)sharedManager { - static AFNetworkActivityIndicatorManager *_sharedManager = nil; - static dispatch_once_t oncePredicate; - dispatch_once(&oncePredicate, ^{ - _sharedManager = [[self alloc] init]; - }); - - return _sharedManager; -} - -+ (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible { - return [NSSet setWithObject:@"activityCount"]; -} - -- (id)init { - self = [super init]; - if (!self) { - return nil; - } - - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidStart:) name:AFNetworkingOperationDidStartNotification object:nil]; - [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil]; - - return self; -} - -- (void)dealloc { - [[NSNotificationCenter defaultCenter] removeObserver:self]; - - [_activityIndicatorVisibilityTimer invalidate]; - -} - -- (void)updateNetworkActivityIndicatorVisibilityDelayed { - if (self.enabled) { - // Delay hiding of activity indicator for a short interval, to avoid flickering - if (![self isNetworkActivityIndicatorVisible]) { - [self.activityIndicatorVisibilityTimer invalidate]; - self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO]; - [[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes]; - } else { - [self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:[NSArray arrayWithObject:NSRunLoopCommonModes]]; - } - } -} - -- (BOOL)isNetworkActivityIndicatorVisible { - return _activityCount > 0; -} - -- (void)updateNetworkActivityIndicatorVisibility { - [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]]; -} - -// Not exposed, but used if activityCount is set via KVC. -- (NSInteger)activityCount { - return _activityCount; -} - -- (void)setActivityCount:(NSInteger)activityCount { - @synchronized(self) { - _activityCount = activityCount; - } - - dispatch_async(dispatch_get_main_queue(), ^{ - [self updateNetworkActivityIndicatorVisibilityDelayed]; - }); -} - -- (void)incrementActivityCount { - [self willChangeValueForKey:@"activityCount"]; - @synchronized(self) { - _activityCount++; - } - [self didChangeValueForKey:@"activityCount"]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [self updateNetworkActivityIndicatorVisibilityDelayed]; - }); -} - -- (void)decrementActivityCount { - [self willChangeValueForKey:@"activityCount"]; - @synchronized(self) { -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wgnu" - _activityCount = MAX(_activityCount - 1, 0); -#pragma clang diagnostic pop - } - [self didChangeValueForKey:@"activityCount"]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [self updateNetworkActivityIndicatorVisibilityDelayed]; - }); -} - -- (void)networkingOperationDidStart:(NSNotification *)notification { - AFURLConnectionOperation *connectionOperation = [notification object]; - if (connectionOperation.request.URL) { - [self incrementActivityCount]; - } -} - -- (void)networkingOperationDidFinish:(NSNotification *)notification { - AFURLConnectionOperation *connectionOperation = [notification object]; - if (connectionOperation.request.URL) { - [self decrementActivityCount]; - } -} - -@end - -#endif diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworking.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworking.h deleted file mode 100644 index b8f840b92cfb..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworking.h +++ /dev/null @@ -1,43 +0,0 @@ -// AFNetworking.h -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import - -#ifndef _AFNETWORKING_ - #define _AFNETWORKING_ - - #import "AFURLConnectionOperation.h" - - #import "AFHTTPRequestOperation.h" - #import "AFJSONRequestOperation.h" - #import "AFXMLRequestOperation.h" - #import "AFPropertyListRequestOperation.h" - #import "AFHTTPClient.h" - - #import "AFImageRequestOperation.h" - - #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - #import "AFNetworkActivityIndicatorManager.h" - #import "UIImageView+AFNetworking.h" - #endif -#endif /* _AFNETWORKING_ */ diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.h deleted file mode 100644 index 9ebb6057437f..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.h +++ /dev/null @@ -1,68 +0,0 @@ -// AFPropertyListRequestOperation.h -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import "AFHTTPRequestOperation.h" - -/** - `AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data. - - ## Acceptable Content Types - - By default, `AFPropertyListRequestOperation` accepts the following MIME types: - - - `application/x-plist` - */ -@interface AFPropertyListRequestOperation : AFHTTPRequestOperation - -///---------------------------- -/// @name Getting Response Data -///---------------------------- - -/** - An object deserialized from a plist constructed using the response data. - */ -@property (readonly, nonatomic) id responsePropertyList; - -///-------------------------------------- -/// @name Managing Property List Behavior -///-------------------------------------- - -/** - One of the `NSPropertyListMutabilityOptions` options, specifying the mutability of objects deserialized from the property list. By default, this is `NSPropertyListImmutable`. - */ -@property (nonatomic, assign) NSPropertyListReadOptions propertyListReadOptions; - -/** - Creates and returns an `AFPropertyListRequestOperation` object and sets the specified success and failure callbacks. - - @param urlRequest The request object to be loaded asynchronously during execution of the operation - @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the object deserialized from a plist constructed using the response data. - @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while deserializing the object from a property list. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred. - - @return A new property list request operation - */ -+ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure; - -@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.m deleted file mode 100644 index 370e12be8e39..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.m +++ /dev/null @@ -1,143 +0,0 @@ -// AFPropertyListRequestOperation.m -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFPropertyListRequestOperation.h" - -static dispatch_queue_t property_list_request_operation_processing_queue() { - static dispatch_queue_t af_property_list_request_operation_processing_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", DISPATCH_QUEUE_CONCURRENT); - }); - - return af_property_list_request_operation_processing_queue; -} - -@interface AFPropertyListRequestOperation () -@property (readwrite, nonatomic) id responsePropertyList; -@property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat; -@property (readwrite, nonatomic) NSError *propertyListError; -@end - -@implementation AFPropertyListRequestOperation -@synthesize responsePropertyList = _responsePropertyList; -@synthesize propertyListReadOptions = _propertyListReadOptions; -@synthesize propertyListFormat = _propertyListFormat; -@synthesize propertyListError = _propertyListError; - -+ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)request - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure -{ - AFPropertyListRequestOperation *requestOperation = [(AFPropertyListRequestOperation *)[self alloc] initWithRequest:request]; - [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - if (success) { - success(operation.request, operation.response, responseObject); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if (failure) { - failure(operation.request, operation.response, error, [(AFPropertyListRequestOperation *)operation responsePropertyList]); - } - }]; - - return requestOperation; -} - -- (id)initWithRequest:(NSURLRequest *)urlRequest { - self = [super initWithRequest:urlRequest]; - if (!self) { - return nil; - } - - self.propertyListReadOptions = NSPropertyListImmutable; - - return self; -} - - -- (id)responsePropertyList { - if (!_responsePropertyList && [self.responseData length] > 0 && [self isFinished]) { - NSPropertyListFormat format; - NSError *error = nil; - self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error]; - self.propertyListFormat = format; - self.propertyListError = error; - } - - return _responsePropertyList; -} - -- (NSError *)error { - if (_propertyListError) { - return _propertyListError; - } else { - return [super error]; - } -} - -#pragma mark - AFHTTPRequestOperation - -+ (NSSet *)acceptableContentTypes { - return [NSSet setWithObjects:@"application/x-plist", nil]; -} - -+ (BOOL)canProcessRequest:(NSURLRequest *)request { - return [[[request URL] pathExtension] isEqualToString:@"plist"] || [super canProcessRequest:request]; -} - -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-retain-cycles" -#pragma clang diagnostic ignored "-Wgnu" - self.completionBlock = ^ { - if (self.error) { - if (failure) { - dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - dispatch_async(property_list_request_operation_processing_queue(), ^(void) { - id propertyList = self.responsePropertyList; - - if (self.propertyListError) { - if (failure) { - dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - if (success) { - dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ - success(self, propertyList); - }); - } - } - }); - } - }; -#pragma clang diagnostic pop -} - -@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h deleted file mode 100644 index 0ac9e105c3f7..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h +++ /dev/null @@ -1,370 +0,0 @@ -// AFURLConnectionOperation.h -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import - -#import - -/** - `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods. - - ## Subclassing Notes - - This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors. - - If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes. - - ## NSURLConnection Delegate Methods - - `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods: - - - `connection:didReceiveResponse:` - - `connection:didReceiveData:` - - `connectionDidFinishLoading:` - - `connection:didFailWithError:` - - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:` - - `connection:willCacheResponse:` - - `connectionShouldUseCredentialStorage:` - - `connection:willSendRequestForAuthenticationChallenge:` - - If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. - - ## Class Constructors - - Class constructors, or methods that return an unowned instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, `AFJSONRequestOperation` provides `JSONRequestOperationWithRequest:success:failure:`, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the `response data`. - - ## Callbacks and Completion Blocks - - The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this. - - Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/). - - ## SSL Pinning - - Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle. - - SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice. - - When `defaultSSLPinningMode` is defined on `AFHTTPClient` and the Security framework is linked, connections will be validated on all matching certificates with a `.cer` extension in the bundle root. - - ## NSCoding & NSCopying Conformance - - `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind: - - ### NSCoding Caveats - - - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`. - - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged. - - ### NSCopying Caveats - - - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations. - - A copy of an operation will not include the `outputStream` of the original. - - Operation copies do not include `completionBlock`. `completionBlock` often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied. - */ - -typedef enum { - AFSSLPinningModeNone, - AFSSLPinningModePublicKey, - AFSSLPinningModeCertificate, -} AFURLConnectionOperationSSLPinningMode; - -@interface AFURLConnectionOperation : NSOperation = 50000) || \ - (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080) -NSURLConnectionDataDelegate, -#endif -NSCoding, NSCopying> - -///------------------------------- -/// @name Accessing Run Loop Modes -///------------------------------- - -/** - The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`. - */ -@property (nonatomic, strong) NSSet *runLoopModes; - -///----------------------------------------- -/// @name Getting URL Connection Information -///----------------------------------------- - -/** - The request used by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSURLRequest *request; - -/** - The last response received by the operation's connection. - */ -@property (readonly, nonatomic, strong) NSURLResponse *response; - -/** - The error, if any, that occurred in the lifecycle of the request. - */ -@property (readonly, nonatomic, strong) NSError *error; - -/** - Whether the connection should accept an invalid SSL certificate. - - If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is set, this property defaults to `YES` for backwards compatibility. Otherwise, this property defaults to `NO`. - */ -@property (nonatomic, assign) BOOL allowsInvalidSSLCertificate; - -///---------------------------- -/// @name Getting Response Data -///---------------------------- - -/** - The data received during the request. - */ -@property (readonly, nonatomic, strong) NSData *responseData; - -/** - The string representation of the response data. - */ -@property (readonly, nonatomic, copy) NSString *responseString; - -/** - The string encoding of the response. - - If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`. - */ -@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding; - -///------------------------------- -/// @name Managing URL Credentials -///------------------------------- - -/** - Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. - - This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. - */ -@property (nonatomic, assign) BOOL shouldUseCredentialStorage; - -/** - The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. - - This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. - */ -@property (nonatomic, strong) NSURLCredential *credential; - -/** - The pinning mode which will be used for SSL connections. `AFSSLPinningModePublicKey` by default. - - SSL Pinning requires that the Security framework is linked with the binary. See the "SSL Pinning" section in the `AFURLConnectionOperation`" header for more information. - */ -@property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode SSLPinningMode; - -///------------------------ -/// @name Accessing Streams -///------------------------ - -/** - The input stream used to read data to be sent during the request. - - This property acts as a proxy to the `HTTPBodyStream` property of `request`. - */ -@property (nonatomic, strong) NSInputStream *inputStream; - -/** - The output stream that is used to write data received until the request is finished. - - By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set. - */ -@property (nonatomic, strong) NSOutputStream *outputStream; - -///--------------------------------------------- -/// @name Managing Request Operation Information -///--------------------------------------------- - -/** - The user info dictionary for the receiver. - */ -@property (nonatomic, strong) NSDictionary *userInfo; - -///------------------------------------------------------ -/// @name Initializing an AFURLConnectionOperation Object -///------------------------------------------------------ - -/** - Initializes and returns a newly allocated operation object with a url connection configured with the specified url request. - - This is the designated initializer. - - @param urlRequest The request object to be used by the operation connection. - */ -- (id)initWithRequest:(NSURLRequest *)urlRequest; - -///---------------------------------- -/// @name Pausing / Resuming Requests -///---------------------------------- - -/** - Pauses the execution of the request operation. - - A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect. - */ -- (void)pause; - -/** - Whether the request operation is currently paused. - - @return `YES` if the operation is currently paused, otherwise `NO`. - */ -- (BOOL)isPaused; - -/** - Resumes the execution of the paused request operation. - - Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request. - */ -- (void)resume; - -///---------------------------------------------- -/// @name Configuring Backgrounding Task Behavior -///---------------------------------------------- - -/** - Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task. - - @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified. - */ -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler; -#endif - -///--------------------------------- -/// @name Setting Progress Callbacks -///--------------------------------- - -/** - Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. - - @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. - */ -- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block; - -/** - Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. - - @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread. - */ -- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block; - -///------------------------------------------------- -/// @name Setting NSURLConnection Delegate Callbacks -///------------------------------------------------- - -/** - Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`. - - @param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol). - - If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates. - */ -- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block; - -/** - Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequest:redirectResponse:`. - - @param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect. - */ -- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block; - -/** - Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`. - - @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request. - */ -- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block; - -@end - -///---------------- -/// @name Constants -///---------------- - -/** - ## SSL Pinning Options - - The following constants are provided by `AFURLConnectionOperation` as possible SSL Pinning options. - - enum { - AFSSLPinningModeNone, - AFSSLPinningModePublicKey, - AFSSLPinningModeCertificate, - } - - `AFSSLPinningModeNone` - Do not pin SSL connections - - `AFSSLPinningModePublicKey` - Pin SSL connections to certificate public key (SPKI). - - `AFSSLPinningModeCertificate` - Pin SSL connections to exact certificate. This may cause problems when your certificate expires and needs re-issuance. - - ## User info dictionary keys - - These keys may exist in the user info dictionary, in addition to those defined for NSError. - - - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` - - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` - - ### Constants - - `AFNetworkingOperationFailingURLRequestErrorKey` - The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`. - - `AFNetworkingOperationFailingURLResponseErrorKey` - The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`. - - ## Error Domains - - The following error domain is predefined. - - - `NSString * const AFNetworkingErrorDomain` - - ### Constants - - `AFNetworkingErrorDomain` - AFNetworking errors. Error codes for `AFNetworkingErrorDomain` correspond to codes in `NSURLErrorDomain`. - */ -extern NSString * const AFNetworkingErrorDomain; -extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey; -extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey; - -///-------------------- -/// @name Notifications -///-------------------- - -/** - Posted when an operation begins executing. - */ -extern NSString * const AFNetworkingOperationDidStartNotification; - -/** - Posted when an operation finishes. - */ -extern NSString * const AFNetworkingOperationDidFinishNotification; diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m deleted file mode 100644 index 595ea864317a..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m +++ /dev/null @@ -1,848 +0,0 @@ -// AFURLConnectionOperation.m -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFURLConnectionOperation.h" - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import -#endif - -#if !__has_feature(objc_arc) -#error AFNetworking must be built with ARC. -// You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files. -#endif - -typedef enum { - AFOperationPausedState = -1, - AFOperationReadyState = 1, - AFOperationExecutingState = 2, - AFOperationFinishedState = 3, -} _AFOperationState; - -typedef signed short AFOperationState; - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier; -#else -typedef id AFBackgroundTaskIdentifier; -#endif - -static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock"; - -NSString * const AFNetworkingErrorDomain = @"AFNetworkingErrorDomain"; -NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"AFNetworkingOperationFailingURLRequestErrorKey"; -NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"AFNetworkingOperationFailingURLResponseErrorKey"; - -NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start"; -NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish"; - -typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); -typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge); -typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse); -typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse); - -static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { - switch (state) { - case AFOperationReadyState: - return @"isReady"; - case AFOperationExecutingState: - return @"isExecuting"; - case AFOperationFinishedState: - return @"isFinished"; - case AFOperationPausedState: - return @"isPaused"; - default: - return @"state"; - } -} - -static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) { - switch (fromState) { - case AFOperationReadyState: - switch (toState) { - case AFOperationPausedState: - case AFOperationExecutingState: - return YES; - case AFOperationFinishedState: - return isCancelled; - default: - return NO; - } - case AFOperationExecutingState: - switch (toState) { - case AFOperationPausedState: - case AFOperationFinishedState: - return YES; - default: - return NO; - } - case AFOperationFinishedState: - return NO; - case AFOperationPausedState: - return toState == AFOperationReadyState; - default: - return YES; - } -} - -#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -static NSData *AFSecKeyGetData(SecKeyRef key) { - CFDataRef data = NULL; - - OSStatus status = SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data); - NSCAssert(status == errSecSuccess, @"SecItemExport error: %ld", (long int)status); - NSCParameterAssert(data); - - return (__bridge_transfer NSData *)data; -} -#endif - -static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - return [(__bridge id)key1 isEqual:(__bridge id)key2]; -#else - return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; -#endif -} - -@interface AFURLConnectionOperation () -@property (readwrite, nonatomic, assign) AFOperationState state; -@property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled; -@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; -@property (readwrite, nonatomic, strong) NSURLConnection *connection; -@property (readwrite, nonatomic, strong) NSURLRequest *request; -@property (readwrite, nonatomic, strong) NSURLResponse *response; -@property (readwrite, nonatomic, strong) NSError *error; -@property (readwrite, nonatomic, strong) NSData *responseData; -@property (readwrite, nonatomic, copy) NSString *responseString; -@property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding; -@property (readwrite, nonatomic, assign) long long totalBytesRead; -@property (readwrite, nonatomic, assign) AFBackgroundTaskIdentifier backgroundTaskIdentifier; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse; -@property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse; - -- (void)operationDidStart; -- (void)finish; -- (void)cancelConnection; -@end - -@implementation AFURLConnectionOperation -@synthesize state = _state; -@synthesize cancelled = _cancelled; -@synthesize connection = _connection; -@synthesize runLoopModes = _runLoopModes; -@synthesize request = _request; -@synthesize response = _response; -@synthesize error = _error; -@synthesize allowsInvalidSSLCertificate = _allowsInvalidSSLCertificate; -@synthesize responseData = _responseData; -@synthesize responseString = _responseString; -@synthesize responseStringEncoding = _responseStringEncoding; -@synthesize totalBytesRead = _totalBytesRead; -@dynamic inputStream; -@synthesize outputStream = _outputStream; -@synthesize credential = _credential; -@synthesize SSLPinningMode = _SSLPinningMode; -@synthesize shouldUseCredentialStorage = _shouldUseCredentialStorage; -@synthesize userInfo = _userInfo; -@synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier; -@synthesize uploadProgress = _uploadProgress; -@synthesize downloadProgress = _downloadProgress; -@synthesize authenticationChallenge = _authenticationChallenge; -@synthesize cacheResponse = _cacheResponse; -@synthesize redirectResponse = _redirectResponse; -@synthesize lock = _lock; - -+ (void)networkRequestThreadEntryPoint:(id __unused)object { - @autoreleasepool { - [[NSThread currentThread] setName:@"AFNetworking"]; - - NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; - [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; - [runLoop run]; - } -} - -+ (NSThread *)networkRequestThread { - static NSThread *_networkRequestThread = nil; - static dispatch_once_t oncePredicate; - dispatch_once(&oncePredicate, ^{ - _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil]; - [_networkRequestThread start]; - }); - - return _networkRequestThread; -} - -+ (NSArray *)pinnedCertificates { - static NSArray *_pinnedCertificates = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - NSBundle *bundle = [NSBundle mainBundle]; - NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; - - NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]]; - for (NSString *path in paths) { - NSData *certificateData = [NSData dataWithContentsOfFile:path]; - [certificates addObject:certificateData]; - } - - _pinnedCertificates = [[NSArray alloc] initWithArray:certificates]; - }); - - return _pinnedCertificates; -} - -+ (NSArray *)pinnedPublicKeys { - static NSArray *_pinnedPublicKeys = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - NSArray *pinnedCertificates = [self pinnedCertificates]; - NSMutableArray *publicKeys = [NSMutableArray arrayWithCapacity:[pinnedCertificates count]]; - - for (NSData *data in pinnedCertificates) { - SecCertificateRef allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)data); - NSParameterAssert(allowedCertificate); - - SecCertificateRef allowedCertificates[] = {allowedCertificate}; - CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); - - SecPolicyRef policy = SecPolicyCreateBasicX509(); - SecTrustRef allowedTrust = NULL; - OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &allowedTrust); - NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status); - if (status == errSecSuccess && allowedTrust) { - SecTrustResultType result = 0; - status = SecTrustEvaluate(allowedTrust, &result); - NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status); - if (status == errSecSuccess) { - SecKeyRef allowedPublicKey = SecTrustCopyPublicKey(allowedTrust); - NSParameterAssert(allowedPublicKey); - if (allowedPublicKey) { - [publicKeys addObject:(__bridge_transfer id)allowedPublicKey]; - } - } - - CFRelease(allowedTrust); - } - - CFRelease(policy); - CFRelease(certificates); - CFRelease(allowedCertificate); - } - - _pinnedPublicKeys = [[NSArray alloc] initWithArray:publicKeys]; - }); - - return _pinnedPublicKeys; -} - -- (id)initWithRequest:(NSURLRequest *)urlRequest { - NSParameterAssert(urlRequest); - - self = [super init]; - if (!self) { - return nil; - } - - self.lock = [[NSRecursiveLock alloc] init]; - self.lock.name = kAFNetworkingLockName; - - self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; - - self.request = urlRequest; - - self.shouldUseCredentialStorage = YES; - - // #ifdef included for backwards-compatibility -#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ - self.allowsInvalidSSLCertificate = YES; -#endif - - self.state = AFOperationReadyState; - - return self; -} - -- (void)dealloc { - if (_outputStream) { - [_outputStream close]; - _outputStream = nil; - } - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) - if (_backgroundTaskIdentifier) { - [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier]; - _backgroundTaskIdentifier = UIBackgroundTaskInvalid; - } -#endif -} - -- (NSString *)description { - return [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response]; -} - -- (void)setCompletionBlock:(void (^)(void))block { - [self.lock lock]; - if (!block) { - [super setCompletionBlock:nil]; - } else { - __weak __typeof(&*self)weakSelf = self; - [super setCompletionBlock:^ { - __strong __typeof(&*weakSelf)strongSelf = weakSelf; - - block(); - [strongSelf setCompletionBlock:nil]; - }]; - } - [self.lock unlock]; -} - -- (NSInputStream *)inputStream { - return self.request.HTTPBodyStream; -} - -- (void)setInputStream:(NSInputStream *)inputStream { - [self willChangeValueForKey:@"inputStream"]; - NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; - mutableRequest.HTTPBodyStream = inputStream; - self.request = mutableRequest; - [self didChangeValueForKey:@"inputStream"]; -} - -- (NSOutputStream *)outputStream { - if (!_outputStream) { - self.outputStream = [NSOutputStream outputStreamToMemory]; - } - - return _outputStream; -} - -- (void)setOutputStream:(NSOutputStream *)outputStream { - [self.lock lock]; - if (outputStream != _outputStream) { - [self willChangeValueForKey:@"outputStream"]; - if (_outputStream) { - [_outputStream close]; - } - _outputStream = outputStream; - [self didChangeValueForKey:@"outputStream"]; - } - [self.lock unlock]; -} - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler { - [self.lock lock]; - if (!self.backgroundTaskIdentifier) { - UIApplication *application = [UIApplication sharedApplication]; - __weak __typeof(&*self)weakSelf = self; - self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ - __strong __typeof(&*weakSelf)strongSelf = weakSelf; - - if (handler) { - handler(); - } - - if (strongSelf) { - [strongSelf cancel]; - - [application endBackgroundTask:strongSelf.backgroundTaskIdentifier]; - strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; - } - }]; - } - [self.lock unlock]; -} -#endif - -- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block { - self.uploadProgress = block; -} - -- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block { - self.downloadProgress = block; -} - -- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block { - self.authenticationChallenge = block; -} - -- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block { - self.cacheResponse = block; -} - -- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block { - self.redirectResponse = block; -} - -- (void)setState:(AFOperationState)state { - if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) { - return; - } - - [self.lock lock]; - NSString *oldStateKey = AFKeyPathFromOperationState(self.state); - NSString *newStateKey = AFKeyPathFromOperationState(state); - - [self willChangeValueForKey:newStateKey]; - [self willChangeValueForKey:oldStateKey]; - _state = state; - [self didChangeValueForKey:oldStateKey]; - [self didChangeValueForKey:newStateKey]; - [self.lock unlock]; -} - -- (NSString *)responseString { - [self.lock lock]; - if (!_responseString && self.response && self.responseData) { - self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding]; - } - [self.lock unlock]; - - return _responseString; -} - -- (NSStringEncoding)responseStringEncoding { - [self.lock lock]; - if (!_responseStringEncoding && self.response) { - NSStringEncoding stringEncoding = NSUTF8StringEncoding; - if (self.response.textEncodingName) { - CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName); - if (IANAEncoding != kCFStringEncodingInvalidId) { - stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding); - } - } - - self.responseStringEncoding = stringEncoding; - } - [self.lock unlock]; - - return _responseStringEncoding; -} - -- (void)pause { - if ([self isPaused] || [self isFinished] || [self isCancelled]) { - return; - } - - [self.lock lock]; - - if ([self isExecuting]) { - [self.connection performSelector:@selector(cancel) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - - dispatch_async(dispatch_get_main_queue(), ^{ - NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; - [notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; - }); - } - - self.state = AFOperationPausedState; - - [self.lock unlock]; -} - -- (BOOL)isPaused { - return self.state == AFOperationPausedState; -} - -- (void)resume { - if (![self isPaused]) { - return; - } - - [self.lock lock]; - self.state = AFOperationReadyState; - - [self start]; - [self.lock unlock]; -} - -#pragma mark - NSOperation - -- (BOOL)isReady { - return self.state == AFOperationReadyState && [super isReady]; -} - -- (BOOL)isExecuting { - return self.state == AFOperationExecutingState; -} - -- (BOOL)isFinished { - return self.state == AFOperationFinishedState; -} - -- (BOOL)isConcurrent { - return YES; -} - -- (void)start { - [self.lock lock]; - if ([self isReady]) { - self.state = AFOperationExecutingState; - - [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - } - [self.lock unlock]; -} - -- (void)operationDidStart { - [self.lock lock]; - if (![self isCancelled]) { - self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; - - NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; - for (NSString *runLoopMode in self.runLoopModes) { - [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode]; - [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; - } - - [self.connection start]; - } - [self.lock unlock]; - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self]; - }); - - if ([self isCancelled]) { - NSDictionary *userInfo = nil; - if ([self.request URL]) { - userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; - } - self.error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; - - [self finish]; - } -} - -- (void)finish { - self.state = AFOperationFinishedState; - - dispatch_async(dispatch_get_main_queue(), ^{ - [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; - }); -} - -- (void)cancel { - [self.lock lock]; - if (![self isFinished] && ![self isCancelled]) { - [self willChangeValueForKey:@"isCancelled"]; - _cancelled = YES; - [super cancel]; - [self didChangeValueForKey:@"isCancelled"]; - - // Cancel the connection on the thread it runs on to prevent race conditions - [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; - } - [self.lock unlock]; -} - -- (void)cancelConnection { - NSDictionary *userInfo = nil; - if ([self.request URL]) { - userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; - } - NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; - - if (![self isFinished] && self.connection) { - [self.connection cancel]; - [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error]; - } -} - -#pragma mark - NSURLConnectionDelegate - -- (void)connection:(NSURLConnection *)connection -willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge -{ - if (self.authenticationChallenge) { - self.authenticationChallenge(connection, challenge); - return; - } - - if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { - SecTrustRef serverTrust = challenge.protectionSpace.serverTrust; - - SecPolicyRef policy = SecPolicyCreateBasicX509(); - CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); - NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:certificateCount]; - - for (CFIndex i = 0; i < certificateCount; i++) { - SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); - - if (self.SSLPinningMode == AFSSLPinningModeCertificate) { - [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; - } else if (self.SSLPinningMode == AFSSLPinningModePublicKey) { - SecCertificateRef someCertificates[] = {certificate}; - CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); - - SecTrustRef trust = NULL; - - OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust); - NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status); - if (status == errSecSuccess && trust) { - SecTrustResultType result; - status = SecTrustEvaluate(trust, &result); - NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status); - if (status == errSecSuccess) { - [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; - } - - CFRelease(trust); - } - - CFRelease(certificates); - } - } - - CFRelease(policy); - - switch (self.SSLPinningMode) { - case AFSSLPinningModePublicKey: { - NSArray *pinnedPublicKeys = [self.class pinnedPublicKeys]; - - for (id publicKey in trustChain) { - for (id pinnedPublicKey in pinnedPublicKeys) { - if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)publicKey, (__bridge SecKeyRef)pinnedPublicKey)) { - NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; - [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; - return; - } - } - } - - [[challenge sender] cancelAuthenticationChallenge:challenge]; - break; - } - case AFSSLPinningModeCertificate: { - for (id serverCertificateData in trustChain) { - if ([[self.class pinnedCertificates] containsObject:serverCertificateData]) { - NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; - [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; - return; - } - } - - [[challenge sender] cancelAuthenticationChallenge:challenge]; - break; - } - case AFSSLPinningModeNone: { - if (self.allowsInvalidSSLCertificate){ - NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; - [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; - } else { - SecTrustResultType result = 0; - OSStatus status = SecTrustEvaluate(serverTrust, &result); - NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status); - - if (status == errSecSuccess && (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed)) { - NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; - [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] cancelAuthenticationChallenge:challenge]; - } - } - break; - } - } - } else { - if ([challenge previousFailureCount] == 0) { - if (self.credential) { - [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge]; - } else { - [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; - } - } else { - [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; - } - } -} - -- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection { - return self.shouldUseCredentialStorage; -} - -- (NSURLRequest *)connection:(NSURLConnection *)connection - willSendRequest:(NSURLRequest *)request - redirectResponse:(NSURLResponse *)redirectResponse -{ - if (self.redirectResponse) { - return self.redirectResponse(connection, request, redirectResponse); - } else { - return request; - } -} - -- (void)connection:(NSURLConnection __unused *)connection - didSendBodyData:(NSInteger)bytesWritten - totalBytesWritten:(NSInteger)totalBytesWritten -totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite -{ - if (self.uploadProgress) { - dispatch_async(dispatch_get_main_queue(), ^{ - self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); - }); - } -} - -- (void)connection:(NSURLConnection __unused *)connection -didReceiveResponse:(NSURLResponse *)response -{ - self.response = response; - - [self.outputStream open]; -} - -- (void)connection:(NSURLConnection __unused *)connection - didReceiveData:(NSData *)data -{ - NSUInteger length = [data length]; - while (YES) { - NSUInteger totalNumberOfBytesWritten = 0; - if ([self.outputStream hasSpaceAvailable]) { - const uint8_t *dataBuffer = (uint8_t *)[data bytes]; - - NSInteger numberOfBytesWritten = 0; - while (totalNumberOfBytesWritten < length) { - numberOfBytesWritten = [self.outputStream write:&dataBuffer[0] maxLength:length]; - if (numberOfBytesWritten == -1) { - [self.connection cancel]; - [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError]; - return; - } else { - totalNumberOfBytesWritten += numberOfBytesWritten; - } - } - - break; - } - } - - dispatch_async(dispatch_get_main_queue(), ^{ - self.totalBytesRead += length; - - if (self.downloadProgress) { - self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength); - } - }); -} - -- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection { - self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; - - [self.outputStream close]; - - [self finish]; - - self.connection = nil; -} - -- (void)connection:(NSURLConnection __unused *)connection - didFailWithError:(NSError *)error -{ - self.error = error; - - [self.outputStream close]; - - [self finish]; - - self.connection = nil; -} - -- (NSCachedURLResponse *)connection:(NSURLConnection *)connection - willCacheResponse:(NSCachedURLResponse *)cachedResponse -{ - if (self.cacheResponse) { - return self.cacheResponse(connection, cachedResponse); - } else { - if ([self isCancelled]) { - return nil; - } - - return cachedResponse; - } -} - -#pragma mark - NSCoding - -- (id)initWithCoder:(NSCoder *)aDecoder { - NSURLRequest *request = [aDecoder decodeObjectForKey:@"request"]; - - self = [self initWithRequest:request]; - if (!self) { - return nil; - } - - self.state = (AFOperationState)[aDecoder decodeIntegerForKey:@"state"]; - self.cancelled = [aDecoder decodeBoolForKey:@"isCancelled"]; - self.response = [aDecoder decodeObjectForKey:@"response"]; - self.error = [aDecoder decodeObjectForKey:@"error"]; - self.responseData = [aDecoder decodeObjectForKey:@"responseData"]; - self.totalBytesRead = [[aDecoder decodeObjectForKey:@"totalBytesRead"] longLongValue]; - self.allowsInvalidSSLCertificate = [[aDecoder decodeObjectForKey:@"allowsInvalidSSLCertificate"] boolValue]; - - return self; -} - -- (void)encodeWithCoder:(NSCoder *)aCoder { - [self pause]; - - [aCoder encodeObject:self.request forKey:@"request"]; - - switch (self.state) { - case AFOperationExecutingState: - case AFOperationPausedState: - [aCoder encodeInteger:AFOperationReadyState forKey:@"state"]; - break; - default: - [aCoder encodeInteger:self.state forKey:@"state"]; - break; - } - - [aCoder encodeBool:[self isCancelled] forKey:@"isCancelled"]; - [aCoder encodeObject:self.response forKey:@"response"]; - [aCoder encodeObject:self.error forKey:@"error"]; - [aCoder encodeObject:self.responseData forKey:@"responseData"]; - [aCoder encodeObject:[NSNumber numberWithLongLong:self.totalBytesRead] forKey:@"totalBytesRead"]; - [aCoder encodeObject:[NSNumber numberWithBool:self.allowsInvalidSSLCertificate] forKey:@"allowsInvalidSSLCertificate"]; -} - -#pragma mark - NSCopying - -- (id)copyWithZone:(NSZone *)zone { - AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request]; - - operation.uploadProgress = self.uploadProgress; - operation.downloadProgress = self.downloadProgress; - operation.authenticationChallenge = self.authenticationChallenge; - operation.cacheResponse = self.cacheResponse; - operation.redirectResponse = self.redirectResponse; - operation.allowsInvalidSSLCertificate = self.allowsInvalidSSLCertificate; - - return operation; -} - -@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.h deleted file mode 100644 index 4130932e6988..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.h +++ /dev/null @@ -1,89 +0,0 @@ -// AFXMLRequestOperation.h -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import "AFHTTPRequestOperation.h" - -#import - -/** - `AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data. - - ## Acceptable Content Types - - By default, `AFXMLRequestOperation` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: - - - `application/xml` - - `text/xml` - - ## Use With AFHTTPClient - - When `AFXMLRequestOperation` is registered with `AFHTTPClient`, the response object in the success callback of `HTTPRequestOperationWithRequest:success:failure:` will be an instance of `NSXMLParser`. On platforms that support `NSXMLDocument`, you have the option to ignore the response object, and simply use the `responseXMLDocument` property of the operation argument of the callback. - */ -@interface AFXMLRequestOperation : AFHTTPRequestOperation - -///---------------------------- -/// @name Getting Response Data -///---------------------------- - -/** - An `NSXMLParser` object constructed from the response data. - */ -@property (readonly, nonatomic, strong) NSXMLParser *responseXMLParser; - -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED -/** - An `NSXMLDocument` object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error. - */ -@property (readonly, nonatomic, strong) NSXMLDocument *responseXMLDocument; -#endif - -/** - Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks. - - @param urlRequest The request object to be loaded asynchronously during execution of the operation - @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML parser constructed with the response data of request. - @param failure A block object to be executed when the operation finishes unsuccessfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network error that occurred. - - @return A new XML request operation - */ -+ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure; - - -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED -/** - Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks. - - @param urlRequest The request object to be loaded asynchronously during execution of the operation - @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML document created from the response data of request. - @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as XML. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred. - - @return A new XML request operation - */ -+ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure; -#endif - -@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.m deleted file mode 100644 index a97cd88478d2..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.m +++ /dev/null @@ -1,167 +0,0 @@ -// AFXMLRequestOperation.m -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import "AFXMLRequestOperation.h" - -#include - -static dispatch_queue_t xml_request_operation_processing_queue() { - static dispatch_queue_t af_xml_request_operation_processing_queue; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", DISPATCH_QUEUE_CONCURRENT); - }); - - return af_xml_request_operation_processing_queue; -} - -@interface AFXMLRequestOperation () -@property (readwrite, nonatomic, strong) NSXMLParser *responseXMLParser; -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED -@property (readwrite, nonatomic, strong) NSXMLDocument *responseXMLDocument; -#endif -@property (readwrite, nonatomic, strong) NSError *XMLError; -@end - -@implementation AFXMLRequestOperation -@synthesize responseXMLParser = _responseXMLParser; -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED -@synthesize responseXMLDocument = _responseXMLDocument; -#endif -@synthesize XMLError = _XMLError; - -+ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure -{ - AFXMLRequestOperation *requestOperation = [(AFXMLRequestOperation *)[self alloc] initWithRequest:urlRequest]; - [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - if (success) { - success(operation.request, operation.response, responseObject); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if (failure) { - failure(operation.request, operation.response, error, [(AFXMLRequestOperation *)operation responseXMLParser]); - } - }]; - - return requestOperation; -} - -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED -+ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure -{ - AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest]; - [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) { - if (success) { - NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument]; - success(operation.request, operation.response, XMLDocument); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if (failure) { - NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument]; - failure(operation.request, operation.response, error, XMLDocument); - } - }]; - - return requestOperation; -} -#endif - - -- (NSXMLParser *)responseXMLParser { - if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) { - self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData]; - } - - return _responseXMLParser; -} - -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED -- (NSXMLDocument *)responseXMLDocument { - if (!_responseXMLDocument && [self.responseData length] > 0 && [self isFinished]) { - NSError *error = nil; - self.responseXMLDocument = [[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error]; - self.XMLError = error; - } - - return _responseXMLDocument; -} -#endif - -- (NSError *)error { - if (_XMLError) { - return _XMLError; - } else { - return [super error]; - } -} - -#pragma mark - NSOperation - -- (void)cancel { - [super cancel]; - - self.responseXMLParser.delegate = nil; -} - -#pragma mark - AFHTTPRequestOperation - -+ (NSSet *)acceptableContentTypes { - return [NSSet setWithObjects:@"application/xml", @"text/xml", nil]; -} - -+ (BOOL)canProcessRequest:(NSURLRequest *)request { - return [[[request URL] pathExtension] isEqualToString:@"xml"] || [super canProcessRequest:request]; -} - -- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success - failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure -{ -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Warc-retain-cycles" -#pragma clang diagnostic ignored "-Wgnu" - self.completionBlock = ^ { - dispatch_async(xml_request_operation_processing_queue(), ^(void) { - NSXMLParser *XMLParser = self.responseXMLParser; - - if (self.error) { - if (failure) { - dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ - failure(self, self.error); - }); - } - } else { - if (success) { - dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ - success(self, XMLParser); - }); - } - } - }); - }; -#pragma clang diagnostic pop -} - -@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.h deleted file mode 100644 index bafb7901ea7a..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.h +++ /dev/null @@ -1,78 +0,0 @@ -// UIImageView+AFNetworking.h -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import "AFImageRequestOperation.h" - -#import - -#if __IPHONE_OS_VERSION_MIN_REQUIRED -#import - -/** - This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. - */ -@interface UIImageView (AFNetworking) - -/** - Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL, and sets it the request is finished. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. - - By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` - - @param url The URL used for the image request. - */ -- (void)setImageWithURL:(NSURL *)url; - -/** - Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. - - By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` - - @param url The URL used for the image request. - @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. - */ -- (void)setImageWithURL:(NSURL *)url - placeholderImage:(UIImage *)placeholderImage; - -/** - Creates and enqueues an image request operation, which asynchronously downloads the image with the specified URL request object. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. - - If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is executed. - - @param urlRequest The URL request used for the image request. - @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. - @param success A block to be executed when the image request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the request and response parameters will be `nil`. - @param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. - */ -- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest - placeholderImage:(UIImage *)placeholderImage - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; - -/** - Cancels any executing image request operation for the receiver, if one exists. - */ -- (void)cancelImageRequestOperation; - -@end - -#endif diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.m deleted file mode 100644 index 839a2b85722f..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.m +++ /dev/null @@ -1,191 +0,0 @@ -// UIImageView+AFNetworking.m -// -// Copyright (c) 2011 Gowalla (http://gowalla.com/) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -#import -#import - -#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#import "UIImageView+AFNetworking.h" - -@interface AFImageCache : NSCache -- (UIImage *)cachedImageForRequest:(NSURLRequest *)request; -- (void)cacheImage:(UIImage *)image - forRequest:(NSURLRequest *)request; -@end - -#pragma mark - - -static char kAFImageRequestOperationObjectKey; - -@interface UIImageView (_AFNetworking) -@property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation; -@end - -@implementation UIImageView (_AFNetworking) -@dynamic af_imageRequestOperation; -@end - -#pragma mark - - -@implementation UIImageView (AFNetworking) - -- (AFHTTPRequestOperation *)af_imageRequestOperation { - return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey); -} - -- (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation { - objc_setAssociatedObject(self, &kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); -} - -+ (NSOperationQueue *)af_sharedImageRequestOperationQueue { - static NSOperationQueue *_af_imageRequestOperationQueue = nil; - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _af_imageRequestOperationQueue = [[NSOperationQueue alloc] init]; - [_af_imageRequestOperationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount]; - }); - - return _af_imageRequestOperationQueue; -} - -+ (AFImageCache *)af_sharedImageCache { - static AFImageCache *_af_imageCache = nil; - static dispatch_once_t oncePredicate; - dispatch_once(&oncePredicate, ^{ - _af_imageCache = [[AFImageCache alloc] init]; - }); - - return _af_imageCache; -} - -#pragma mark - - -- (void)setImageWithURL:(NSURL *)url { - [self setImageWithURL:url placeholderImage:nil]; -} - -- (void)setImageWithURL:(NSURL *)url - placeholderImage:(UIImage *)placeholderImage -{ - NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; - [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; - - [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; -} - -- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest - placeholderImage:(UIImage *)placeholderImage - success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success - failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure -{ - [self cancelImageRequestOperation]; - - UIImage *cachedImage = [[[self class] af_sharedImageCache] cachedImageForRequest:urlRequest]; - if (cachedImage) { - self.af_imageRequestOperation = nil; - - if (success) { - success(nil, nil, cachedImage); - } else { - self.image = cachedImage; - } - } else { - if (placeholderImage) { - self.image = placeholderImage; - } - - AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest]; - -#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ - requestOperation.allowsInvalidSSLCertificate = YES; -#endif - - [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { - if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) { - if (self.af_imageRequestOperation == operation) { - self.af_imageRequestOperation = nil; - } - - if (success) { - success(operation.request, operation.response, responseObject); - } else if (responseObject) { - self.image = responseObject; - } - } - - [[[self class] af_sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) { - if (self.af_imageRequestOperation == operation) { - self.af_imageRequestOperation = nil; - } - - if (failure) { - failure(operation.request, operation.response, error); - } - } - }]; - - self.af_imageRequestOperation = requestOperation; - - [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation]; - } -} - -- (void)cancelImageRequestOperation { - [self.af_imageRequestOperation cancel]; - self.af_imageRequestOperation = nil; -} - -@end - -#pragma mark - - -static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) { - return [[request URL] absoluteString]; -} - -@implementation AFImageCache - -- (UIImage *)cachedImageForRequest:(NSURLRequest *)request { - switch ([request cachePolicy]) { - case NSURLRequestReloadIgnoringCacheData: - case NSURLRequestReloadIgnoringLocalAndRemoteCacheData: - return nil; - default: - break; - } - - return [self objectForKey:AFImageCacheKeyFromURLRequest(request)]; -} - -- (void)cacheImage:(UIImage *)image - forRequest:(NSURLRequest *)request -{ - if (image && request) { - [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)]; - } -} - -@end - -#endif diff --git a/samples/client/petstore/objc/Pods/AFNetworking/LICENSE b/samples/client/petstore/objc/Pods/AFNetworking/LICENSE deleted file mode 100644 index 42d32adadadd..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2011 Gowalla (http://gowalla.com/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/samples/client/petstore/objc/Pods/AFNetworking/README.md b/samples/client/petstore/objc/Pods/AFNetworking/README.md deleted file mode 100644 index 4d2f226d4eb8..000000000000 --- a/samples/client/petstore/objc/Pods/AFNetworking/README.md +++ /dev/null @@ -1,208 +0,0 @@ -

    - AFNetworking -

    - -[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.png?branch=master)](https://travis-ci.org/AFNetworking/AFNetworking) - -AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of [NSURLConnection](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html), [NSOperation](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html), and other familiar Foundation technologies. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. For example, here's how easy it is to get JSON from a URL: - -```objective-c -NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"]; -NSURLRequest *request = [NSURLRequest requestWithURL:url]; -AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { - NSLog(@"App.net Global Stream: %@", JSON); -} failure:nil]; -[operation start]; -``` - -Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. - -Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did! - -## How To Get Started - -- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/zipball/master) and try out the included Mac and iPhone example apps -- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles in the wiki](https://github.com/AFNetworking/AFNetworking/wiki) -- Check out the [complete documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at the APIs available in AFNetworking -- Watch the [NSScreencast episode about AFNetworking](http://nsscreencast.com/episodes/6-afnetworking) for a quick introduction to how to use it in your application -- Questions? [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking) is the best place to find answers - -## Overview - -AFNetworking is architected to be as small and modular as possible, in order to make it simple to use and extend. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    Core
    AFURLConnectionOperationAn NSOperation that implements the NSURLConnection delegate methods.
    HTTP Requests
    AFHTTPRequestOperationA subclass of AFURLConnectionOperation for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
    AFJSONRequestOperationA subclass of AFHTTPRequestOperation for downloading and working with JSON response data.
    AFXMLRequestOperationA subclass of AFHTTPRequestOperation for downloading and working with XML response data.
    AFPropertyListRequestOperationA subclass of AFHTTPRequestOperation for downloading and deserializing objects with property list response data.
    HTTP Client
    AFHTTPClient - Captures the common patterns of communicating with an web application over HTTP, including: - -
      -
    • Making requests from relative paths of a base URL
    • -
    • Setting HTTP headers to be added automatically to requests
    • -
    • Authenticating requests with HTTP Basic credentials or an OAuth token
    • -
    • Managing an NSOperationQueue for requests made by the client
    • -
    • Generating query strings or HTTP bodies from an NSDictionary
    • -
    • Constructing multipart form requests
    • -
    • Automatically parsing HTTP response data into its corresponding object representation
    • -
    • Monitoring and responding to changes in network reachability
    • -
    -
    Images
    AFImageRequestOperationA subclass of AFHTTPRequestOperation for downloading and processing images.
    UIImageView+AFNetworkingAdds methods to UIImageView for loading remote images asynchronously from a URL.
    - -## Example Usage - -### XML Request - -```objective-c -NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]]; -AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) { - XMLParser.delegate = self; - [XMLParser parse]; -} failure:nil]; -[operation start]; -``` - -### Image Request - -```objective-c -UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)]; -[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]]; -``` - -### API Client Request - -```objective-c -// AFAppDotNetAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates -[[AFAppDotNetAPIClient sharedClient] getPath:@"stream/0/posts/stream/global" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) { - NSLog(@"App.net Global Stream: %@", JSON); -} failure:nil]; -``` - -### File Upload with Progress Callback - -```objective-c -NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"]; -AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; -NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5); -NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id formData) { - [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"]; -}]; - -AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; -[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { - NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); -}]; -[httpClient enqueueHTTPRequestOperation:operation]; -``` - -### Streaming Request - -```objective-c -NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]]; - -AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; -operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]]; -operation.outputStream = [NSOutputStream outputStreamToMemory]; -[operation start]; -``` - -## Requirements - -AFNetworking 1.0 and higher requires either [iOS 5.0](http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html) and above, or [Mac OS 10.7](http://developer.apple.com/library/mac/#releasenotes/MacOSX/WhatsNewInOSX/Articles/MacOSX10_6.html#//apple_ref/doc/uid/TP40008898-SW7) ([64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)) and above. - -For compatibility with iOS 4.3, use the latest 0.10.x release. - -### ARC - -AFNetworking uses ARC as of its 1.0 release. - -If you are using AFNetworking 1.0 in your non-arc project, you will need to set a `-fobjc-arc` compiler flag on all of the AFNetworking source files. Conversely, if you are adding a pre-1.0 version of AFNetworking, you will need to set a `-fno-objc-arc` compiler flag. - -To set a compiler flag in Xcode, go to your active target and select the "Build Phases" tab. Now select all AFNetworking source files, press Enter, insert `-fobjc-arc` or `-fno-objc-arc` and then "Done" to enable or disable ARC for AFNetworking. - -## Unit Tests - -AFNetworking includes a suite of unit tests within the Tests subdirectory. In order to run the unit tests, you must install the testing dependencies via CocoaPods. To do so: - - $ gem install cocoapods # If necessary - $ cd Tests - $ pod install - -Once CocoaPods has finished the installation, you can execute the test suite via the 'iOS Tests' and 'OS X Tests' schemes within Xcode. - -### Test Logging - -By default, the unit tests do not emit any output during execution. For debugging purposes, it can be useful to enable logging of the requests and responses. Logging support is provided by the [AFHTTPRequestOperationLogger](https://github.com/AFNetworking/AFHTTPRequestOperationLogger) extension, which is installed via CocoaPods into the test targets. To enable logging, edit the test Scheme and add an environment variable named `AFTestsLoggingEnabled` with a value of `YES`. - -### Using xctool - -If you wish to execute the tests from the command line or within a continuous integration environment, you will need to install [xctool](https://github.com/facebook/xctool). The recommended installation method is [Homebrew](http://mxcl.github.io/homebrew/). - -To install the commandline testing support via Homebrew: - - $ brew update - $ brew install xctool --HEAD - -Once xctool is installed, you can execute the suite via `rake test`. - -## Credits - -AFNetworking was created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). - -AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). - -And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). - -## Contact - -Follow AFNetworking on Twitter ([@AFNetworking](https://twitter.com/AFNetworking)) - -### Creators - -[Mattt Thompson](http://github.com/mattt) -[@mattt](https://twitter.com/mattt) - -[Scott Raymond](http://github.com/sco) -[@sco](https://twitter.com/sco) - -## License - -AFNetworking is available under the MIT license. See the LICENSE file for more info. diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPClient.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPClient.h deleted file mode 120000 index a88168d71da2..000000000000 --- a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPClient.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFHTTPClient.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPRequestOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPRequestOperation.h deleted file mode 120000 index d51daed27c1c..000000000000 --- a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPRequestOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFHTTPRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFImageRequestOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFImageRequestOperation.h deleted file mode 120000 index f7c5e913d350..000000000000 --- a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFImageRequestOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFImageRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFJSONRequestOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFJSONRequestOperation.h deleted file mode 120000 index 4dd9622727ff..000000000000 --- a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFJSONRequestOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFJSONRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworkActivityIndicatorManager.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworkActivityIndicatorManager.h deleted file mode 120000 index a09102c76d08..000000000000 --- a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworkActivityIndicatorManager.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworking.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworking.h deleted file mode 120000 index 83dd518f7b2a..000000000000 --- a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworking.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFNetworking.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFPropertyListRequestOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFPropertyListRequestOperation.h deleted file mode 120000 index fb82b5c57062..000000000000 --- a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFPropertyListRequestOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFPropertyListRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFURLConnectionOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFURLConnectionOperation.h deleted file mode 120000 index 360459d4c03d..000000000000 --- a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFURLConnectionOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFURLConnectionOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFXMLRequestOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFXMLRequestOperation.h deleted file mode 120000 index c5c354bbcb28..000000000000 --- a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFXMLRequestOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFXMLRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/UIImageView+AFNetworking.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/UIImageView+AFNetworking.h deleted file mode 120000 index 7c7e6c38e965..000000000000 --- a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/UIImageView+AFNetworking.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/UIImageView+AFNetworking.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPClient.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPClient.h deleted file mode 120000 index a88168d71da2..000000000000 --- a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPClient.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFHTTPClient.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPRequestOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPRequestOperation.h deleted file mode 120000 index d51daed27c1c..000000000000 --- a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPRequestOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFHTTPRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFImageRequestOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFImageRequestOperation.h deleted file mode 120000 index f7c5e913d350..000000000000 --- a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFImageRequestOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFImageRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFJSONRequestOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFJSONRequestOperation.h deleted file mode 120000 index 4dd9622727ff..000000000000 --- a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFJSONRequestOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFJSONRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworkActivityIndicatorManager.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworkActivityIndicatorManager.h deleted file mode 120000 index a09102c76d08..000000000000 --- a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworkActivityIndicatorManager.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworking.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworking.h deleted file mode 120000 index 83dd518f7b2a..000000000000 --- a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworking.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFNetworking.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFPropertyListRequestOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFPropertyListRequestOperation.h deleted file mode 120000 index fb82b5c57062..000000000000 --- a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFPropertyListRequestOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFPropertyListRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFURLConnectionOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFURLConnectionOperation.h deleted file mode 120000 index 360459d4c03d..000000000000 --- a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFURLConnectionOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFURLConnectionOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFXMLRequestOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFXMLRequestOperation.h deleted file mode 120000 index c5c354bbcb28..000000000000 --- a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFXMLRequestOperation.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/AFXMLRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/UIImageView+AFNetworking.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/UIImageView+AFNetworking.h deleted file mode 120000 index 7c7e6c38e965..000000000000 --- a/samples/client/petstore/objc/Pods/Headers/AFNetworking/UIImageView+AFNetworking.h +++ /dev/null @@ -1 +0,0 @@ -../../AFNetworking/AFNetworking/UIImageView+AFNetworking.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Manifest.lock b/samples/client/petstore/objc/Pods/Manifest.lock deleted file mode 100644 index f52a69324dba..000000000000 --- a/samples/client/petstore/objc/Pods/Manifest.lock +++ /dev/null @@ -1,10 +0,0 @@ -PODS: - - AFNetworking (1.3.3) - -DEPENDENCIES: - - AFNetworking (~> 1.0) - -SPEC CHECKSUMS: - AFNetworking: 0700ec7a58c36ad217173e167f6e4df7270df66b - -COCOAPODS: 0.25.0 diff --git a/samples/client/petstore/objc/Pods/Pods-AFNetworking-Private.xcconfig b/samples/client/petstore/objc/Pods/Pods-AFNetworking-Private.xcconfig deleted file mode 100644 index af8cfd47a496..000000000000 --- a/samples/client/petstore/objc/Pods/Pods-AFNetworking-Private.xcconfig +++ /dev/null @@ -1,5 +0,0 @@ -#include "Pods-AFNetworking.xcconfig" -GCC_PREPROCESSOR_DEFINITIONS = COCOAPODS=1 -HEADER_SEARCH_PATHS = "${PODS_ROOT}/BuildHeaders" "${PODS_ROOT}/BuildHeaders/AFNetworking" "${PODS_ROOT}/Headers" "${PODS_ROOT}/Headers/AFNetworking" -OTHER_LDFLAGS = -ObjC ${PODS_AFNETWORKING_OTHER_LDFLAGS} -PODS_ROOT = ${SRCROOT} \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Pods-AFNetworking-dummy.m b/samples/client/petstore/objc/Pods/Pods-AFNetworking-dummy.m deleted file mode 100644 index c50a8c616899..000000000000 --- a/samples/client/petstore/objc/Pods/Pods-AFNetworking-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods_AFNetworking : NSObject -@end -@implementation PodsDummy_Pods_AFNetworking -@end diff --git a/samples/client/petstore/objc/Pods/Pods-AFNetworking-prefix.pch b/samples/client/petstore/objc/Pods/Pods-AFNetworking-prefix.pch deleted file mode 100644 index 133fd577e8e3..000000000000 --- a/samples/client/petstore/objc/Pods/Pods-AFNetworking-prefix.pch +++ /dev/null @@ -1,19 +0,0 @@ -#ifdef __OBJC__ -#import -#endif - -#import "Pods-environment.h" -#import - -#define _AFNETWORKING_PIN_SSL_CERTIFICATES_ - -#if __IPHONE_OS_VERSION_MIN_REQUIRED - #import - #import - #import -#else - #import - #import - #import -#endif - diff --git a/samples/client/petstore/objc/Pods/Pods-AFNetworking.xcconfig b/samples/client/petstore/objc/Pods/Pods-AFNetworking.xcconfig deleted file mode 100644 index 13e3dff03668..000000000000 --- a/samples/client/petstore/objc/Pods/Pods-AFNetworking.xcconfig +++ /dev/null @@ -1 +0,0 @@ -PODS_AFNETWORKING_OTHER_LDFLAGS = -framework CoreGraphics -framework MobileCoreServices -framework Security -framework SystemConfiguration \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Pods-acknowledgements.markdown b/samples/client/petstore/objc/Pods/Pods-acknowledgements.markdown deleted file mode 100644 index 0a417941f218..000000000000 --- a/samples/client/petstore/objc/Pods/Pods-acknowledgements.markdown +++ /dev/null @@ -1,26 +0,0 @@ -# Acknowledgements -This application makes use of the following third party libraries: - -## AFNetworking - -Copyright (c) 2011 Gowalla (http://gowalla.com/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -Generated by CocoaPods - http://cocoapods.org diff --git a/samples/client/petstore/objc/Pods/Pods-acknowledgements.plist b/samples/client/petstore/objc/Pods/Pods-acknowledgements.plist deleted file mode 100644 index 0c9d23f5fadf..000000000000 --- a/samples/client/petstore/objc/Pods/Pods-acknowledgements.plist +++ /dev/null @@ -1,56 +0,0 @@ - - - - - PreferenceSpecifiers - - - FooterText - This application makes use of the following third party libraries: - Title - Acknowledgements - Type - PSGroupSpecifier - - - FooterText - Copyright (c) 2011 Gowalla (http://gowalla.com/) - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - Title - AFNetworking - Type - PSGroupSpecifier - - - FooterText - Generated by CocoaPods - http://cocoapods.org - Title - - Type - PSGroupSpecifier - - - StringsTable - Acknowledgements - Title - Acknowledgements - - diff --git a/samples/client/petstore/objc/Pods/Pods-dummy.m b/samples/client/petstore/objc/Pods/Pods-dummy.m deleted file mode 100644 index ade64bd1a9b4..000000000000 --- a/samples/client/petstore/objc/Pods/Pods-dummy.m +++ /dev/null @@ -1,5 +0,0 @@ -#import -@interface PodsDummy_Pods : NSObject -@end -@implementation PodsDummy_Pods -@end diff --git a/samples/client/petstore/objc/Pods/Pods-environment.h b/samples/client/petstore/objc/Pods/Pods-environment.h deleted file mode 100644 index 17dfbefd8372..000000000000 --- a/samples/client/petstore/objc/Pods/Pods-environment.h +++ /dev/null @@ -1,14 +0,0 @@ - -// To check if a library is compiled with CocoaPods you -// can use the `COCOAPODS` macro definition which is -// defined in the xcconfigs so it is available in -// headers also when they are imported in the client -// project. - - -// AFNetworking -#define COCOAPODS_POD_AVAILABLE_AFNetworking -#define COCOAPODS_VERSION_MAJOR_AFNetworking 1 -#define COCOAPODS_VERSION_MINOR_AFNetworking 3 -#define COCOAPODS_VERSION_PATCH_AFNetworking 3 - diff --git a/samples/client/petstore/objc/Pods/Pods-resources.sh b/samples/client/petstore/objc/Pods/Pods-resources.sh deleted file mode 100755 index d6513b83d874..000000000000 --- a/samples/client/petstore/objc/Pods/Pods-resources.sh +++ /dev/null @@ -1,47 +0,0 @@ -#!/bin/sh -set -e - -RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt -> "$RESOURCES_TO_COPY" - -install_resource() -{ - case $1 in - *.storyboard) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc ${PODS_ROOT}/$1 --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" - ;; - *.xib) - echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib ${PODS_ROOT}/$1 --sdk ${SDKROOT}" - ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" - ;; - *.framework) - echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - echo "rsync -av ${PODS_ROOT}/$1 ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - rsync -av "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" - ;; - *.xcdatamodel) - echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1"`.mom\"" - xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodel`.mom" - ;; - *.xcdatamodeld) - echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd\"" - xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd" - ;; - /*) - echo "$1" - echo "$1" >> "$RESOURCES_TO_COPY" - ;; - *) - echo "${PODS_ROOT}/$1" - echo "${PODS_ROOT}/$1" >> "$RESOURCES_TO_COPY" - ;; - esac -} - -rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" -if [[ "${ACTION}" == "install" ]]; then - rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" -fi -rm -f "$RESOURCES_TO_COPY" diff --git a/samples/client/petstore/objc/Pods/Pods.xcconfig b/samples/client/petstore/objc/Pods/Pods.xcconfig deleted file mode 100644 index c06def566617..000000000000 --- a/samples/client/petstore/objc/Pods/Pods.xcconfig +++ /dev/null @@ -1,4 +0,0 @@ -GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 -HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers" "${PODS_ROOT}/Headers/AFNetworking" -OTHER_LDFLAGS = -ObjC -framework CoreGraphics -framework MobileCoreServices -framework Security -framework SystemConfiguration -PODS_ROOT = ${SRCROOT}/../Pods \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/objc/Pods/Pods.xcodeproj/project.pbxproj deleted file mode 100644 index 1a2a2a848a24..000000000000 --- a/samples/client/petstore/objc/Pods/Pods.xcodeproj/project.pbxproj +++ /dev/null @@ -1,1419 +0,0 @@ - - - - - archiveVersion - 1 - classes - - objectVersion - 46 - objects - - 08AD1E7714834BA097149FFC - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.objc - name - AFURLConnectionOperation.m - path - AFNetworking/AFURLConnectionOperation.m - sourceTree - <group> - - 0A30FD7007D548689A8CFA96 - - buildConfigurationList - D83638CD2B874305B4E2B366 - buildPhases - - CAF06F18CAB044D582844864 - EB343EA5DF6345D7867FC8B7 - - buildRules - - dependencies - - 36E14D068FBE423684F46265 - - isa - PBXNativeTarget - name - Pods - productName - Pods - productReference - 4C14728A19A84EAA9AFA4921 - productType - com.apple.product-type.library.static - - 117F23A7BDB2475BB504D0F5 - - fileRef - 4BF878DF59B546788943B1C4 - isa - PBXBuildFile - settings - - COMPILER_FLAGS - -fobjc-arc -DOS_OBJECT_USE_OBJC=0 - - - 13106AAC07724E9D97A8B49F - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - text.xcconfig - path - Pods-AFNetworking.xcconfig - sourceTree - <group> - - 17722A4C9883485BB1BF1C34 - - isa - PBXFileReference - lastKnownFileType - wrapper.framework - name - CoreGraphics.framework - path - System/Library/Frameworks/CoreGraphics.framework - sourceTree - SDKROOT - - 184B9675055042D798F70DD4 - - fileRef - 41C954074E9C4774989EE939 - isa - PBXBuildFile - - 1A32B73F523240569574D287 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.objc - name - AFHTTPRequestOperation.m - path - AFNetworking/AFHTTPRequestOperation.m - sourceTree - <group> - - 1C472D5A8E8A4F08954C4AA2 - - buildActionMask - 2147483647 - files - - 3BBDEC35F3194F569BC38755 - 4313834545D74DE3948659F0 - 7643E5EF1A9547E7876DE986 - 475DFF9ECD7746639003AD4A - F71E6F37CA9A4629AAC2CDCC - - isa - PBXFrameworksBuildPhase - runOnlyForDeploymentPostprocessing - 0 - - 1E15FB759FAE49F89C5CB65D - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - name - AFURLConnectionOperation.h - path - AFNetworking/AFURLConnectionOperation.h - sourceTree - <group> - - 1F5E1B3B5C2C40B8B5C0D3D1 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - path - Pods-AFNetworking-prefix.pch - sourceTree - <group> - - 2043689D5F07489597A49188 - - isa - PBXFileReference - lastKnownFileType - wrapper.framework - name - MobileCoreServices.framework - path - System/Library/Frameworks/MobileCoreServices.framework - sourceTree - SDKROOT - - 242B94135C604951BF12B255 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.objc - name - AFNetworkActivityIndicatorManager.m - path - AFNetworking/AFNetworkActivityIndicatorManager.m - sourceTree - <group> - - 258C9862D1A340E494399953 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - name - AFNetworkActivityIndicatorManager.h - path - AFNetworking/AFNetworkActivityIndicatorManager.h - sourceTree - <group> - - 2B63AA5CB8434020B521167B - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - text.plist.xml - path - Pods-acknowledgements.plist - sourceTree - <group> - - 2C21BED5C48B4FE187F91AAF - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - text - path - Pods-acknowledgements.markdown - sourceTree - <group> - - 2D0AD3E49325490CBCD844E7 - - attributes - - LastUpgradeCheck - 0500 - - buildConfigurationList - 9C1681924E934108AE569B3B - compatibilityVersion - Xcode 3.2 - developmentRegion - English - hasScannedForEncodings - 0 - isa - PBXProject - knownRegions - - en - - mainGroup - 40736C2ECA4D41A1B8D721AA - productRefGroup - 669C06BC945D42D2B942A283 - projectDirPath - - projectReferences - - projectRoot - - targets - - 0A30FD7007D548689A8CFA96 - ADDE8DBB9F9E475B90FBC797 - - - 2E34FB5F1E3748149252B6AD - - fileRef - CF4689A092504584B06A11F7 - isa - PBXBuildFile - - 2F2767F66C604065872045DE - - buildConfigurations - - 44F295FD071343108C2F4714 - 7351BEBB632E4B1380FD70CC - - defaultConfigurationIsVisible - 0 - defaultConfigurationName - Release - isa - XCConfigurationList - - 3396677D4F7D47ACAFB45EA3 - - children - - 17722A4C9883485BB1BF1C34 - 41C954074E9C4774989EE939 - 2043689D5F07489597A49188 - 6D512D4B085A466E829659CB - D69A248065874CCE8D755FFC - - isa - PBXGroup - name - Frameworks - sourceTree - <group> - - 363F02FE962C4D5084685024 - - fileRef - 928DF5ECB0344C82B94E8F18 - isa - PBXBuildFile - - 36675631701345F4AEAB7DBF - - children - - 928DF5ECB0344C82B94E8F18 - - isa - PBXGroup - name - Products - sourceTree - <group> - - 36E14D068FBE423684F46265 - - isa - PBXTargetDependency - target - ADDE8DBB9F9E475B90FBC797 - targetProxy - C9B8CD7C05314612A2434792 - - 37D3C638E91F452899FE87C7 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - text - name - Podfile - path - ../Podfile - sourceTree - SOURCE_ROOT - xcLanguageSpecificationIdentifier - xcode.lang.ruby - - 39B010F2F8A5405DB8788FA9 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.objc - name - AFJSONRequestOperation.m - path - AFNetworking/AFJSONRequestOperation.m - sourceTree - <group> - - 3BBDEC35F3194F569BC38755 - - fileRef - 17722A4C9883485BB1BF1C34 - isa - PBXBuildFile - - 40736C2ECA4D41A1B8D721AA - - children - - 3396677D4F7D47ACAFB45EA3 - C22DD5E647C44918AAD0EC67 - 669C06BC945D42D2B942A283 - F9B38E093C8243CBB847A0CE - 37D3C638E91F452899FE87C7 - - isa - PBXGroup - sourceTree - <group> - - 41C954074E9C4774989EE939 - - isa - PBXFileReference - lastKnownFileType - wrapper.framework - name - Foundation.framework - path - System/Library/Frameworks/Foundation.framework - sourceTree - SDKROOT - - 4313834545D74DE3948659F0 - - fileRef - 41C954074E9C4774989EE939 - isa - PBXBuildFile - - 44F295FD071343108C2F4714 - - baseConfigurationReference - E2A06AE6E23349F7834ED6E7 - buildSettings - - ALWAYS_SEARCH_USER_PATHS - NO - COPY_PHASE_STRIP - NO - DSTROOT - /tmp/xcodeproj.dst - GCC_C_LANGUAGE_STANDARD - gnu99 - GCC_DYNAMIC_NO_PIC - NO - GCC_OPTIMIZATION_LEVEL - 0 - GCC_PRECOMPILE_PREFIX_HEADER - YES - GCC_PREFIX_HEADER - Pods-AFNetworking-prefix.pch - GCC_PREPROCESSOR_DEFINITIONS - - DEBUG=1 - $(inherited) - - GCC_SYMBOLS_PRIVATE_EXTERN - NO - GCC_VERSION - com.apple.compilers.llvm.clang.1_0 - INSTALL_PATH - $(BUILT_PRODUCTS_DIR) - IPHONEOS_DEPLOYMENT_TARGET - 6.0 - OTHER_LDFLAGS - - PRODUCT_NAME - $(TARGET_NAME) - PUBLIC_HEADERS_FOLDER_PATH - $(TARGET_NAME) - SDKROOT - iphoneos - SKIP_INSTALL - YES - - isa - XCBuildConfiguration - name - Debug - - 4575990AE6344B769BEE7053 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - text.xcconfig - path - Pods.xcconfig - sourceTree - <group> - - 475DFF9ECD7746639003AD4A - - fileRef - 6D512D4B085A466E829659CB - isa - PBXBuildFile - - 4ADFF8D90E254C66B692F502 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - name - AFImageRequestOperation.h - path - AFNetworking/AFImageRequestOperation.h - sourceTree - <group> - - 4BF878DF59B546788943B1C4 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.objc - name - AFPropertyListRequestOperation.m - path - AFNetworking/AFPropertyListRequestOperation.m - sourceTree - <group> - - 4C14728A19A84EAA9AFA4921 - - explicitFileType - archive.ar - includeInIndex - 0 - isa - PBXFileReference - path - libPods.a - sourceTree - BUILT_PRODUCTS_DIR - - 4C2A6ED1A9944D5DA6403F09 - - fileRef - E2E82489B82D4CC180AA87F7 - isa - PBXBuildFile - - 5125B97E5E154A638B6A2552 - - fileRef - D7AB04599CF5422B80CC2E77 - isa - PBXBuildFile - settings - - COMPILER_FLAGS - -fobjc-arc -DOS_OBJECT_USE_OBJC=0 - - - 520A1437FB9D4C82B7F0BFE8 - - children - - 53995F8949DE49F9935BF848 - 9450661AED894042BEE72962 - 2C21BED5C48B4FE187F91AAF - 2B63AA5CB8434020B521167B - 732EB3FD102147BAB5999C96 - 4575990AE6344B769BEE7053 - - isa - PBXGroup - name - Pods - sourceTree - <group> - - 53995F8949DE49F9935BF848 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - path - Pods-environment.h - sourceTree - <group> - - 553E8882F7CB4F5FAE46BCBE - - fileRef - 39B010F2F8A5405DB8788FA9 - isa - PBXBuildFile - settings - - COMPILER_FLAGS - -fobjc-arc -DOS_OBJECT_USE_OBJC=0 - - - 5AE42FF5353741FF83A9C702 - - fileRef - C74FC79D37F443A7A9A6F8EC - isa - PBXBuildFile - - 5E9724BBAAB74732BA412FFA - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - name - AFNetworking.h - path - AFNetworking/AFNetworking.h - sourceTree - <group> - - 5FB77F13243D47D8B82A47A7 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.objc - name - AFHTTPClient.m - path - AFNetworking/AFHTTPClient.m - sourceTree - <group> - - 669C06BC945D42D2B942A283 - - children - - 4C14728A19A84EAA9AFA4921 - - isa - PBXGroup - name - Products - sourceTree - <group> - - 6D512D4B085A466E829659CB - - isa - PBXFileReference - lastKnownFileType - wrapper.framework - name - Security.framework - path - System/Library/Frameworks/Security.framework - sourceTree - SDKROOT - - 6EBE2C14A7FC4379A222F0B0 - - fileRef - F764EA36EAEF4A908B23E10A - isa - PBXBuildFile - - 732EB3FD102147BAB5999C96 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - text.script.sh - path - Pods-resources.sh - sourceTree - <group> - - 7351BEBB632E4B1380FD70CC - - baseConfigurationReference - E2A06AE6E23349F7834ED6E7 - buildSettings - - ALWAYS_SEARCH_USER_PATHS - NO - COPY_PHASE_STRIP - YES - DSTROOT - /tmp/xcodeproj.dst - GCC_C_LANGUAGE_STANDARD - gnu99 - GCC_PRECOMPILE_PREFIX_HEADER - YES - GCC_PREFIX_HEADER - Pods-AFNetworking-prefix.pch - GCC_VERSION - com.apple.compilers.llvm.clang.1_0 - INSTALL_PATH - $(BUILT_PRODUCTS_DIR) - IPHONEOS_DEPLOYMENT_TARGET - 6.0 - OTHER_CFLAGS - - -DNS_BLOCK_ASSERTIONS=1 - $(inherited) - - OTHER_CPLUSPLUSFLAGS - - -DNS_BLOCK_ASSERTIONS=1 - $(inherited) - - OTHER_LDFLAGS - - PRODUCT_NAME - $(TARGET_NAME) - PUBLIC_HEADERS_FOLDER_PATH - $(TARGET_NAME) - SDKROOT - iphoneos - SKIP_INSTALL - YES - VALIDATE_PRODUCT - YES - - isa - XCBuildConfiguration - name - Release - - 75F8D108CCAC46C8B9525E88 - - fileRef - A2C8A7C8FD9947F28CB5D942 - isa - PBXBuildFile - - 7643E5EF1A9547E7876DE986 - - fileRef - 2043689D5F07489597A49188 - isa - PBXBuildFile - - 7A30533345E2474FB6048F84 - - buildSettings - - IPHONEOS_DEPLOYMENT_TARGET - 6.0 - ONLY_ACTIVE_ARCH - YES - STRIP_INSTALLED_PRODUCT - NO - - isa - XCBuildConfiguration - name - Debug - - 7EA9C38B88DC4FA69AA264D3 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.objc - name - UIImageView+AFNetworking.m - path - AFNetworking/UIImageView+AFNetworking.m - sourceTree - <group> - - 928DF5ECB0344C82B94E8F18 - - explicitFileType - archive.ar - includeInIndex - 0 - isa - PBXFileReference - path - libPods-AFNetworking.a - sourceTree - BUILT_PRODUCTS_DIR - - 9385A49D20E44B1A9EC05A78 - - fileRef - 242B94135C604951BF12B255 - isa - PBXBuildFile - settings - - COMPILER_FLAGS - -fobjc-arc -DOS_OBJECT_USE_OBJC=0 - - - 9450661AED894042BEE72962 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.objc - path - Pods-dummy.m - sourceTree - <group> - - 95229B59E0E7458CA7C4F379 - - children - - FC62B60F07924F33B461AFCC - A2C8A7C8FD9947F28CB5D942 - 4ADFF8D90E254C66B692F502 - CEBCBBA20E674D4DB370177B - 258C9862D1A340E494399953 - 5E9724BBAAB74732BA412FFA - CF4689A092504584B06A11F7 - 1E15FB759FAE49F89C5CB65D - F764EA36EAEF4A908B23E10A - C74FC79D37F443A7A9A6F8EC - 5FB77F13243D47D8B82A47A7 - 1A32B73F523240569574D287 - D7AB04599CF5422B80CC2E77 - 39B010F2F8A5405DB8788FA9 - 242B94135C604951BF12B255 - 4BF878DF59B546788943B1C4 - 08AD1E7714834BA097149FFC - FE5CE872AE5949968454923E - 7EA9C38B88DC4FA69AA264D3 - - isa - PBXGroup - name - Source Files - sourceTree - <group> - - 9570A7F385264CD5BBFCB900 - - buildActionMask - 2147483647 - files - - FE725C0AF8A24B2FBE3B510E - 75F8D108CCAC46C8B9525E88 - F72BC8DDF894435AB6A2594D - AADF91BF4793404E94659CE8 - B872082AE7E8478693E0925F - E9273D887ADF4EFDAB3887D8 - 2E34FB5F1E3748149252B6AD - E53598F917C7429A8ABEA931 - 6EBE2C14A7FC4379A222F0B0 - 5AE42FF5353741FF83A9C702 - - isa - PBXHeadersBuildPhase - runOnlyForDeploymentPostprocessing - 0 - - 9669D77043994416864E2267 - - fileRef - 1A32B73F523240569574D287 - isa - PBXBuildFile - settings - - COMPILER_FLAGS - -fobjc-arc -DOS_OBJECT_USE_OBJC=0 - - - 9C1681924E934108AE569B3B - - buildConfigurations - - 7A30533345E2474FB6048F84 - FDD7D8C57FA6489A895DCBF6 - - defaultConfigurationIsVisible - 0 - defaultConfigurationName - Release - isa - XCConfigurationList - - A2C8A7C8FD9947F28CB5D942 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - name - AFHTTPRequestOperation.h - path - AFNetworking/AFHTTPRequestOperation.h - sourceTree - <group> - - A2D09F3EF81D4BECB3B8C3AA - - fileRef - 9450661AED894042BEE72962 - isa - PBXBuildFile - - AADF91BF4793404E94659CE8 - - fileRef - CEBCBBA20E674D4DB370177B - isa - PBXBuildFile - - ADDE8DBB9F9E475B90FBC797 - - buildConfigurationList - 2F2767F66C604065872045DE - buildPhases - - D83F3CF6DA96433B972AA62D - 1C472D5A8E8A4F08954C4AA2 - 9570A7F385264CD5BBFCB900 - - buildRules - - dependencies - - isa - PBXNativeTarget - name - Pods-AFNetworking - productName - Pods-AFNetworking - productReference - 928DF5ECB0344C82B94E8F18 - productType - com.apple.product-type.library.static - - B872082AE7E8478693E0925F - - fileRef - 258C9862D1A340E494399953 - isa - PBXBuildFile - - C22DD5E647C44918AAD0EC67 - - children - - F603B69EEFF14170BE6FA566 - - isa - PBXGroup - name - Pods - sourceTree - <group> - - C74FC79D37F443A7A9A6F8EC - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - name - UIImageView+AFNetworking.h - path - AFNetworking/UIImageView+AFNetworking.h - sourceTree - <group> - - C9B8CD7C05314612A2434792 - - containerPortal - 2D0AD3E49325490CBCD844E7 - isa - PBXContainerItemProxy - proxyType - 1 - remoteGlobalIDString - ADDE8DBB9F9E475B90FBC797 - remoteInfo - Pods-AFNetworking - - CAC922C847194DC5A4F3E024 - - fileRef - 7EA9C38B88DC4FA69AA264D3 - isa - PBXBuildFile - settings - - COMPILER_FLAGS - -fobjc-arc -DOS_OBJECT_USE_OBJC=0 - - - CAF06F18CAB044D582844864 - - buildActionMask - 2147483647 - files - - A2D09F3EF81D4BECB3B8C3AA - - isa - PBXSourcesBuildPhase - runOnlyForDeploymentPostprocessing - 0 - - CEBCBBA20E674D4DB370177B - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - name - AFJSONRequestOperation.h - path - AFNetworking/AFJSONRequestOperation.h - sourceTree - <group> - - CF4689A092504584B06A11F7 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - name - AFPropertyListRequestOperation.h - path - AFNetworking/AFPropertyListRequestOperation.h - sourceTree - <group> - - D191D66EE1F84CAA93702591 - - baseConfigurationReference - 4575990AE6344B769BEE7053 - buildSettings - - ALWAYS_SEARCH_USER_PATHS - NO - COPY_PHASE_STRIP - YES - DSTROOT - /tmp/xcodeproj.dst - GCC_C_LANGUAGE_STANDARD - gnu99 - GCC_PRECOMPILE_PREFIX_HEADER - YES - GCC_VERSION - com.apple.compilers.llvm.clang.1_0 - INSTALL_PATH - $(BUILT_PRODUCTS_DIR) - IPHONEOS_DEPLOYMENT_TARGET - 6.0 - OTHER_CFLAGS - - -DNS_BLOCK_ASSERTIONS=1 - $(inherited) - - OTHER_CPLUSPLUSFLAGS - - -DNS_BLOCK_ASSERTIONS=1 - $(inherited) - - OTHER_LDFLAGS - - PRODUCT_NAME - $(TARGET_NAME) - PUBLIC_HEADERS_FOLDER_PATH - $(TARGET_NAME) - SDKROOT - iphoneos - SKIP_INSTALL - YES - VALIDATE_PRODUCT - YES - - isa - XCBuildConfiguration - name - Release - - D1ED042E2078427081658CEA - - fileRef - FE5CE872AE5949968454923E - isa - PBXBuildFile - settings - - COMPILER_FLAGS - -fobjc-arc -DOS_OBJECT_USE_OBJC=0 - - - D66C6AC4368F47599EC35DE2 - - fileRef - 08AD1E7714834BA097149FFC - isa - PBXBuildFile - settings - - COMPILER_FLAGS - -fobjc-arc -DOS_OBJECT_USE_OBJC=0 - - - D69A248065874CCE8D755FFC - - isa - PBXFileReference - lastKnownFileType - wrapper.framework - name - SystemConfiguration.framework - path - System/Library/Frameworks/SystemConfiguration.framework - sourceTree - SDKROOT - - D7AB04599CF5422B80CC2E77 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.objc - name - AFImageRequestOperation.m - path - AFNetworking/AFImageRequestOperation.m - sourceTree - <group> - - D83638CD2B874305B4E2B366 - - buildConfigurations - - D9038D6BC9504E39A8279073 - D191D66EE1F84CAA93702591 - - defaultConfigurationIsVisible - 0 - defaultConfigurationName - Release - isa - XCConfigurationList - - D83F3CF6DA96433B972AA62D - - buildActionMask - 2147483647 - files - - DB224BFAF42D46A692A571E5 - 9669D77043994416864E2267 - 5125B97E5E154A638B6A2552 - 553E8882F7CB4F5FAE46BCBE - 9385A49D20E44B1A9EC05A78 - 117F23A7BDB2475BB504D0F5 - D66C6AC4368F47599EC35DE2 - D1ED042E2078427081658CEA - 4C2A6ED1A9944D5DA6403F09 - CAC922C847194DC5A4F3E024 - - isa - PBXSourcesBuildPhase - runOnlyForDeploymentPostprocessing - 0 - - D9038D6BC9504E39A8279073 - - baseConfigurationReference - 4575990AE6344B769BEE7053 - buildSettings - - ALWAYS_SEARCH_USER_PATHS - NO - COPY_PHASE_STRIP - NO - DSTROOT - /tmp/xcodeproj.dst - GCC_C_LANGUAGE_STANDARD - gnu99 - GCC_DYNAMIC_NO_PIC - NO - GCC_OPTIMIZATION_LEVEL - 0 - GCC_PRECOMPILE_PREFIX_HEADER - YES - GCC_PREPROCESSOR_DEFINITIONS - - DEBUG=1 - $(inherited) - - GCC_SYMBOLS_PRIVATE_EXTERN - NO - GCC_VERSION - com.apple.compilers.llvm.clang.1_0 - INSTALL_PATH - $(BUILT_PRODUCTS_DIR) - IPHONEOS_DEPLOYMENT_TARGET - 6.0 - OTHER_LDFLAGS - - PRODUCT_NAME - $(TARGET_NAME) - PUBLIC_HEADERS_FOLDER_PATH - $(TARGET_NAME) - SDKROOT - iphoneos - SKIP_INSTALL - YES - - isa - XCBuildConfiguration - name - Debug - - DB224BFAF42D46A692A571E5 - - fileRef - 5FB77F13243D47D8B82A47A7 - isa - PBXBuildFile - settings - - COMPILER_FLAGS - -fobjc-arc -DOS_OBJECT_USE_OBJC=0 - - - DC92641749314F3CB6204D69 - - children - - E2E82489B82D4CC180AA87F7 - 1F5E1B3B5C2C40B8B5C0D3D1 - 13106AAC07724E9D97A8B49F - E2A06AE6E23349F7834ED6E7 - - isa - PBXGroup - name - Support Files - sourceTree - SOURCE_ROOT - - E2A06AE6E23349F7834ED6E7 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - text.xcconfig - path - Pods-AFNetworking-Private.xcconfig - sourceTree - <group> - - E2E82489B82D4CC180AA87F7 - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.objc - path - Pods-AFNetworking-dummy.m - sourceTree - <group> - - E53598F917C7429A8ABEA931 - - fileRef - 1E15FB759FAE49F89C5CB65D - isa - PBXBuildFile - - E9273D887ADF4EFDAB3887D8 - - fileRef - 5E9724BBAAB74732BA412FFA - isa - PBXBuildFile - - EB343EA5DF6345D7867FC8B7 - - buildActionMask - 2147483647 - files - - 184B9675055042D798F70DD4 - 363F02FE962C4D5084685024 - - isa - PBXFrameworksBuildPhase - runOnlyForDeploymentPostprocessing - 0 - - F603B69EEFF14170BE6FA566 - - children - - 36675631701345F4AEAB7DBF - 95229B59E0E7458CA7C4F379 - DC92641749314F3CB6204D69 - - isa - PBXGroup - name - AFNetworking - path - AFNetworking - sourceTree - <group> - - F71E6F37CA9A4629AAC2CDCC - - fileRef - D69A248065874CCE8D755FFC - isa - PBXBuildFile - - F72BC8DDF894435AB6A2594D - - fileRef - 4ADFF8D90E254C66B692F502 - isa - PBXBuildFile - - F764EA36EAEF4A908B23E10A - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - name - AFXMLRequestOperation.h - path - AFNetworking/AFXMLRequestOperation.h - sourceTree - <group> - - F9B38E093C8243CBB847A0CE - - children - - 520A1437FB9D4C82B7F0BFE8 - - isa - PBXGroup - name - Targets Support Files - sourceTree - <group> - - FC62B60F07924F33B461AFCC - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.h - name - AFHTTPClient.h - path - AFNetworking/AFHTTPClient.h - sourceTree - <group> - - FDD7D8C57FA6489A895DCBF6 - - buildSettings - - IPHONEOS_DEPLOYMENT_TARGET - 6.0 - STRIP_INSTALLED_PRODUCT - NO - - isa - XCBuildConfiguration - name - Release - - FE5CE872AE5949968454923E - - includeInIndex - 1 - isa - PBXFileReference - lastKnownFileType - sourcecode.c.objc - name - AFXMLRequestOperation.m - path - AFNetworking/AFXMLRequestOperation.m - sourceTree - <group> - - FE725C0AF8A24B2FBE3B510E - - fileRef - FC62B60F07924F33B461AFCC - isa - PBXBuildFile - - - rootObject - 2D0AD3E49325490CBCD844E7 - - diff --git a/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods-AFNetworking.xcscheme b/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods-AFNetworking.xcscheme deleted file mode 100644 index 04cc49a93cc7..000000000000 --- a/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods-AFNetworking.xcscheme +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods.xcscheme b/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods.xcscheme deleted file mode 100644 index 802886807fbf..000000000000 --- a/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods.xcscheme +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/xcschememanagement.plist b/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/xcschememanagement.plist deleted file mode 100644 index 6b9c43c11f05..000000000000 --- a/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/xcschememanagement.plist +++ /dev/null @@ -1,52 +0,0 @@ - - - - - SchemeUserState - - Pods-AFNetworking.xcscheme - - orderHint - 3 - - Pods.xcscheme - - orderHint - 2 - - - SuppressBuildableAutocreation - - 0A30FD7007D548689A8CFA96 - - primary - - - 7934141CDD144029B68BBCCA - - primary - - - 9DF4A09206094F4EB8B7F841 - - primary - - - ADDE8DBB9F9E475B90FBC797 - - primary - - - B044D459E2CB44439DF863F1 - - primary - - - FEFF1D6E156342BEA878F340 - - primary - - - - - diff --git a/samples/client/petstore/objc/client/SWGApiClient.h b/samples/client/petstore/objc/client/SWGApiClient.h index aab60cd05958..300cd8597782 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.h +++ b/samples/client/petstore/objc/client/SWGApiClient.h @@ -1,7 +1,15 @@ #import -#import "AFHTTPClient.h" +#import "AFHTTPRequestOperationManager.h" -@interface SWGApiClient : AFHTTPClient +/** + * 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 : AFHTTPRequestOperationManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @property(nonatomic, assign) NSTimeInterval timeoutInterval; diff --git a/samples/client/petstore/objc/client/SWGApiClient.m b/samples/client/petstore/objc/client/SWGApiClient.m index 1c48412bc5aa..ff454970cf05 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.m +++ b/samples/client/petstore/objc/client/SWGApiClient.m @@ -1,18 +1,18 @@ #import "SWGApiClient.h" #import "SWGFile.h" -#import "AFJSONRequestOperation.h" - @implementation SWGApiClient +NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject"; + static long requestId = 0; -static bool offlineState = true; +static bool offlineState = false; static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; static NSOperationQueue* sharedQueue; static void (^reachabilityChangeBlock)(int); -static bool loggingEnabled = false; +static bool loggingEnabled = true; +(void)setLoggingEnabled:(bool) state { loggingEnabled = state; @@ -26,8 +26,8 @@ static bool loggingEnabled = false; cacheEnabled = enabled; } -+(void)configureCacheWithMemoryAndDiskCapacity:(unsigned long) memorySize - diskSize:(unsigned long) diskSize { ++(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize + diskSize: (unsigned long) diskSize { NSAssert(memorySize > 0, @"invalid in-memory cache size"); NSAssert(diskSize >= 0, @"invalid disk cache size"); @@ -68,8 +68,6 @@ static bool loggingEnabled = false; SWGApiClient * client = [_pool objectForKey:baseUrl]; if (client == nil) { client = [[SWGApiClient alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]]; - [client registerHTTPOperationClass:[AFJSONRequestOperation class]]; - client.parameterEncoding = AFJSONParameterEncoding; [_pool setValue:client forKey:baseUrl ]; if(loggingEnabled) NSLog(@"new client for path %@", baseUrl); @@ -82,7 +80,7 @@ static bool loggingEnabled = false; -(void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { - [self setDefaultHeader:forKey value:value]; + [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; } +(unsigned long)requestQueueSize { @@ -142,6 +140,8 @@ static bool loggingEnabled = false; -(id)initWithBaseURL:(NSURL *)url { self = [super initWithBaseURL:url]; + self.requestSerializer = [AFJSONRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; if (!self) return nil; return self; @@ -160,7 +160,7 @@ static bool loggingEnabled = false; } +(void) configureCacheReachibilityForHost:(NSString*)host { - [[SWGApiClient sharedClientFromPool:host ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + [[SWGApiClient sharedClientFromPool:host].reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { reachabilityStatus = status; switch (status) { case AFNetworkReachabilityStatusUnknown: @@ -194,6 +194,7 @@ static bool loggingEnabled = false; reachabilityChangeBlock(status); } }]; + [[SWGApiClient sharedClientFromPool:host].reachabilityManager startMonitoring]; } -(NSString*) pathWithQueryParamsToString:(NSString*) path @@ -233,35 +234,60 @@ static bool loggingEnabled = false; NSLog(@"request: %@ response: %@ ", [self descriptionForRequest:request], data ); } - --(NSNumber*) dictionary:(NSString*) path - method:(NSString*) method - queryParams:(NSDictionary*) queryParams - body:(id) body - headerParams:(NSDictionary*) headerParams - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock { +-(NSNumber*) dictionary: (NSString*) path + method: (NSString*) method + queryParams: (NSDictionary*) queryParams + body: (id) body + headerParams: (NSDictionary*) headerParams + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock { NSMutableURLRequest * request = nil; - - if ([body isKindOfClass:[SWGFile class]]){ - SWGFile * file = (SWGFile*) body; + if (body != nil && [body isKindOfClass:[NSArray class]]){ + SWGFile * file; + NSMutableDictionary * params = [[NSMutableDictionary alloc] init]; + for(id obj in body) { + if([obj isKindOfClass:[SWGFile class]]) { + file = (SWGFile*) obj; + requestContentType = @"multipart/form-data"; + } + else if([obj isKindOfClass:[NSDictionary class]]) { + for(NSString * key in obj) { + params[key] = obj[key]; + } + } + } + NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString]; - request = [self multipartFormRequestWithMethod:@"POST" - path:path - parameters:nil - constructingBodyWithBlock: ^(id formData) { - [formData appendPartWithFileData:[file data] - name:@"image" - fileName:[file name] - mimeType:[file mimeType]]; - }]; + if(file != nil) { + request = [self.requestSerializer multipartFormRequestWithMethod: @"POST" + URLString: urlString + parameters: nil + constructingBodyWithBlock: ^(id formData) { + + for(NSString * key in params) { + NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding]; + [formData appendPartWithFormData: data name: key]; + } + + [formData appendPartWithFileData: [file data] + name: [file paramName] + fileName: [file name] + mimeType: [file mimeType]]; + + } + error:nil]; + } } else { - request = [self requestWithMethod:method - path:[self pathWithQueryParamsToString:path queryParams:queryParams] - parameters:body]; + NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; + NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:body + error:nil]; } BOOL hasHeaderParams = false; if(headerParams != nil && [headerParams count] > 0) @@ -279,9 +305,11 @@ static bool loggingEnabled = false; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } + AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer]; + if(body != nil) { if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){ - [request setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; + [requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; } else if ([body isKindOfClass:[SWGFile class]]) {} else { @@ -293,7 +321,7 @@ static bool loggingEnabled = false; [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; } } - [request setValue:[headerParams valueForKey:responseContentType] forHTTPHeaderField:@"Accept"]; + [requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; // Always disable cookies! [request setHTTPShouldHandleCookies:NO]; @@ -304,60 +332,88 @@ static bool loggingEnabled = false; } NSNumber* requestId = [SWGApiClient queueRequest]; - AFJSONRequestOperation *op = - [AFJSONRequestOperation - JSONRequestOperationWithRequest:request - success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { + AFHTTPRequestOperation *op = + [self HTTPRequestOperationWithRequest:request + success:^(AFHTTPRequestOperation *operation, id JSON) { if([self executeRequestWithId:requestId]) { if(self.logServerResponses) [self logResponse:JSON forRequest:request error:nil]; completionBlock(JSON, nil); } - } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) { + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if([self executeRequestWithId:requestId]) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if(operation.responseObject) { + // Add in the (parsed) response body. + userInfo[SWGResponseObjectErrorKey] = operation.responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + if(self.logServerResponses) - [self logResponse:nil forRequest:request error:error]; - completionBlock(nil, error); + [self logResponse:nil forRequest:request error:augmentedError]; + completionBlock(nil, augmentedError); } } ]; - [self enqueueHTTPRequestOperation:op]; + [self.operationQueue addOperation:op]; return requestId; } --(NSNumber*) stringWithCompletionBlock:(NSString*) path - method:(NSString*) method - queryParams:(NSDictionary*) queryParams - body:(id) body - headerParams:(NSDictionary*) headerParams - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - completionBlock:(void (^)(NSString*, NSError *))completionBlock { - AFHTTPClient *client = self; - client.parameterEncoding = AFJSONParameterEncoding; - +-(NSNumber*) stringWithCompletionBlock: (NSString*) path + method: (NSString*) method + queryParams: (NSDictionary*) queryParams + body: (id) body + headerParams: (NSDictionary*) headerParams + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + completionBlock: (void (^)(NSString*, NSError *))completionBlock { NSMutableURLRequest * request = nil; - - if ([body isKindOfClass:[SWGFile class]]){ - SWGFile * file = (SWGFile*) body; + if (body != nil && [body isKindOfClass:[NSArray class]]){ + SWGFile * file; + NSMutableDictionary * params = [[NSMutableDictionary alloc] init]; + for(id obj in body) { + if([obj isKindOfClass:[SWGFile class]]) { + file = (SWGFile*) obj; + requestContentType = @"multipart/form-data"; + } + else if([obj isKindOfClass:[NSDictionary class]]) { + for(NSString * key in obj) { + params[key] = obj[key]; + } + } + } + NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString]; - request = [self multipartFormRequestWithMethod:@"POST" - path:path - parameters:nil - constructingBodyWithBlock: ^(id formData) { - [formData appendPartWithFileData:[file data] - name:@"image" - fileName:[file name] - mimeType:[file mimeType]]; - }]; + if(file != nil) { + request = [self.requestSerializer multipartFormRequestWithMethod: @"POST" + URLString: urlString + parameters: nil + constructingBodyWithBlock: ^(id formData) { + + for(NSString * key in params) { + NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding]; + [formData appendPartWithFormData: data name: key]; + } + + [formData appendPartWithFileData: [file data] + name: [file paramName] + fileName: [file name] + mimeType: [file mimeType]]; + + } + error:nil]; + } } else { - request = [self requestWithMethod:method - path:[self pathWithQueryParamsToString:path queryParams:queryParams] - parameters:body]; + NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; + NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + + request = [self.requestSerializer requestWithMethod: method + URLString: urlString + parameters: body + error: nil]; } - BOOL hasHeaderParams = false; if(headerParams != nil && [headerParams count] > 0) hasHeaderParams = true; @@ -374,9 +430,12 @@ static bool loggingEnabled = false; [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } + + AFJSONRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer]; + if(body != nil) { - if([body isKindOfClass:[NSDictionary class]]){ - [request setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; + if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){ + [requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; } else if ([body isKindOfClass:[SWGFile class]]){} else { @@ -388,17 +447,16 @@ static bool loggingEnabled = false; [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; } } - [request setValue:[headerParams valueForKey:responseContentType] forHTTPHeaderField:@"Accept"]; + [requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + // Always disable cookies! [request setHTTPShouldHandleCookies:NO]; NSNumber* requestId = [SWGApiClient queueRequest]; - AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request]; - [op setCompletionBlockWithSuccess: - ^(AFHTTPRequestOperation *resp, - id responseObject) { - NSString *response = [resp responseString]; + AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request + success:^(AFHTTPRequestOperation *operation, id responseObject) { + NSString *response = [operation responseString]; if([self executeRequestWithId:requestId]) { if(self.logServerResponses) [self logResponse:responseObject forRequest:request error:nil]; @@ -406,14 +464,21 @@ static bool loggingEnabled = false; } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { if([self executeRequestWithId:requestId]) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if(operation.responseObject) { + // Add in the (parsed) response body. + userInfo[SWGResponseObjectErrorKey] = operation.responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + if(self.logServerResponses) - [self logResponse:nil forRequest:request error:error]; - completionBlock(nil, error); + [self logResponse:nil forRequest:request error:augmentedError]; + completionBlock(nil, augmentedError); } }]; - [self enqueueHTTPRequestOperation:op]; + [self.operationQueue addOperation:op]; return requestId; } -@end +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/SWGApiResponse.h b/samples/client/petstore/objc/client/SWGApiResponse.h new file mode 100644 index 000000000000..2021a408f03e --- /dev/null +++ b/samples/client/petstore/objc/client/SWGApiResponse.h @@ -0,0 +1,18 @@ +#import +#import "SWGObject.h" + + +@interface SWGApiResponse : SWGObject + +@property(nonatomic) NSNumber* code; +@property(nonatomic) NSString* type; +@property(nonatomic) NSString* message; +- (id) code: (NSNumber*) code + type: (NSString*) type + message: (NSString*) message; + + +- (id) initWithValues: (NSDictionary*)dict; +- (NSDictionary*) asDictionary; + +@end diff --git a/samples/client/petstore/objc/client/SWGApiResponse.m b/samples/client/petstore/objc/client/SWGApiResponse.m new file mode 100644 index 000000000000..b6391774790a --- /dev/null +++ b/samples/client/petstore/objc/client/SWGApiResponse.m @@ -0,0 +1,54 @@ +#import "SWGDate.h" +#import "SWGApiResponse.h" + +@implementation SWGApiResponse + +-(id)code: (NSNumber*) code + type: (NSString*) type + message: (NSString*) message + +{ + _code = code; + _type = type; + _message = message; + + + return self; +} + +-(id) initWithValues:(NSDictionary*)dict +{ + self = [super init]; + if(self) { + _code = dict[@"code"]; + + _type = dict[@"type"]; + + _message = dict[@"message"]; + + + } + return self; +} + +-(NSDictionary*) asDictionary { + NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; + + + if(_code != nil) dict[@"code"] = _code ; + + + + if(_type != nil) dict[@"type"] = _type ; + + + + if(_message != nil) dict[@"message"] = _message ; + + + + NSDictionary* output = [dict copy]; + return output; +} + +@end diff --git a/samples/client/petstore/objc/client/SWGCategory.h b/samples/client/petstore/objc/client/SWGCategory.h index 7443279dc278..35c271051729 100644 --- a/samples/client/petstore/objc/client/SWGCategory.h +++ b/samples/client/petstore/objc/client/SWGCategory.h @@ -5,15 +5,12 @@ @interface SWGCategory : SWGObject @property(nonatomic) NSNumber* _id; - @property(nonatomic) NSString* name; - -- (id) _id: (NSNumber*) _id - name: (NSString*) name; +- (id) _id: (NSNumber*) _id + name: (NSString*) name; + - (id) initWithValues: (NSDictionary*)dict; - (NSDictionary*) asDictionary; - @end - diff --git a/samples/client/petstore/objc/client/SWGCategory.m b/samples/client/petstore/objc/client/SWGCategory.m index 4058217c9e11..882d8a34c597 100644 --- a/samples/client/petstore/objc/client/SWGCategory.m +++ b/samples/client/petstore/objc/client/SWGCategory.m @@ -5,31 +5,42 @@ -(id)_id: (NSNumber*) _id name: (NSString*) name + { - __id = _id; - _name = name; - return self; + __id = _id; + _name = name; + + + return self; } -(id) initWithValues:(NSDictionary*)dict { self = [super init]; if(self) { - __id = dict[@"id"]; - _name = dict[@"name"]; + __id = dict[@"id"]; + + _name = dict[@"name"]; + - } return self; } -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; - if(__id != nil) dict[@"id"] = __id ; - if(_name != nil) dict[@"name"] = _name ; - NSDictionary* output = [dict copy]; + + + if(__id != nil) dict[@"id"] = __id ; + + + + if(_name != nil) dict[@"name"] = _name ; + + + + NSDictionary* output = [dict copy]; return output; } @end - diff --git a/samples/client/petstore/objc/client/SWGFile.h b/samples/client/petstore/objc/client/SWGFile.h index fe6e81c289d2..fd87e13bacec 100644 --- a/samples/client/petstore/objc/client/SWGFile.h +++ b/samples/client/petstore/objc/client/SWGFile.h @@ -5,9 +5,10 @@ @property(nonatomic, readonly) NSString* name; @property(nonatomic, readonly) NSString* mimeType; @property(nonatomic, readonly) NSData* data; +@property(nonatomic) NSString* paramName; - (id) initWithNameData: (NSString*) filename mimeType: (NSString*) mimeType data: (NSData*) data; - @end \ No newline at end of file +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/SWGOrder.h b/samples/client/petstore/objc/client/SWGOrder.h index c1486966e244..feb85e9c54e4 100644 --- a/samples/client/petstore/objc/client/SWGOrder.h +++ b/samples/client/petstore/objc/client/SWGOrder.h @@ -6,24 +6,20 @@ @interface SWGOrder : SWGObject @property(nonatomic) NSNumber* _id; - @property(nonatomic) NSNumber* petId; - @property(nonatomic) NSNumber* quantity; - -@property(nonatomic) NSString* status; /* Order Status [optional]*/ - @property(nonatomic) SWGDate* shipDate; - -- (id) _id: (NSNumber*) _id - petId: (NSNumber*) petId - quantity: (NSNumber*) quantity - status: (NSString*) status - shipDate: (SWGDate*) shipDate; +@property(nonatomic) NSString* status; /* Order Status */ +@property(nonatomic) NSNumber* complete; +- (id) _id: (NSNumber*) _id + petId: (NSNumber*) petId + quantity: (NSNumber*) quantity + shipDate: (SWGDate*) shipDate + status: (NSString*) status + complete: (NSNumber*) complete; + - (id) initWithValues: (NSDictionary*)dict; - (NSDictionary*) asDictionary; - @end - diff --git a/samples/client/petstore/objc/client/SWGOrder.m b/samples/client/petstore/objc/client/SWGOrder.m index cdcf432bb880..d2147a7b1c36 100644 --- a/samples/client/petstore/objc/client/SWGOrder.m +++ b/samples/client/petstore/objc/client/SWGOrder.m @@ -6,41 +6,66 @@ -(id)_id: (NSNumber*) _id petId: (NSNumber*) petId quantity: (NSNumber*) quantity - status: (NSString*) status shipDate: (SWGDate*) shipDate + status: (NSString*) status + complete: (NSNumber*) complete + { - __id = _id; - _petId = petId; - _quantity = quantity; - _status = status; - _shipDate = shipDate; - return self; + __id = _id; + _petId = petId; + _quantity = quantity; + _shipDate = shipDate; + _status = status; + _complete = complete; + + + return self; } -(id) initWithValues:(NSDictionary*)dict { self = [super init]; if(self) { - __id = dict[@"id"]; - _petId = dict[@"petId"]; - _quantity = dict[@"quantity"]; - _status = dict[@"status"]; - id shipDate_dict = dict[@"shipDate"]; - if(shipDate_dict != nil) - _shipDate = [[SWGDate alloc]initWithValues:shipDate_dict]; + __id = dict[@"id"]; + + _petId = dict[@"petId"]; + + _quantity = dict[@"quantity"]; + + + + id shipDate_dict = dict[@"shipDate"]; + + if(shipDate_dict != nil) + _shipDate = [[SWGDate alloc]initWithValues:shipDate_dict]; + + + _status = dict[@"status"]; + + _complete = dict[@"complete"]; + - } return self; } -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; - if(__id != nil) dict[@"id"] = __id ; - if(_petId != nil) dict[@"petId"] = _petId ; - if(_quantity != nil) dict[@"quantity"] = _quantity ; - if(_status != nil) dict[@"status"] = _status ; - if(_shipDate != nil){ + + + if(__id != nil) dict[@"id"] = __id ; + + + + if(_petId != nil) dict[@"petId"] = _petId ; + + + + if(_quantity != nil) dict[@"quantity"] = _quantity ; + + + + if(_shipDate != nil){ if([_shipDate isKindOfClass:[NSArray class]]){ NSMutableArray * array = [[NSMutableArray alloc] init]; for( SWGDate *shipDate in (NSArray*)_shipDate) { @@ -55,12 +80,24 @@ } } else { - if(_shipDate != nil) dict[@"shipDate"] = [(SWGObject*)_shipDate asDictionary]; + + if(_shipDate != nil) dict[@"shipDate"] = [(SWGObject*)_shipDate asDictionary]; + } } + + + + if(_status != nil) dict[@"status"] = _status ; + + + + if(_complete != nil) dict[@"complete"] = _complete ; + + + NSDictionary* output = [dict copy]; return output; } @end - diff --git a/samples/client/petstore/objc/client/SWGPet.h b/samples/client/petstore/objc/client/SWGPet.h index d36a50cbf4d6..f16fa74cf1e5 100644 --- a/samples/client/petstore/objc/client/SWGPet.h +++ b/samples/client/petstore/objc/client/SWGPet.h @@ -1,33 +1,26 @@ #import #import "SWGObject.h" -#import "SWGCategory.h" #import "SWGTag.h" +#import "SWGCategory.h" @interface SWGPet : SWGObject -@property(nonatomic) NSNumber* _id; /* unique identifier for the pet */ - +@property(nonatomic) NSNumber* _id; @property(nonatomic) SWGCategory* category; - @property(nonatomic) NSString* name; - @property(nonatomic) NSArray* photoUrls; - @property(nonatomic) NSArray* tags; - -@property(nonatomic) NSString* status; /* pet status in the store [optional]*/ - -- (id) _id: (NSNumber*) _id - category: (SWGCategory*) category - name: (NSString*) name - photoUrls: (NSArray*) photoUrls - tags: (NSArray*) tags - status: (NSString*) status; +@property(nonatomic) NSString* status; /* pet status in the store */ +- (id) _id: (NSNumber*) _id + category: (SWGCategory*) category + name: (NSString*) name + photoUrls: (NSArray*) photoUrls + tags: (NSArray*) tags + status: (NSString*) status; + - (id) initWithValues: (NSDictionary*)dict; - (NSDictionary*) asDictionary; - @end - diff --git a/samples/client/petstore/objc/client/SWGPet.m b/samples/client/petstore/objc/client/SWGPet.m index 4bbfe48a8eac..4a863a7e1fda 100644 --- a/samples/client/petstore/objc/client/SWGPet.m +++ b/samples/client/petstore/objc/client/SWGPet.m @@ -9,57 +9,74 @@ photoUrls: (NSArray*) photoUrls tags: (NSArray*) tags status: (NSString*) status + { - __id = _id; - _category = category; - _name = name; - _photoUrls = photoUrls; - _tags = tags; - _status = status; - return self; + __id = _id; + _category = category; + _name = name; + _photoUrls = photoUrls; + _tags = tags; + _status = status; + + + return self; } -(id) initWithValues:(NSDictionary*)dict { self = [super init]; if(self) { - __id = dict[@"id"]; + __id = dict[@"id"]; + + + id category_dict = dict[@"category"]; + if(category_dict != nil) - _category = [[SWGCategory alloc]initWithValues:category_dict]; - _name = dict[@"name"]; - _photoUrls = dict[@"photoUrls"]; + _category = [[SWGCategory alloc]initWithValues:category_dict]; + + + _name = dict[@"name"]; + + _photoUrls = dict[@"photoUrls"]; + + + id tags_dict = dict[@"tags"]; + if([tags_dict isKindOfClass:[NSArray class]]) { - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[(NSArray*)tags_dict count]]; - if([(NSArray*)tags_dict count] > 0) { for (NSDictionary* dict in (NSArray*)tags_dict) { SWGTag* d = [[SWGTag alloc] initWithValues:dict]; [objs addObject:d]; } - _tags = [[NSArray alloc] initWithArray:objs]; } - else { + else _tags = [[NSArray alloc] init]; - } } else { _tags = [[NSArray alloc] init]; } - _status = dict[@"status"]; - + + _status = dict[@"status"]; + + } return self; } -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; - if(__id != nil) dict[@"id"] = __id ; - if(_category != nil){ + + + if(__id != nil) dict[@"id"] = __id ; + + + + if(_category != nil){ if([_category isKindOfClass:[NSArray class]]){ NSMutableArray * array = [[NSMutableArray alloc] init]; for( SWGCategory *category in (NSArray*)_category) { @@ -74,12 +91,23 @@ } } else { - if(_category != nil) dict[@"category"] = [(SWGObject*)_category asDictionary]; + + if(_category != nil) dict[@"category"] = [(SWGObject*)_category asDictionary]; + } } - if(_name != nil) dict[@"name"] = _name ; - if(_photoUrls != nil) dict[@"photoUrls"] = _photoUrls ; - if(_tags != nil){ + + + + if(_name != nil) dict[@"name"] = _name ; + + + + if(_photoUrls != nil) dict[@"photoUrls"] = _photoUrls ; + + + + if(_tags != nil){ if([_tags isKindOfClass:[NSArray class]]){ NSMutableArray * array = [[NSMutableArray alloc] init]; for( SWGTag *tags in (NSArray*)_tags) { @@ -94,13 +122,20 @@ } } else { - if(_tags != nil) dict[@"tags"] = [(SWGObject*)_tags asDictionary]; + + if(_tags != nil) dict[@"tags"] = [(SWGObject*)_tags asDictionary]; + } } - if(_status != nil) dict[@"status"] = _status ; - NSDictionary* output = [dict copy]; + + + + if(_status != nil) dict[@"status"] = _status ; + + + + NSDictionary* output = [dict copy]; return output; } @end - diff --git a/samples/client/petstore/objc/client/SWGPetApi.h b/samples/client/petstore/objc/client/SWGPetApi.h index 2e9b2cbf8aff..b40a210ea4ce 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.h +++ b/samples/client/petstore/objc/client/SWGPetApi.h @@ -1,7 +1,7 @@ #import #import "SWGPet.h" #import "SWGFile.h" - +#import "SWGObject.h" @interface SWGPetApi: NSObject @@ -13,91 +13,170 @@ +(NSString*) getBasePath; /** - Find pet by ID - Returns a pet based on ID - @param petId ID of pet that needs to be fetched - */ --(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId - completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock; - -/** - - Deletes a pet + Update an existing pet - @param petId Pet id to delete - */ --(NSNumber*) deletePetWithCompletionBlock :(NSString*) petId - completionHandler: (void (^)(NSError* error))completionBlock; - -/** - - partial updates to a pet - @param petId ID of pet that needs to be fetched + + + @param body Pet object that needs to be added to the store - */ --(NSNumber*) partialUpdateWithCompletionBlock :(NSString*) petId - body:(SWGPet*) body - completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; - -/** - - Updates a pet in the store with form data - @param petId ID of pet that needs to be updated - @param name Updated name of the pet - @param status Updated status of the pet - */ --(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId - name:(NSString*) name - status:(NSString*) status - completionHandler: (void (^)(NSError* error))completionBlock; -/** - - uploads an image - - @param additionalMetadata Additional data to pass to server - @param body file to upload + return type: */ --(NSNumber*) uploadFileWithCompletionBlock :(NSString*) additionalMetadata - body:(SWGFile*) body - completionHandler: (void (^)(NSError* error))completionBlock; +-(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body + + + completionHandler: (void (^)(NSError* error))completionBlock; + /** Add a new pet to the store + + + + @param body Pet object that needs to be added to the store + + + return type: */ -(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body - completionHandler: (void (^)(NSError* error))completionBlock; + + + completionHandler: (void (^)(NSError* error))completionBlock; -/** - - Update an existing pet - - @param body Pet object that needs to be updated in the store - */ --(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body - completionHandler: (void (^)(NSError* error))completionBlock; /** Finds Pets by status + Multiple status values can be provided with comma seperated strings + + + @param status Status values that need to be considered for filter + + + return type: NSArray* */ --(NSNumber*) findPetsByStatusWithCompletionBlock :(NSString*) status - completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; +-(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status + + completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; + + /** Finds Pets by tags + Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - @param tags Tags to filter by - */ --(NSNumber*) findPetsByTagsWithCompletionBlock :(NSString*) tags - completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; + -@end + + @param tags Tags to filter by + + + return type: NSArray* + */ +-(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray*) tags + + completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; + + + +/** + + Find pet by ID + + Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + + + + @param petId ID of pet that needs to be fetched + + + return type: SWGPet* + */ +-(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId + + completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock; + + + +/** + + Updates a pet in the store with form data + + + + + + @param petId ID of pet that needs to be updated + + @param name Updated name of the pet + + @param status Updated status of the pet + + + return type: + */ +-(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId + name:(NSString*) name + status:(NSString*) status + + + completionHandler: (void (^)(NSError* error))completionBlock; + + +/** + + Deletes a pet + + + + + + @param api_key + + @param petId Pet id to delete + + + return type: + */ +-(NSNumber*) deletePetWithCompletionBlock :(NSString*) api_key + petId:(NSNumber*) petId + + + completionHandler: (void (^)(NSError* error))completionBlock; + + +/** + + uploads an image + + + + + + @param petId ID of pet to update + + @param additionalMetadata Additional data to pass to server + + @param file file to upload + + + return type: + */ +-(NSNumber*) uploadFileWithCompletionBlock :(NSNumber*) petId + additionalMetadata:(NSString*) additionalMetadata + file:(SWGFile*) file + + + completionHandler: (void (^)(NSError* error))completionBlock; + + + +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index b911307b4e68..bf968a2776a0 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -6,9 +6,8 @@ - @implementation SWGPetApi -static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; +static NSString * basePath = @"http://petstore.swagger.io/v2"; +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static SWGPetApi* singletonAPI = nil; @@ -52,281 +51,10 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; } --(NSNumber*) getPetByIdWithCompletionBlock:(NSNumber*) petId - completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(petId == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType:requestContentType - responseContentType:responseContentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - SWGPet *result = nil; - if (data) { - result = [[SWGPet alloc]initWithValues: data]; - } - completionBlock(result , nil);}]; - - -} - --(NSNumber*) deletePetWithCompletionBlock:(NSString*) petId - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(petId == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"DELETE" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(NSNumber*) partialUpdateWithCompletionBlock:(NSString*) petId - body:(SWGPet*) body - completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(SWGObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(SWGObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - // convert it to a dictionary - NSError * error; - NSString * str = (NSString*)body; - NSDictionary *JSON = - [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] - options:NSJSONReadingMutableContainers - error:&error]; - bodyDictionary = JSON; - } - else if([body isKindOfClass: [SWGFile class]]) { - requestContentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(petId == nil) { - // error - } - if(body == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client dictionary: requestUrl - method: @"PATCH" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - SWGPet* d = [[SWGPet alloc]initWithValues: dict]; - [objs addObject:d]; - } - completionBlock(objs, nil); - } - }]; - - -} - --(NSNumber*) updatePetWithFormWithCompletionBlock:(NSString*) petId - name:(NSString*) name - status:(NSString*) status - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(petId == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(NSNumber*) uploadFileWithCompletionBlock:(NSString*) additionalMetadata - body:(SWGFile*) body - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/uploadImage", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(SWGObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(SWGObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - // convert it to a dictionary - NSError * error; - NSString * str = (NSString*)body; - NSDictionary *JSON = - [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] - options:NSJSONReadingMutableContainers - error:&error]; - bodyDictionary = JSON; - } - else if([body isKindOfClass: [SWGFile class]]) { - requestContentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(NSNumber*) addPetWithCompletionBlock:(SWGPet*) body - completionHandler: (void (^)(NSError* error))completionBlock{ +-(NSNumber*) updatePetWithCompletionBlock: (SWGPet*) body + + + completionHandler: (void (^)(NSError* error))completionBlock { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; @@ -334,15 +62,23 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; NSString* responseContentType = @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ + + id __body = body; + + if(__body != nil && [__body isKindOfClass:[NSArray class]]){ NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { + for (id dict in (NSArray*)__body) { if([dict respondsToSelector:@selector(asDictionary)]) { [objs addObject:[(SWGObject*)dict asDictionary]]; } @@ -352,52 +88,56 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; } bodyDictionary = objs; } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(SWGObject*)body asDictionary]; + else if([__body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)__body asDictionary]; } - else if([body isKindOfClass:[NSString class]]) { + else if([__body isKindOfClass:[NSString class]]) { // convert it to a dictionary NSError * error; - NSString * str = (NSString*)body; + NSString * str = (NSString*)__body; NSDictionary *JSON = - [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] - options:NSJSONReadingMutableContainers - error:&error]; + [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding] + options: NSJSONReadingMutableContainers + error: &error]; bodyDictionary = JSON; } - else if([body isKindOfClass: [SWGFile class]]) { - requestContentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"PUT" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + } --(NSNumber*) updatePetWithCompletionBlock:(SWGPet*) body - completionHandler: (void (^)(NSError* error))completionBlock{ +-(NSNumber*) addPetWithCompletionBlock: (SWGPet*) body + + + completionHandler: (void (^)(NSError* error))completionBlock { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; @@ -405,15 +145,23 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; NSString* responseContentType = @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ + + id __body = body; + + if(__body != nil && [__body isKindOfClass:[NSArray class]]){ NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { + for (id dict in (NSArray*)__body) { if([dict respondsToSelector:@selector(asDictionary)]) { [objs addObject:[(SWGObject*)dict asDictionary]]; } @@ -423,52 +171,56 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; } bodyDictionary = objs; } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(SWGObject*)body asDictionary]; + else if([__body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)__body asDictionary]; } - else if([body isKindOfClass:[NSString class]]) { + else if([__body isKindOfClass:[NSString class]]) { // convert it to a dictionary NSError * error; - NSString * str = (NSString*)body; + NSString * str = (NSString*)__body; NSDictionary *JSON = - [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] - options:NSJSONReadingMutableContainers - error:&error]; + [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding] + options: NSJSONReadingMutableContainers + error: &error]; bodyDictionary = JSON; } - else if([body isKindOfClass: [SWGFile class]]) { - requestContentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"PUT" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + } --(NSNumber*) findPetsByStatusWithCompletionBlock:(NSString*) status - completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock{ +-(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray*) status + + completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock + { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByStatus", basePath]; @@ -476,46 +228,56 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; NSString* responseContentType = @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; if(status != nil) queryParams[@"status"] = status; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(status == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client dictionary: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - SWGPet* d = [[SWGPet alloc]initWithValues: dict]; - [objs addObject:d]; - } - completionBlock(objs, nil); - } - }]; + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + // array container response type + return [client dictionary: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error); + return; + } + + }]; + + } --(NSNumber*) findPetsByTagsWithCompletionBlock:(NSString*) tags - completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock{ +-(NSNumber*) findPetsByTagsWithCompletionBlock: (NSArray*) tags + + completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock + { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByTags", basePath]; @@ -523,44 +285,325 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; NSString* responseContentType = @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; if(tags != nil) queryParams[@"tags"] = tags; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(tags == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client dictionary: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - SWGPet* d = [[SWGPet alloc]initWithValues: dict]; - [objs addObject:d]; - } - completionBlock(objs, nil); - } - }]; + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + // array container response type + return [client dictionary: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error); + return; + } + + }]; + + +} + +-(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId + + completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock + { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + + // comples response type + return [client dictionary: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error); + + return; + } + + SWGPet *result = nil; + if (data) { + result = [[SWGPet alloc]initWithValues: data]; + } + completionBlock(result , nil); + + }]; + + +} + +-(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId + name: (NSString*) name + status: (NSString*) status + + + completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + formParams[@"name"] = name; + + formParams[@"status"] = status; + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + +} + +-(NSNumber*) deletePetWithCompletionBlock: (NSString*) api_key + petId: (NSNumber*) petId + + + completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + if(api_key != nil) + headerParams[@"api_key"] = api_key; + + + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"DELETE" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + +} + +-(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId + additionalMetadata: (NSString*) additionalMetadata + file: (SWGFile*) file + + + completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}/uploadImage", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + formParams[@"additionalMetadata"] = additionalMetadata; + + requestContentType = @"multipart/form-data"; + [bodyDictionary addObject:file]; + file.paramName = @"file"; + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + } -@end +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/SWGStoreApi.h b/samples/client/petstore/objc/client/SWGStoreApi.h index 9dcfdbd3ea72..2daa1e8656fb 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.h +++ b/samples/client/petstore/objc/client/SWGStoreApi.h @@ -1,6 +1,6 @@ #import #import "SWGOrder.h" - +#import "SWGObject.h" @interface SWGStoreApi: NSObject @@ -12,29 +12,76 @@ +(NSString*) getBasePath; /** - Find purchase order by ID - For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors - @param orderId ID of pet that needs to be fetched - */ --(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId - completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; + Returns pet inventories by status + + Returns a map of status codes to quantities + -/** + - Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - @param orderId ID of the order that needs to be deleted + return type: NSDictionary* */ --(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId - completionHandler: (void (^)(NSError* error))completionBlock; +-(NSNumber*) getInventoryWithCompletionBlock : + (void (^)(NSDictionary* output, NSError* error))completionBlock; + + /** Place an order for a pet + + + + @param body order placed for purchasing the pet + + + return type: SWGOrder* */ -(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body - completionHandler: (void (^)(NSError* error))completionBlock; + + completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; + -@end + +/** + + Find purchase order by ID + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + + + + @param orderId ID of pet that needs to be fetched + + + return type: SWGOrder* + */ +-(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId + + completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; + + + +/** + + Delete purchase order by ID + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + + + + @param orderId ID of the order that needs to be deleted + + + return type: + */ +-(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId + + + completionHandler: (void (^)(NSError* error))completionBlock; + + + +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m index 8bb18a8c8e39..b81d127eb51e 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.m +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -5,9 +5,8 @@ - @implementation SWGStoreApi -static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; +static NSString * basePath = @"http://petstore.swagger.io/v2"; +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static SWGStoreApi* singletonAPI = nil; @@ -51,88 +50,70 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; } --(NSNumber*) getOrderByIdWithCompletionBlock:(NSString*) orderId - completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock{ +-(NSNumber*) getInventoryWithCompletionBlock: + (void (^)(NSDictionary* output, NSError* error))completionBlock + { - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/inventory", basePath]; // remove format in URL if needed if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; + + NSString* requestContentType = @"application/json"; NSString* responseContentType = @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(orderId == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType:requestContentType - responseContentType:responseContentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - SWGOrder *result = nil; - if (data) { - result = [[SWGOrder alloc]initWithValues: data]; - } - completionBlock(result , nil);}]; -} - --(NSNumber*) deleteOrderWithCompletionBlock:(NSString*) orderId - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; id bodyDictionary = nil; - if(orderId == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + bodyDictionary = [[NSMutableArray alloc] init]; - return [client stringWithCompletionBlock:requestUrl - method:@"DELETE" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + [bodyDictionary addObject:formParams]; + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + // map container response type + return [client dictionary: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error); + return; + } + + NSDictionary *result = nil; + if (data) { + result = [[NSDictionary alloc]initWithDictionary: data]; + } + completionBlock(data, nil); + + }]; + + } --(NSNumber*) placeOrderWithCompletionBlock:(SWGOrder*) body - completionHandler: (void (^)(NSError* error))completionBlock{ +-(NSNumber*) placeOrderWithCompletionBlock: (SWGOrder*) body + + completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock + { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath]; @@ -140,15 +121,23 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; NSString* responseContentType = @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ + + id __body = body; + + if(__body != nil && [__body isKindOfClass:[NSArray class]]){ NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { + for (id dict in (NSArray*)__body) { if([dict respondsToSelector:@selector(asDictionary)]) { [objs addObject:[(SWGObject*)dict asDictionary]]; } @@ -158,50 +147,186 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; } bodyDictionary = objs; } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(SWGObject*)body asDictionary]; + else if([__body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)__body asDictionary]; } - else if([body isKindOfClass:[NSString class]]) { + else if([__body isKindOfClass:[NSString class]]) { // convert it to a dictionary NSError * error; - NSString * str = (NSString*)body; + NSString * str = (NSString*)__body; NSDictionary *JSON = - [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] - options:NSJSONReadingMutableContainers - error:&error]; + [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding] + options: NSJSONReadingMutableContainers + error: &error]; bodyDictionary = JSON; } - else if([body isKindOfClass: [SWGFile class]]) { - requestContentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + + // comples response type + return [client dictionary: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error); + + return; + } + + SWGOrder *result = nil; + if (data) { + result = [[SWGOrder alloc]initWithValues: data]; + } + completionBlock(result , nil); + + }]; + + +} + +-(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId + + completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock + { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; + + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + + // comples response type + return [client dictionary: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error); + + return; + } + + SWGOrder *result = nil; + if (data) { + result = [[SWGOrder alloc]initWithValues: data]; + } + completionBlock(result , nil); + + }]; + + +} + +-(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId + + + completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; + + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"DELETE" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + } -@end +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/SWGTag.h b/samples/client/petstore/objc/client/SWGTag.h index 55ad9f0422ee..7eb82c7f2bcd 100644 --- a/samples/client/petstore/objc/client/SWGTag.h +++ b/samples/client/petstore/objc/client/SWGTag.h @@ -5,15 +5,12 @@ @interface SWGTag : SWGObject @property(nonatomic) NSNumber* _id; - @property(nonatomic) NSString* name; - -- (id) _id: (NSNumber*) _id - name: (NSString*) name; +- (id) _id: (NSNumber*) _id + name: (NSString*) name; + - (id) initWithValues: (NSDictionary*)dict; - (NSDictionary*) asDictionary; - @end - diff --git a/samples/client/petstore/objc/client/SWGTag.m b/samples/client/petstore/objc/client/SWGTag.m index 0949e5eaa458..bb1ea0262fd8 100644 --- a/samples/client/petstore/objc/client/SWGTag.m +++ b/samples/client/petstore/objc/client/SWGTag.m @@ -5,31 +5,42 @@ -(id)_id: (NSNumber*) _id name: (NSString*) name + { - __id = _id; - _name = name; - return self; + __id = _id; + _name = name; + + + return self; } -(id) initWithValues:(NSDictionary*)dict { self = [super init]; if(self) { - __id = dict[@"id"]; - _name = dict[@"name"]; + __id = dict[@"id"]; + + _name = dict[@"name"]; + - } return self; } -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; - if(__id != nil) dict[@"id"] = __id ; - if(_name != nil) dict[@"name"] = _name ; - NSDictionary* output = [dict copy]; + + + if(__id != nil) dict[@"id"] = __id ; + + + + if(_name != nil) dict[@"name"] = _name ; + + + + NSDictionary* output = [dict copy]; return output; } @end - diff --git a/samples/client/petstore/objc/client/SWGUser.h b/samples/client/petstore/objc/client/SWGUser.h index 659687bda0be..938f2775c5e4 100644 --- a/samples/client/petstore/objc/client/SWGUser.h +++ b/samples/client/petstore/objc/client/SWGUser.h @@ -5,33 +5,24 @@ @interface SWGUser : SWGObject @property(nonatomic) NSNumber* _id; - -@property(nonatomic) NSString* firstName; - @property(nonatomic) NSString* username; - +@property(nonatomic) NSString* firstName; @property(nonatomic) NSString* lastName; - @property(nonatomic) NSString* email; - @property(nonatomic) NSString* password; - @property(nonatomic) NSString* phone; - -@property(nonatomic) NSNumber* userStatus; /* User Status [optional]*/ - -- (id) _id: (NSNumber*) _id - firstName: (NSString*) firstName - username: (NSString*) username - lastName: (NSString*) lastName - email: (NSString*) email - password: (NSString*) password - phone: (NSString*) phone - userStatus: (NSNumber*) userStatus; +@property(nonatomic) NSNumber* userStatus; /* User Status */ +- (id) _id: (NSNumber*) _id + username: (NSString*) username + firstName: (NSString*) firstName + lastName: (NSString*) lastName + email: (NSString*) email + password: (NSString*) password + phone: (NSString*) phone + userStatus: (NSNumber*) userStatus; + - (id) initWithValues: (NSDictionary*)dict; - (NSDictionary*) asDictionary; - @end - diff --git a/samples/client/petstore/objc/client/SWGUser.m b/samples/client/petstore/objc/client/SWGUser.m index 1b2f85a29c31..a4121f6ec5c5 100644 --- a/samples/client/petstore/objc/client/SWGUser.m +++ b/samples/client/petstore/objc/client/SWGUser.m @@ -4,56 +4,91 @@ @implementation SWGUser -(id)_id: (NSNumber*) _id - firstName: (NSString*) firstName username: (NSString*) username + firstName: (NSString*) firstName lastName: (NSString*) lastName email: (NSString*) email password: (NSString*) password phone: (NSString*) phone userStatus: (NSNumber*) userStatus + { - __id = _id; - _firstName = firstName; - _username = username; - _lastName = lastName; - _email = email; - _password = password; - _phone = phone; - _userStatus = userStatus; - return self; + __id = _id; + _username = username; + _firstName = firstName; + _lastName = lastName; + _email = email; + _password = password; + _phone = phone; + _userStatus = userStatus; + + + return self; } -(id) initWithValues:(NSDictionary*)dict { self = [super init]; if(self) { - __id = dict[@"id"]; - _firstName = dict[@"firstName"]; - _username = dict[@"username"]; - _lastName = dict[@"lastName"]; - _email = dict[@"email"]; - _password = dict[@"password"]; - _phone = dict[@"phone"]; - _userStatus = dict[@"userStatus"]; + __id = dict[@"id"]; + + _username = dict[@"username"]; + + _firstName = dict[@"firstName"]; + + _lastName = dict[@"lastName"]; + + _email = dict[@"email"]; + + _password = dict[@"password"]; + + _phone = dict[@"phone"]; + + _userStatus = dict[@"userStatus"]; + - } return self; } -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; - if(__id != nil) dict[@"id"] = __id ; - if(_firstName != nil) dict[@"firstName"] = _firstName ; - if(_username != nil) dict[@"username"] = _username ; - if(_lastName != nil) dict[@"lastName"] = _lastName ; - if(_email != nil) dict[@"email"] = _email ; - if(_password != nil) dict[@"password"] = _password ; - if(_phone != nil) dict[@"phone"] = _phone ; - if(_userStatus != nil) dict[@"userStatus"] = _userStatus ; - NSDictionary* output = [dict copy]; + + + if(__id != nil) dict[@"id"] = __id ; + + + + if(_username != nil) dict[@"username"] = _username ; + + + + if(_firstName != nil) dict[@"firstName"] = _firstName ; + + + + if(_lastName != nil) dict[@"lastName"] = _lastName ; + + + + if(_email != nil) dict[@"email"] = _email ; + + + + if(_password != nil) dict[@"password"] = _password ; + + + + if(_phone != nil) dict[@"phone"] = _phone ; + + + + if(_userStatus != nil) dict[@"userStatus"] = _userStatus ; + + + + NSDictionary* output = [dict copy]; return output; } @end - diff --git a/samples/client/petstore/objc/client/SWGUserApi.h b/samples/client/petstore/objc/client/SWGUserApi.h index 9a8cc281ef39..14d08208f836 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.h +++ b/samples/client/petstore/objc/client/SWGUserApi.h @@ -1,6 +1,6 @@ #import #import "SWGUser.h" - +#import "SWGObject.h" @interface SWGUserApi: NSObject @@ -10,78 +10,160 @@ +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(void) setBasePath:(NSString*)basePath; +(NSString*) getBasePath; -/** - - Updated user - This can only be done by the logged in user. - @param username name that need to be deleted - @param body Updated user object - */ --(NSNumber*) updateUserWithCompletionBlock :(NSString*) username - body:(SWGUser*) body - completionHandler: (void (^)(NSError* error))completionBlock; - -/** - - Delete user - This can only be done by the logged in user. - @param username The name that needs to be deleted - */ --(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username - completionHandler: (void (^)(NSError* error))completionBlock; - -/** - - Get user by user name - - @param username The name that needs to be fetched. Use user1 for testing. - */ --(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username - completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock; - -/** - - Logs user into the system - - @param username The user name for login - @param password The password for login in clear text - */ --(NSNumber*) loginUserWithCompletionBlock :(NSString*) username - password:(NSString*) password - completionHandler: (void (^)(NSString* output, NSError* error))completionBlock; - -/** - - Logs out current logged in user session - - */ --(NSNumber*) logoutUserWithCompletionBlock :(void (^)(NSError* error))completionBlock; - /** Create user + This can only be done by the logged in user. + + + @param body Created user object + + + return type: */ -(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body - completionHandler: (void (^)(NSError* error))completionBlock; + + + completionHandler: (void (^)(NSError* error))completionBlock; + /** Creates list of users with given input array + + + + @param body List of user object + + + return type: */ -(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray*) body - completionHandler: (void (^)(NSError* error))completionBlock; + + + completionHandler: (void (^)(NSError* error))completionBlock; + /** - Creates list of users with given list input + Creates list of users with given input array + + + + @param body List of user object + + + return type: */ -(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray*) body - completionHandler: (void (^)(NSError* error))completionBlock; + + + completionHandler: (void (^)(NSError* error))completionBlock; -@end + +/** + + Logs user into the system + + + + + + @param username The user name for login + + @param password The password for login in clear text + + + return type: NSString* + */ +-(NSNumber*) loginUserWithCompletionBlock :(NSString*) username + password:(NSString*) password + + completionHandler: (void (^)(NSString* output, NSError* error))completionBlock; + + + +/** + + Logs out current logged in user session + + + + + + + return type: + */ +-(NSNumber*) logoutUserWithCompletionBlock : + + (void (^)(NSError* error))completionBlock; + + +/** + + Get user by user name + + + + + + @param username The name that needs to be fetched. Use user1 for testing. + + + return type: SWGUser* + */ +-(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username + + completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock; + + + +/** + + Updated user + + This can only be done by the logged in user. + + + + @param username name that need to be deleted + + @param body Updated user object + + + return type: + */ +-(NSNumber*) updateUserWithCompletionBlock :(NSString*) username + body:(SWGUser*) body + + + completionHandler: (void (^)(NSError* error))completionBlock; + + +/** + + Delete user + + This can only be done by the logged in user. + + + + @param username The name that needs to be deleted + + + return type: + */ +-(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username + + + completionHandler: (void (^)(NSError* error))completionBlock; + + + +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/SWGUserApi.m b/samples/client/petstore/objc/client/SWGUserApi.m index f7e9df6289aa..4c69415620b6 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.m +++ b/samples/client/petstore/objc/client/SWGUserApi.m @@ -5,9 +5,8 @@ - @implementation SWGUserApi -static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; +static NSString * basePath = @"http://petstore.swagger.io/v2"; +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static SWGUserApi* singletonAPI = nil; @@ -51,245 +50,10 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; } --(NSNumber*) updateUserWithCompletionBlock:(NSString*) username - body:(SWGUser*) body - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(SWGObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(SWGObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - // convert it to a dictionary - NSError * error; - NSString * str = (NSString*)body; - NSDictionary *JSON = - [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] - options:NSJSONReadingMutableContainers - error:&error]; - bodyDictionary = JSON; - } - else if([body isKindOfClass: [SWGFile class]]) { - requestContentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(username == nil) { - // error - } - if(body == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"PUT" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(NSNumber*) deleteUserWithCompletionBlock:(NSString*) username - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(username == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"DELETE" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(NSNumber*) getUserByNameWithCompletionBlock:(NSString*) username - completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(username == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType:requestContentType - responseContentType:responseContentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - SWGUser *result = nil; - if (data) { - result = [[SWGUser alloc]initWithValues: data]; - } - completionBlock(result , nil);}]; - - -} - --(NSNumber*) loginUserWithCompletionBlock:(NSString*) username - password:(NSString*) password - completionHandler: (void (^)(NSString* output, NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/login", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(username != nil) - queryParams[@"username"] = username; - if(password != nil) - queryParams[@"password"] = password; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(username == nil) { - // error - } - if(password == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(nil, error); - return; - } - NSString *result = data ? [[NSString alloc]initWithString: data] : nil; - completionBlock(result, nil); - }]; - - -} - --(NSNumber*) logoutUserWithCompletionBlock: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/logout", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(NSNumber*) createUserWithCompletionBlock:(SWGUser*) body - completionHandler: (void (^)(NSError* error))completionBlock{ +-(NSNumber*) createUserWithCompletionBlock: (SWGUser*) body + + + completionHandler: (void (^)(NSError* error))completionBlock { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user", basePath]; @@ -297,15 +61,23 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; NSString* responseContentType = @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ + + id __body = body; + + if(__body != nil && [__body isKindOfClass:[NSArray class]]){ NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { + for (id dict in (NSArray*)__body) { if([dict respondsToSelector:@selector(asDictionary)]) { [objs addObject:[(SWGObject*)dict asDictionary]]; } @@ -315,52 +87,56 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; } bodyDictionary = objs; } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(SWGObject*)body asDictionary]; + else if([__body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)__body asDictionary]; } - else if([body isKindOfClass:[NSString class]]) { + else if([__body isKindOfClass:[NSString class]]) { // convert it to a dictionary NSError * error; - NSString * str = (NSString*)body; + NSString * str = (NSString*)__body; NSDictionary *JSON = - [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] - options:NSJSONReadingMutableContainers - error:&error]; + [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding] + options: NSJSONReadingMutableContainers + error: &error]; bodyDictionary = JSON; } - else if([body isKindOfClass: [SWGFile class]]) { - requestContentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + } --(NSNumber*) createUsersWithArrayInputWithCompletionBlock:(NSArray*) body - completionHandler: (void (^)(NSError* error))completionBlock{ +-(NSNumber*) createUsersWithArrayInputWithCompletionBlock: (NSArray*) body + + + completionHandler: (void (^)(NSError* error))completionBlock { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithArray", basePath]; @@ -368,15 +144,23 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; NSString* responseContentType = @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ + + id __body = body; + + if(__body != nil && [__body isKindOfClass:[NSArray class]]){ NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { + for (id dict in (NSArray*)__body) { if([dict respondsToSelector:@selector(asDictionary)]) { [objs addObject:[(SWGObject*)dict asDictionary]]; } @@ -386,52 +170,56 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; } bodyDictionary = objs; } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(SWGObject*)body asDictionary]; + else if([__body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)__body asDictionary]; } - else if([body isKindOfClass:[NSString class]]) { + else if([__body isKindOfClass:[NSString class]]) { // convert it to a dictionary NSError * error; - NSString * str = (NSString*)body; + NSString * str = (NSString*)__body; NSDictionary *JSON = - [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] - options:NSJSONReadingMutableContainers - error:&error]; + [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding] + options: NSJSONReadingMutableContainers + error: &error]; bodyDictionary = JSON; } - else if([body isKindOfClass: [SWGFile class]]) { - requestContentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + } --(NSNumber*) createUsersWithListInputWithCompletionBlock:(NSArray*) body - completionHandler: (void (^)(NSError* error))completionBlock{ +-(NSNumber*) createUsersWithListInputWithCompletionBlock: (NSArray*) body + + + completionHandler: (void (^)(NSError* error))completionBlock { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithList", basePath]; @@ -439,15 +227,23 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; NSString* responseContentType = @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ + + id __body = body; + + if(__body != nil && [__body isKindOfClass:[NSArray class]]){ NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { + for (id dict in (NSArray*)__body) { if([dict respondsToSelector:@selector(asDictionary)]) { [objs addObject:[(SWGObject*)dict asDictionary]]; } @@ -457,50 +253,394 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; } bodyDictionary = objs; } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(SWGObject*)body asDictionary]; + else if([__body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)__body asDictionary]; } - else if([body isKindOfClass:[NSString class]]) { + else if([__body isKindOfClass:[NSString class]]) { // convert it to a dictionary NSError * error; - NSString * str = (NSString*)body; + NSString * str = (NSString*)__body; NSDictionary *JSON = - [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] - options:NSJSONReadingMutableContainers - error:&error]; + [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding] + options: NSJSONReadingMutableContainers + error: &error]; bodyDictionary = JSON; } - else if([body isKindOfClass: [SWGFile class]]) { - requestContentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - return [client stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + +} + +-(NSNumber*) loginUserWithCompletionBlock: (NSString*) username + password: (NSString*) password + + completionHandler: (void (^)(NSString* output, NSError* error))completionBlock + { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/login", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + if(username != nil) + queryParams[@"username"] = username; + if(password != nil) + queryParams[@"password"] = password; + + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + return [client stringWithCompletionBlock: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(nil, error); + return; + } + NSString *result = data ? [[NSString alloc]initWithString: data] : nil; + completionBlock(result, nil); + }]; + + + + + +} + +-(NSNumber*) logoutUserWithCompletionBlock: + + (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/logout", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + +} + +-(NSNumber*) getUserByNameWithCompletionBlock: (NSString*) username + + completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock + { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + + // comples response type + return [client dictionary: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error); + + return; + } + + SWGUser *result = nil; + if (data) { + result = [[SWGUser alloc]initWithValues: data]; + } + completionBlock(result , nil); + + }]; + + +} + +-(NSNumber*) updateUserWithCompletionBlock: (NSString*) username + body: (SWGUser*) body + + + completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + + id bodyDictionary = nil; + + id __body = body; + + if(__body != nil && [__body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)__body) { + if([dict respondsToSelector:@selector(asDictionary)]) { + [objs addObject:[(SWGObject*)dict asDictionary]]; + } + else{ + [objs addObject:dict]; + } + } + bodyDictionary = objs; + } + else if([__body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)__body asDictionary]; + } + else if([__body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)__body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding] + options: NSJSONReadingMutableContainers + error: &error]; + bodyDictionary = JSON; + } + + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"PUT" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + +} + +-(NSNumber*) deleteUserWithCompletionBlock: (NSString*) username + + + completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + + + id bodyDictionary = nil; + + + bodyDictionary = [[NSMutableArray alloc] init]; + + NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + + + [bodyDictionary addObject:formParams]; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + // primitive response type + + + // no return base type + return [client stringWithCompletionBlock: requestUrl + method: @"DELETE" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + + + } -@end +@end \ No newline at end of file diff --git a/samples/client/petstore/php/PHPPetstoreCodegen.scala b/samples/client/petstore/php/PHPPetstoreCodegen.scala deleted file mode 100644 index c438fff84bb7..000000000000 --- a/samples/client/petstore/php/PHPPetstoreCodegen.scala +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicPHPGenerator - -import java.io.File - -object PHPPetstoreCodegen extends BasicPHPGenerator { - def main(args: Array[String]) = generateClient(args) - - override def destinationDir = "samples/client/petstore/php" - - override def supportingFiles = List( - ("Swagger.mustache", destinationDir + File.separator + apiPackage.get, "Swagger.php") - ) -} \ No newline at end of file diff --git a/samples/client/petstore/php/PetApi.php b/samples/client/petstore/php/PetApi.php index f6dbc352395b..da31002dcbb8 100644 --- a/samples/client/petstore/php/PetApi.php +++ b/samples/client/petstore/php/PetApi.php @@ -1,6 +1,6 @@ apiClient = $apiClient; } - /** - * getPetById - * Find pet by ID - * petId, int: ID of pet that needs to be fetched (required) - - * @return Pet - */ - - public function getPetById($petId) { - - //parse inputs - $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($petId != null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($petId), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'Pet'); - return $responseObject; - - } - /** - * deletePet - * Deletes a pet - * petId, string: Pet id to delete (required) - - * @return - */ - - public function deletePet($petId) { - - //parse inputs - $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($petId != null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($petId), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - /** - * partialUpdate - * partial updates to a pet - * petId, string: ID of pet that needs to be fetched (required) - - * body, Pet: Pet object that needs to be added to the store (required) - - * @return Array[Pet] - */ - - public function partialUpdate($petId, $body) { - - //parse inputs - $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "PATCH"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json,application/xml'; - $headerParams['Content-Type'] = 'application/json,application/xml'; - - if($petId != null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($petId), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'Array[Pet]'); - return $responseObject; - - } - /** - * updatePetWithForm - * Updates a pet in the store with form data - * petId, string: ID of pet that needs to be updated (required) - - * name, string: Updated name of the pet (optional) - - * status, string: Updated status of the pet (optional) - - * @return - */ - - public function updatePetWithForm($petId, $name=null, $status=null) { - - //parse inputs - $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; - - if($petId != null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($petId), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - /** - * uploadFile - * uploads an image - * additionalMetadata, string: Additional data to pass to server (optional) - - * body, File: file to upload (optional) - - * @return - */ - - public function uploadFile($additionalMetadata=null, $body=null) { - - //parse inputs - $resourcePath = "/pet/uploadImage"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'multipart/form-data'; - - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - /** - * addPet - * Add a new pet to the store - * body, Pet: Pet object that needs to be added to the store (required) - - * @return - */ - - public function addPet($body) { - - //parse inputs - $resourcePath = "/pet"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json,application/xml'; - - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - /** + + /** * updatePet + * * Update an existing pet - * body, Pet: Pet object that needs to be updated in the store (required) - - * @return + * body, Pet: Pet object that needs to be added to the store (required) + * + * @return */ public function updatePet($body) { - //parse inputs + // parse inputs $resourcePath = "/pet"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "PUT"; $queryParams = array(); $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = 'application/json,application/xml'; - //make the API Call - if (! isset($body)) { - $body = null; + + + + + // body params + $body = null; + if (isset($body)) { + $body = $body; } + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $body, $headerParams); + + } + + /** + * addPet + * + * Add a new pet to the store + * body, Pet: Pet object that needs to be added to the store (required) + * + * @return + */ + public function addPet($body) { + + // parse inputs + $resourcePath = "/pet"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = 'application/json,application/xml'; + + + + + + // body params + $body = null; + if (isset($body)) { + $body = $body; } - /** - * findPetsByStatus - * Finds Pets by status - * status, string: Status values that need to be considered for filter (required) - * @return Array[Pet] + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + + } + + /** + * findPetsByStatus + * + * Finds Pets by status + * status, array[string]: Status values that need to be considered for filter (required) + * + * @return array[Pet] */ public function findPetsByStatus($status) { - //parse inputs + // parse inputs $resourcePath = "/pet/findByStatus"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; - if($status != null) { + // query params + if($status !== null) { $queryParams['status'] = $this->apiClient->toQueryValue($status); } - //make the API Call - if (! isset($body)) { - $body = null; + + + + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); } + + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $body, $headerParams); - - if(! $response){ - return null; - } + if(! $response) { + return null; + } $responseObject = $this->apiClient->deserialize($response, - 'Array[Pet]'); + 'array[Pet]'); return $responseObject; - - } - /** + } + + /** * findPetsByTags + * * Finds Pets by tags - * tags, string: Tags to filter by (required) - - * @return Array[Pet] + * tags, array[string]: Tags to filter by (required) + * + * @return array[Pet] */ public function findPetsByTags($tags) { - //parse inputs + // parse inputs $resourcePath = "/pet/findByTags"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; - if($tags != null) { + // query params + if($tags !== null) { $queryParams['tags'] = $this->apiClient->toQueryValue($tags); } - //make the API Call - if (! isset($body)) { - $body = null; + + + + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); } + + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $body, $headerParams); - - if(! $response){ - return null; - } + if(! $response) { + return null; + } $responseObject = $this->apiClient->deserialize($response, - 'Array[Pet]'); + 'array[Pet]'); return $responseObject; + } + + /** + * getPetById + * + * Find pet by ID + * petId, int: ID of pet that needs to be fetched (required) + * + * @return Pet + */ + public function getPetById($petId) { + + // parse inputs + $resourcePath = "/pet/{petId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; + + + + // path params + if($petId !== null) { + $resourcePath = str_replace("{" . "petId" . "}", + $this->apiClient->toPathValue($petId), $resourcePath); + } + + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + if(! $response) { + return null; + } + + $responseObject = $this->apiClient->deserialize($response, + 'Pet'); + return $responseObject; + } + + /** + * updatePetWithForm + * + * Updates a pet in the store with form data + * petId, string: ID of pet that needs to be updated (required) + * * name, string: Updated name of the pet (required) + * * status, string: Updated status of the pet (required) + * + * @return + */ + + public function updatePetWithForm($petId, $name, $status) { + + // parse inputs + $resourcePath = "/pet/{petId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + + + // path params + if($petId !== null) { + $resourcePath = str_replace("{" . "petId" . "}", + $this->apiClient->toPathValue($petId), $resourcePath); + } + + if ($name !== null) { + $formParams[name] = $name; + } + if ($status !== null) { + $formParams[status] = $status; + } + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + + } + + /** + * deletePet + * + * Deletes a pet + * api_key, string: (required) + * * petId, int: Pet id to delete (required) + * + * @return + */ + + public function deletePet($api_key, $petId) { + + // parse inputs + $resourcePath = "/pet/{petId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "DELETE"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; + + + // header params + if($api_key !== null) { + $headerParams['api_key'] = $this->apiClient->toHeaderValue($api_key); + } + // path params + if($petId !== null) { + $resourcePath = str_replace("{" . "petId" . "}", + $this->apiClient->toPathValue($petId), $resourcePath); + } + + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + + } + + /** + * uploadFile + * + * uploads an image + * petId, int: ID of pet to update (required) + * * additionalMetadata, string: Additional data to pass to server (required) + * * file, file: file to upload (required) + * + * @return + */ + + public function uploadFile($petId, $additionalMetadata, $file) { + + // parse inputs + $resourcePath = "/pet/{petId}/uploadImage"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = 'multipart/form-data'; + + + + // path params + if($petId !== null) { + $resourcePath = str_replace("{" . "petId" . "}", + $this->apiClient->toPathValue($petId), $resourcePath); + } + + if ($additionalMetadata !== null) { + $formParams[additionalMetadata] = $additionalMetadata; + } + if ($file !== null) { + $formParams[file] = '@' . $file; + } + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + + } } - diff --git a/samples/client/petstore/php/StoreApi.php b/samples/client/petstore/php/StoreApi.php index 89e5812c2a0a..0496c08d2e8c 100644 --- a/samples/client/petstore/php/StoreApi.php +++ b/samples/client/petstore/php/StoreApi.php @@ -1,6 +1,6 @@ apiClient = $apiClient; } - /** - * getOrderById - * Find purchase order by ID - * orderId, string: ID of pet that needs to be fetched (required) - - * @return Order + + /** + * getInventory + * + * Returns pet inventories by status + + * @return map[string,int] */ - public function getOrderById($orderId) { + public function getInventory() { - //parse inputs - $resourcePath = "/store/order/{orderId}"; + // parse inputs + $resourcePath = "/store/inventory"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; - if($orderId != null) { - $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->toPathValue($orderId), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; + + + + + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); } + + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $body, $headerParams); - - if(! $response){ - return null; - } + if(! $response) { + return null; + } $responseObject = $this->apiClient->deserialize($response, - 'Order'); + 'map[string,int]'); return $responseObject; - - } - /** - * deleteOrder - * Delete purchase order by ID - * orderId, string: ID of the order that needs to be deleted (required) - - * @return - */ - - public function deleteOrder($orderId) { - - //parse inputs - $resourcePath = "/store/order/{orderId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($orderId != null) { - $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->toPathValue($orderId), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - /** + } + + /** * placeOrder + * * Place an order for a pet * body, Order: order placed for purchasing the pet (required) - - * @return + * + * @return Order */ public function placeOrder($body) { - //parse inputs + // parse inputs $resourcePath = "/store/order"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "POST"; $queryParams = array(); $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; - //make the API Call - if (! isset($body)) { - $body = null; + + + + + // body params + $body = null; + if (isset($body)) { + $body = $body; } + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $body, $headerParams); - + if(! $response) { + return null; } + + $responseObject = $this->apiClient->deserialize($response, + 'Order'); + return $responseObject; + } + + /** + * getOrderById + * + * Find purchase order by ID + * orderId, string: ID of pet that needs to be fetched (required) + * + * @return Order + */ + + public function getOrderById($orderId) { + + // parse inputs + $resourcePath = "/store/order/{orderId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; + + + + // path params + if($orderId !== null) { + $resourcePath = str_replace("{" . "orderId" . "}", + $this->apiClient->toPathValue($orderId), $resourcePath); + } + + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + if(! $response) { + return null; + } + + $responseObject = $this->apiClient->deserialize($response, + 'Order'); + return $responseObject; + } + + /** + * deleteOrder + * + * Delete purchase order by ID + * orderId, string: ID of the order that needs to be deleted (required) + * + * @return + */ + + public function deleteOrder($orderId) { + + // parse inputs + $resourcePath = "/store/order/{orderId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "DELETE"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; + + + + // path params + if($orderId !== null) { + $resourcePath = str_replace("{" . "orderId" . "}", + $this->apiClient->toPathValue($orderId), $resourcePath); + } + + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + + } } - diff --git a/samples/client/petstore/php/Swagger.php b/samples/client/petstore/php/Swagger.php index 088f601489c7..a7a18866345d 100644 --- a/samples/client/petstore/php/Swagger.php +++ b/samples/client/petstore/php/Swagger.php @@ -1,128 +1,149 @@ apiKey = $apiKey; - $this->apiServer = $apiServer; - } + /** + * @param string $host the address of the API server + * @param string $headerName a header to pass on requests + */ + function __construct($host, $headerName = null, $headerValue = null) { + $this->host = $host; + $this->headerName = $headerName; + $this->headerValue = $headerValue; + } + + /** + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + */ + public function setTimeout($seconds) { + if (!is_numeric($seconds)) { + throw new Exception('Timeout variable must be numeric.'); + } + $this->curl_timout = $seconds; + } - /** - * @param string $resourcePath path to method endpoint - * @param string $method method to call - * @param array $queryParams parameters to be place in query URL - * @param array $postData parameters to be placed in POST body - * @param array $headerParams parameters to be place in request header - * @return mixed - */ - public function callAPI($resourcePath, $method, $queryParams, $postData, - $headerParams) { + /** + * @param string $resourcePath path to method endpoint + * @param string $method method to call + * @param array $queryParams parameters to be place in query URL + * @param array $postData parameters to be placed in POST body + * @param array $headerParams parameters to be place in request header + * @return mixed + */ + public function callAPI($resourcePath, $method, $queryParams, $postData, + $headerParams) { - $headers = array(); + $headers = array(); - # Allow API key from $headerParams to override default - $added_api_key = False; - if ($headerParams != null) { - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - if ($key == 'api_key') { - $added_api_key = True; - } - } - } - if (! $added_api_key) { - $headers[] = "api_key: " . $this->apiKey; - } + # Allow API key from $headerParams to override default + $added_api_key = False; + if ($headerParams != null) { + foreach ($headerParams as $key => $val) { + $headers[] = "$key: $val"; + if ($key == $this->headerName) { + $added_api_key = True; + } + } + } + if (! $added_api_key && $this->headerName != null) { + $headers[] = $this->headerName . ": " . $this->headerValue; + } - if (is_object($postData) or is_array($postData)) { - $postData = json_encode($this->sanitizeForSerialization($postData)); - } + if (strpos($headers['Content-Type'], "multipart/form-data") < 0 and (is_object($postData) or is_array($postData))) { + $postData = json_encode($this->sanitizeForSerialization($postData)); + } - $url = $this->apiServer . $resourcePath; + $url = $this->host . $resourcePath; - $curl = curl_init(); - curl_setopt($curl, CURLOPT_TIMEOUT, 5); - // return the result on success, rather than just TRUE - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); + $curl = curl_init(); + if ($this->curl_timout) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->curl_timout); + } + // return the result on success, rather than just TRUE + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - if (! empty($queryParams)) { - $url = ($url . '?' . http_build_query($queryParams)); - } + if (! empty($queryParams)) { + $url = ($url . '?' . http_build_query($queryParams)); + } - if ($method == self::$POST) { - curl_setopt($curl, CURLOPT_POST, true); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PUT) { - $json_data = json_encode($postData); - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method != self::$GET) { - throw new Exception('Method ' . $method . ' is not recognized.'); - } - curl_setopt($curl, CURLOPT_URL, $url); + if ($method == self::$POST) { + curl_setopt($curl, CURLOPT_POST, true); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$PUT) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$DELETE) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method != self::$GET) { + throw new Exception('Method ' . $method . ' is not recognized.'); + } + curl_setopt($curl, CURLOPT_URL, $url); - // Make the request - $response = curl_exec($curl); - $response_info = curl_getinfo($curl); + // Make the request + $response = curl_exec($curl); + $response_info = curl_getinfo($curl); - // Handle the response - if ($response_info['http_code'] == 0) { - throw new Exception("TIMEOUT: api call to " . $url . - " took more than 5s to return" ); - } else if ($response_info['http_code'] == 200) { - $data = json_decode($response); - } else if ($response_info['http_code'] == 401) { - throw new Exception("Unauthorized API request to " . $url . - ": ".json_decode($response)->message ); - } else if ($response_info['http_code'] == 404) { - $data = null; - } else { - throw new Exception("Can't connect to the api: " . $url . - " response code: " . - $response_info['http_code']); - } + // Handle the response + if ($response_info['http_code'] == 0) { + throw new Exception("TIMEOUT: api call to " . $url . + " took more than 5s to return" ); + } else if ($response_info['http_code'] == 200) { + $data = json_decode($response); + } else if ($response_info['http_code'] == 401) { + throw new Exception("Unauthorized API request to " . $url . + ": ".json_decode($response)->message ); + } else if ($response_info['http_code'] == 404) { + $data = null; + } else { + throw new Exception("Can't connect to the api: " . $url . + " response code: " . + $response_info['http_code']); + } + return $data; + } - return $data; - } - - /** - * Build a JSON POST object - */ + /** + * Build a JSON POST object + */ protected function sanitizeForSerialization($data) { if (is_scalar($data) || null === $data) { @@ -147,41 +168,41 @@ class APIClient { return $sanitized; } - /** - * Take value and turn it into a string suitable for inclusion in - * the path, by url-encoding. - * @param string $value a string which will be part of the path - * @return string the serialized object - */ - public static function toPathValue($value) { - return rawurlencode($value); - } + /** + * Take value and turn it into a string suitable for inclusion in + * the path, by url-encoding. + * @param string $value a string which will be part of the path + * @return string the serialized object + */ + public static function toPathValue($value) { + return rawurlencode($value); + } - /** - * Take value and turn it into a string suitable for inclusion in - * the query, by imploding comma-separated if it's an object. - * If it's a string, pass through unchanged. It will be url-encoded - * later. - * @param object $object an object to be serialized to a string - * @return string the serialized object - */ - public static function toQueryValue($object) { + /** + * Take value and turn it into a string suitable for inclusion in + * the query, by imploding comma-separated if it's an object. + * If it's a string, pass through unchanged. It will be url-encoded + * later. + * @param object $object an object to be serialized to a string + * @return string the serialized object + */ + public static function toQueryValue($object) { if (is_array($object)) { return implode(',', $object); } else { return $object; } - } + } - /** - * Just pass through the header value for now. Placeholder in case we - * find out we need to do something with header values. - * @param string $value a string which will be part of the header - * @return string the header string - */ - public static function toHeaderValue($value) { - return $value; - } + /** + * Just pass through the header value for now. Placeholder in case we + * find out we need to do something with header values. + * @param string $value a string which will be part of the header + * @return string the header string + */ + public static function toHeaderValue($value) { + return $value; + } /** * Deserialize a JSON string into an object @@ -195,10 +216,20 @@ class APIClient { { if (null === $data) { $deserialized = null; - } else if (substr($class, 0, 6) == 'array[') { + } elseif (substr($class, 0, 4) == 'map[') { + $inner = substr($class, 4, -1); + $values = array(); + if(strrpos($inner, ",") !== false) { + $subClass = explode(',', $inner, 2)[1]; + foreach ($data as $key => $value) { + $values[] = array($key => self::deserialize($value, $subClass)); + } + } + $deserialized = $values; + } elseif (substr($class, 0, 6) == 'array[') { $subClass = substr($class, 6, -1); $values = array(); - foreach ($data as $value) { + foreach ($data as $key => $value) { $values[] = self::deserialize($value, $subClass); } $deserialized = $values; @@ -222,4 +253,3 @@ class APIClient { } - diff --git a/samples/client/petstore/php/UserApi.php b/samples/client/petstore/php/UserApi.php index 87626f09e0ff..697af96328b3 100644 --- a/samples/client/petstore/php/UserApi.php +++ b/samples/client/petstore/php/UserApi.php @@ -1,6 +1,6 @@ apiClient = $apiClient; } - /** - * updateUser - * Updated user - * username, string: name that need to be deleted (required) - - * body, User: Updated user object (required) - - * @return - */ - - public function updateUser($username, $body) { - - //parse inputs - $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "PUT"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($username != null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - /** - * deleteUser - * Delete user - * username, string: The name that needs to be deleted (required) - - * @return - */ - - public function deleteUser($username) { - - //parse inputs - $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($username != null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - /** - * getUserByName - * Get user by user name - * username, string: The name that needs to be fetched. Use user1 for testing. (required) - - * @return User - */ - - public function getUserByName($username) { - - //parse inputs - $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($username != null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'User'); - return $responseObject; - - } - /** - * loginUser - * Logs user into the system - * username, string: The user name for login (required) - - * password, string: The password for login in clear text (required) - - * @return string - */ - - public function loginUser($username, $password) { - - //parse inputs - $resourcePath = "/user/login"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($username != null) { - $queryParams['username'] = $this->apiClient->toQueryValue($username); - } - if($password != null) { - $queryParams['password'] = $this->apiClient->toQueryValue($password); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'string'); - return $responseObject; - - } - /** - * logoutUser - * Logs out current logged in user session - * @return - */ - - public function logoutUser() { - - //parse inputs - $resourcePath = "/user/logout"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - /** + + /** * createUser + * * Create user * body, User: Created user object (required) - - * @return + * + * @return */ public function createUser($body) { - //parse inputs + // parse inputs $resourcePath = "/user"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "POST"; $queryParams = array(); $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; - //make the API Call - if (! isset($body)) { - $body = null; + + + + + // body params + $body = null; + if (isset($body)) { + $body = $body; } + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $body, $headerParams); - - } - /** + + } + + /** * createUsersWithArrayInput + * * Creates list of users with given input array * body, array[User]: List of user object (required) - - * @return + * + * @return */ public function createUsersWithArrayInput($body) { - //parse inputs + // parse inputs $resourcePath = "/user/createWithArray"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "POST"; $queryParams = array(); $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; - //make the API Call - if (! isset($body)) { - $body = null; + + + + + // body params + $body = null; + if (isset($body)) { + $body = $body; } + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $body, $headerParams); - - } - /** + + } + + /** * createUsersWithListInput - * Creates list of users with given list input + * + * Creates list of users with given input array * body, array[User]: List of user object (required) - - * @return + * + * @return */ public function createUsersWithListInput($body) { - //parse inputs + // parse inputs $resourcePath = "/user/createWithList"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "POST"; $queryParams = array(); $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; - //make the API Call - if (! isset($body)) { - $body = null; + + + + + // body params + $body = null; + if (isset($body)) { + $body = $body; } + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $body, $headerParams); + + } + + /** + * loginUser + * + * Logs user into the system + * username, string: The user name for login (required) + * * password, string: The password for login in clear text (required) + * + * @return string + */ + public function loginUser($username, $password) { + + // parse inputs + $resourcePath = "/user/login"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; + + // query params + if($username !== null) { + $queryParams['username'] = $this->apiClient->toQueryValue($username); + }// query params + if($password !== null) { + $queryParams['password'] = $this->apiClient->toQueryValue($password); + } + + + + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + if(! $response) { + return null; + } + + $responseObject = $this->apiClient->deserialize($response, + 'string'); + return $responseObject; + } + + /** + * logoutUser + * + * Logs out current logged in user session + + * @return + */ + + public function logoutUser() { + + // parse inputs + $resourcePath = "/user/logout"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; + + + + + + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + + } + + /** + * getUserByName + * + * Get user by user name + * username, string: The name that needs to be fetched. Use user1 for testing. (required) + * + * @return User + */ + + public function getUserByName($username) { + + // parse inputs + $resourcePath = "/user/{username}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; + + + + // path params + if($username !== null) { + $resourcePath = str_replace("{" . "username" . "}", + $this->apiClient->toPathValue($username), $resourcePath); + } + + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + if(! $response) { + return null; + } + + $responseObject = $this->apiClient->deserialize($response, + 'User'); + return $responseObject; + } + + /** + * updateUser + * + * Updated user + * username, string: name that need to be deleted (required) + * * body, User: Updated user object (required) + * + * @return + */ + + public function updateUser($username, $body) { + + // parse inputs + $resourcePath = "/user/{username}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "PUT"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; + + + + // path params + if($username !== null) { + $resourcePath = str_replace("{" . "username" . "}", + $this->apiClient->toPathValue($username), $resourcePath); + } + + // body params + $body = null; + if (isset($body)) { + $body = $body; + } + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + + } + + /** + * deleteUser + * + * Delete user + * username, string: The name that needs to be deleted (required) + * + * @return + */ + + public function deleteUser($username) { + + // parse inputs + $resourcePath = "/user/{username}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "DELETE"; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $headerParams['Accept'] = 'application/json,application/xml'; + $headerParams['Content-Type'] = ''; + + + + // path params + if($username !== null) { + $resourcePath = str_replace("{" . "username" . "}", + $this->apiClient->toPathValue($username), $resourcePath); + } + + + + $body = $body ?: $formParams; + + if (strpos($headerParams['Content-Type'], "application/x-www-form-urlencoded") > -1) { + $body = http_build_query($body); + } + + // make the API Call + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + + } } - diff --git a/samples/client/petstore/php/models/Category.php b/samples/client/petstore/php/models/Category.php index adb99943fa31..867cacf771af 100644 --- a/samples/client/petstore/php/models/Category.php +++ b/samples/client/petstore/php/models/Category.php @@ -1,6 +1,6 @@ 'int', 'name' => 'string' - ); - public $id; // int - public $name; // string - } - + + public $id; /* int */ + public $name; /* string */ +} diff --git a/samples/client/petstore/php/models/Order.php b/samples/client/petstore/php/models/Order.php index e0846bd1f73e..d5e10a59404c 100644 --- a/samples/client/petstore/php/models/Order.php +++ b/samples/client/petstore/php/models/Order.php @@ -1,6 +1,6 @@ 'int', 'petId' => 'int', 'quantity' => 'int', + 'shipDate' => 'DateTime', 'status' => 'string', - 'shipDate' => 'DateTime' - + 'complete' => 'boolean' ); - public $id; // int - public $petId; // int - public $quantity; // int + + public $id; /* int */ + public $petId; /* int */ + public $quantity; /* int */ + public $shipDate; /* DateTime */ /** * Order Status */ - public $status; // string - public $shipDate; // DateTime - } - + public $status; /* string */ + public $complete; /* boolean */ +} diff --git a/samples/client/petstore/php/models/Pet.php b/samples/client/petstore/php/models/Pet.php index ccdc86e0ee05..d3231bdc8af1 100644 --- a/samples/client/petstore/php/models/Pet.php +++ b/samples/client/petstore/php/models/Pet.php @@ -1,6 +1,6 @@ 'int', 'category' => 'Category', @@ -30,20 +30,16 @@ class Pet { 'photoUrls' => 'array[string]', 'tags' => 'array[Tag]', 'status' => 'string' - ); - /** - * unique identifier for the pet - */ - public $id; // int - public $category; // Category - public $name; // string - public $photoUrls; // array[string] - public $tags; // array[Tag] + + public $id; /* int */ + public $category; /* Category */ + public $name; /* string */ + public $photoUrls; /* array[string] */ + public $tags; /* array[Tag] */ /** * pet status in the store */ - public $status; // string - } - + public $status; /* string */ +} diff --git a/samples/client/petstore/php/models/Tag.php b/samples/client/petstore/php/models/Tag.php index 8550685e45e7..238d768e682d 100644 --- a/samples/client/petstore/php/models/Tag.php +++ b/samples/client/petstore/php/models/Tag.php @@ -1,6 +1,6 @@ 'int', 'name' => 'string' - ); - public $id; // int - public $name; // string - } - + + public $id; /* int */ + public $name; /* string */ +} diff --git a/samples/client/petstore/php/models/User.php b/samples/client/petstore/php/models/User.php index 85804deb74b4..6178042052bb 100644 --- a/samples/client/petstore/php/models/User.php +++ b/samples/client/petstore/php/models/User.php @@ -1,6 +1,6 @@ 'int', - 'firstName' => 'string', 'username' => 'string', + 'firstName' => 'string', 'lastName' => 'string', 'email' => 'string', 'password' => 'string', 'phone' => 'string', 'userStatus' => 'int' - ); - public $id; // int - public $firstName; // string - public $username; // string - public $lastName; // string - public $email; // string - public $password; // string - public $phone; // string + + public $id; /* int */ + public $username; /* string */ + public $firstName; /* string */ + public $lastName; /* string */ + public $email; /* string */ + public $password; /* string */ + public $phone; /* string */ /** * User Status */ - public $userStatus; // int - } - + public $userStatus; /* int */ +} diff --git a/samples/client/petstore/python/PythonPetstoreCodegen.scala b/samples/client/petstore/python/PythonPetstoreCodegen.scala deleted file mode 100644 index 9758c384453d..000000000000 --- a/samples/client/petstore/python/PythonPetstoreCodegen.scala +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicPythonGenerator - -import java.io.File - -object PythonPetstoreCodegen extends BasicPythonGenerator { - def main(args: Array[String]) = generateClient(args) - - override def destinationDir = "samples/client/petstore/python" - - override def supportingFiles = List( - ("__init__.mustache", destinationDir, "__init__.py"), - ("swagger.mustache", destinationDir + File.separator + apiPackage.getOrElse(""), "swagger.py"), - ("__init__.mustache", destinationDir + File.separator + modelPackage.getOrElse(""), "__init__.py")) -} diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md new file mode 100644 index 000000000000..cf1f7142bc06 --- /dev/null +++ b/samples/client/petstore/python/README.md @@ -0,0 +1,25 @@ +# Swagger Generated Python client + + +Usage example, based on the swagger petstore: + +```python +# include the client module +from client import * + +# build a client connection. In this example, we are passing the hostname as arg0, and +# sending a header with name `api_key` and value `special-key` on each call to the api. + +client = swagger.ApiClient('http://petstore.swagger.io/v2', 'api_key', 'special-key') + +# create the PetApi class with the client we just created +petApi = PetApi.PetApi(client) + +# call the API and fetch a pet, with petId=3 +pet = petApi.getPetById(petId=3) + +# write it into pretty JSON +json = client.sanitizeForSerialization(pet) +print json +{'category': {'category': None, 'status': None, 'name': 'string', 'tags': None, 'photoUrls': None, 'id': 0L}, 'status': {'category': None, 'status': None, 'name': None, 'tags': None, 'photoUrls': None, 'id': None}, 'name': 'foogly', 'tags': [{'id': 0L, 'name': 'string'}], 'photoUrls': ['string'], 'id': 3L} +``` diff --git a/samples/client/petstore/python/__init__.py b/samples/client/petstore/python/__init__.py deleted file mode 100644 index 39f84514fe91..000000000000 --- a/samples/client/petstore/python/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" -import os - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) - diff --git a/samples/client/petstore/python/PetApi.py b/samples/client/petstore/python/client/PetApi.py similarity index 63% rename from samples/client/petstore/python/PetApi.py rename to samples/client/petstore/python/client/PetApi.py index ef38b8eacd04..4b99f62a935f 100644 --- a/samples/client/petstore/python/PetApi.py +++ b/samples/client/petstore/python/client/PetApi.py @@ -1,7 +1,7 @@ #!/usr/bin/env python """ -WordAPI.py -Copyright 2014 Wordnik, Inc. +PetApi.py +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,265 +29,16 @@ class PetApi(object): self.apiClient = apiClient - - def getPetById(self, petId, **kwargs): - """Find pet by ID - - Args: - petId, long: ID of pet that needs to be fetched (required) - - - - Returns: Pet - """ - - allParams = ['petId'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getPetById" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('petId' in params): - replacement = str(self.apiClient.toPathValue(params['petId'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Pet') - return responseObject - - - - - def deletePet(self, petId, **kwargs): - """Deletes a pet - - Args: - petId, str: Pet id to delete (required) - - - - Returns: - """ - - allParams = ['petId'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method deletePet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - - if ('petId' in params): - replacement = str(self.apiClient.toPathValue(params['petId'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def partialUpdate(self, petId, body, **kwargs): - """partial updates to a pet - - Args: - petId, str: ID of pet that needs to be fetched (required) - - body, Pet: Pet object that needs to be added to the store (required) - - - - Returns: Array[Pet] - """ - - allParams = ['petId', 'body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method partialUpdate" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PATCH' - - queryParams = {} - headerParams = {} - - if ('petId' in params): - replacement = str(self.apiClient.toPathValue(params['petId'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Array[Pet]') - return responseObject - - - - - def updatePetWithForm(self, petId, **kwargs): - """Updates a pet in the store with form data - - Args: - petId, str: ID of pet that needs to be updated (required) - - name, str: Updated name of the pet (optional) - - status, str: Updated status of the pet (optional) - - - - Returns: - """ - - allParams = ['petId', 'name', 'status'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method updatePetWithForm" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - if ('petId' in params): - replacement = str(self.apiClient.toPathValue(params['petId'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def uploadFile(self, **kwargs): - """uploads an image - - Args: - additionalMetadata, str: Additional data to pass to server (optional) - - body, File: file to upload (optional) - - - - Returns: - """ - - allParams = ['additionalMetadata', 'body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method uploadFile" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/uploadImage' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def addPet(self, body, **kwargs): - """Add a new pet to the store - - Args: - body, Pet: Pet object that needs to be added to the store (required) - - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method addPet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def updatePet(self, body, **kwargs): + + def updatePet(self, **kwargs): """Update an existing pet Args: - body, Pet: Pet object that needs to be updated in the store (required) - - + body, Pet: Pet object that needs to be added to the store (required) + + + Returns: """ @@ -306,25 +57,101 @@ class PetApi(object): queryParams = {} headerParams = {} + formParams = {} + files = {} + bodyParam = None - postData = (params['body'] if 'body' in params else None) + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = 'application/json,application/xml'; + + + + + + + + + + + if ('body' in params): + bodyParam = params['body'] + + + postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) + postData, headerParams, files=files) + + + + + + def addPet(self, **kwargs): + """Add a new pet to the store + + Args: + + body, Pet: Pet object that needs to be added to the store (required) + + + + Returns: + """ + + allParams = ['body'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method addPet" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'POST' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = 'application/json,application/xml'; - def findPetsByStatus(self, status= None, **kwargs): + + + + + + if ('body' in params): + bodyParam = params['body'] + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + + + + def findPetsByStatus(self, **kwargs): """Finds Pets by status Args: - status, str: Status values that need to be considered for filter (required) - - - Returns: Array[Pet] + status, list[str]: Status values that need to be considered for filter (required) + + + + Returns: list[Pet] """ allParams = ['status'] @@ -342,32 +169,51 @@ class PetApi(object): queryParams = {} headerParams = {} + formParams = {} + files = {} + bodyParam = None + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + if ('status' in params): queryParams['status'] = self.apiClient.toPathValue(params['status']) - postData = (params['body'] if 'body' in params else None) + + + + + + + + + + + postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) + postData, headerParams, files=files) + if not response: return None - responseObject = self.apiClient.deserialize(response, 'Array[Pet]') + responseObject = self.apiClient.deserialize(response, 'list[Pet]') return responseObject - - - def findPetsByTags(self, tags, **kwargs): + + + def findPetsByTags(self, **kwargs): """Finds Pets by tags Args: - tags, str: Tags to filter by (required) - - - Returns: Array[Pet] + tags, list[str]: Tags to filter by (required) + + + + Returns: list[Pet] """ allParams = ['tags'] @@ -385,25 +231,308 @@ class PetApi(object): queryParams = {} headerParams = {} + formParams = {} + files = {} + bodyParam = None + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + if ('tags' in params): queryParams['tags'] = self.apiClient.toPathValue(params['tags']) - postData = (params['body'] if 'body' in params else None) + + + + + + + + + + + postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) + postData, headerParams, files=files) + if not response: return None - responseObject = self.apiClient.deserialize(response, 'Array[Pet]') + responseObject = self.apiClient.deserialize(response, 'list[Pet]') return responseObject + + + + def getPetById(self, **kwargs): + """Find pet by ID + + Args: + + petId, long: ID of pet that needs to be fetched (required) + + + + Returns: Pet + """ + + allParams = ['petId'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method getPetById" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/{petId}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'GET' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + if ('petId' in params): + replacement = str(self.apiClient.toPathValue(params['petId'])) + resourcePath = resourcePath.replace('{' + 'petId' + '}', + replacement) + + + + + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + if not response: + return None + + responseObject = self.apiClient.deserialize(response, 'Pet') + return responseObject + + + + + def updatePetWithForm(self, **kwargs): + """Updates a pet in the store with form data + + Args: + + petId, str: ID of pet that needs to be updated (required) + + + name, str: Updated name of the pet (required) + + + status, str: Updated status of the pet (required) + + + + Returns: + """ + + allParams = ['petId', 'name', 'status'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method updatePetWithForm" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/{petId}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'POST' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + + + + + + if ('petId' in params): + replacement = str(self.apiClient.toPathValue(params['petId'])) + resourcePath = resourcePath.replace('{' + 'petId' + '}', + replacement) + + + + if ('name' in params): + formParams['name'] = params['name'] + + if ('status' in params): + formParams['status'] = params['status'] + + + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + + + + def deletePet(self, **kwargs): + """Deletes a pet + + Args: + + api_key, str: (required) + + + petId, long: Pet id to delete (required) + + + + Returns: + """ + + allParams = ['api_key', 'petId'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method deletePet" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/{petId}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'DELETE' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + if ('api_key' in params): + headerParams['api_key'] = params['api_key'] + + + + if ('petId' in params): + replacement = str(self.apiClient.toPathValue(params['petId'])) + resourcePath = resourcePath.replace('{' + 'petId' + '}', + replacement) + + + + + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + + + + def uploadFile(self, **kwargs): + """uploads an image + + Args: + + petId, long: ID of pet to update (required) + + + additionalMetadata, str: Additional data to pass to server (required) + + + file, file: file to upload (required) + + + + Returns: + """ + + allParams = ['petId', 'additionalMetadata', 'file'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method uploadFile" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/{petId}/uploadImage' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'POST' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = 'multipart/form-data'; + + + + + + + if ('petId' in params): + replacement = str(self.apiClient.toPathValue(params['petId'])) + resourcePath = resourcePath.replace('{' + 'petId' + '}', + replacement) + + + + if ('additionalMetadata' in params): + formParams['additionalMetadata'] = params['additionalMetadata'] + + if ('file' in params): + files['file'] = params['file'] + + + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + + - - diff --git a/samples/client/petstore/python/StoreApi.py b/samples/client/petstore/python/client/StoreApi.py similarity index 58% rename from samples/client/petstore/python/StoreApi.py rename to samples/client/petstore/python/client/StoreApi.py index 547aed42ba90..f47a4408cbb0 100644 --- a/samples/client/petstore/python/StoreApi.py +++ b/samples/client/petstore/python/client/StoreApi.py @@ -1,7 +1,7 @@ #!/usr/bin/env python """ -WordAPI.py -Copyright 2014 Wordnik, Inc. +StoreApi.py +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,15 +29,134 @@ class StoreApi(object): self.apiClient = apiClient + + def getInventory(self, **kwargs): + """Returns pet inventories by status - def getOrderById(self, orderId, **kwargs): + Args: + + + Returns: map(String, int) + """ + + allParams = [] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method getInventory" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/store/inventory' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'GET' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + + + + + + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + if not response: + return None + + responseObject = self.apiClient.deserialize(response, 'map(String, int)') + return responseObject + + + + + def placeOrder(self, **kwargs): + """Place an order for a pet + + Args: + + body, Order: order placed for purchasing the pet (required) + + + + Returns: Order + """ + + allParams = ['body'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method placeOrder" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/store/order' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'POST' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + + + + + + + if ('body' in params): + bodyParam = params['body'] + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + if not response: + return None + + responseObject = self.apiClient.deserialize(response, 'Order') + return responseObject + + + + + def getOrderById(self, **kwargs): """Find purchase order by ID Args: - orderId, str: ID of pet that needs to be fetched (required) - - + orderId, str: ID of pet that needs to be fetched (required) + + + Returns: Order """ @@ -56,33 +175,52 @@ class StoreApi(object): queryParams = {} headerParams = {} + formParams = {} + files = {} + bodyParam = None + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + + if ('orderId' in params): replacement = str(self.apiClient.toPathValue(params['orderId'])) resourcePath = resourcePath.replace('{' + 'orderId' + '}', replacement) - postData = (params['body'] if 'body' in params else None) + + + + + + + postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) + postData, headerParams, files=files) + if not response: return None responseObject = self.apiClient.deserialize(response, 'Order') return responseObject - - - def deleteOrder(self, orderId, **kwargs): + + + def deleteOrder(self, **kwargs): """Delete purchase order by ID Args: - orderId, str: ID of the order that needs to be deleted (required) - - + orderId, str: ID of the order that needs to be deleted (required) + + + Returns: """ @@ -101,58 +239,36 @@ class StoreApi(object): queryParams = {} headerParams = {} + formParams = {} + files = {} + bodyParam = None + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + + if ('orderId' in params): replacement = str(self.apiClient.toPathValue(params['orderId'])) resourcePath = resourcePath.replace('{' + 'orderId' + '}', replacement) - postData = (params['body'] if 'body' in params else None) + + + + + + + postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) + postData, headerParams, files=files) - - - def placeOrder(self, body, **kwargs): - """Place an order for a pet - - Args: - body, Order: order placed for purchasing the pet (required) - - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method placeOrder" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - diff --git a/samples/client/petstore/python/UserApi.py b/samples/client/petstore/python/client/UserApi.py similarity index 70% rename from samples/client/petstore/python/UserApi.py rename to samples/client/petstore/python/client/UserApi.py index 522ec36295e1..a357b785c574 100644 --- a/samples/client/petstore/python/UserApi.py +++ b/samples/client/petstore/python/client/UserApi.py @@ -1,7 +1,7 @@ #!/usr/bin/env python """ -WordAPI.py -Copyright 2014 Wordnik, Inc. +UserApi.py +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -29,223 +29,16 @@ class UserApi(object): self.apiClient = apiClient - - def updateUser(self, username, body, **kwargs): - """Updated user - - Args: - username, str: name that need to be deleted (required) - - body, User: Updated user object (required) - - - - Returns: - """ - - allParams = ['username', 'body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method updateUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PUT' - - queryParams = {} - headerParams = {} - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def deleteUser(self, username, **kwargs): - """Delete user - - Args: - username, str: The name that needs to be deleted (required) - - - - Returns: - """ - - allParams = ['username'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method deleteUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def getUserByName(self, username, **kwargs): - """Get user by user name - - Args: - username, str: The name that needs to be fetched. Use user1 for testing. (required) - - - - Returns: User - """ - - allParams = ['username'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getUserByName" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'User') - return responseObject - - - - - def loginUser(self, username, password, **kwargs): - """Logs user into the system - - Args: - username, str: The user name for login (required) - - password, str: The password for login in clear text (required) - - - - Returns: str - """ - - allParams = ['username', 'password'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method loginUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/login' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('username' in params): - queryParams['username'] = self.apiClient.toPathValue(params['username']) - if ('password' in params): - queryParams['password'] = self.apiClient.toPathValue(params['password']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'str') - return responseObject - - - - - def logoutUser(self, **kwargs): - """Logs out current logged in user session - - Args: - - - Returns: - """ - - allParams = [] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method logoutUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/logout' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def createUser(self, body, **kwargs): + + def createUser(self, **kwargs): """Create user Args: - body, User: Created user object (required) - - + body, User: Created user object (required) + + + Returns: """ @@ -264,24 +57,44 @@ class UserApi(object): queryParams = {} headerParams = {} + formParams = {} + files = {} + bodyParam = None - postData = (params['body'] if 'body' in params else None) + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + + + + + + + if ('body' in params): + bodyParam = params['body'] + + + postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) + postData, headerParams, files=files) - - - def createUsersWithArrayInput(self, body, **kwargs): + + + def createUsersWithArrayInput(self, **kwargs): """Creates list of users with given input array Args: - body, list[User]: List of user object (required) - - + body, list[User]: List of user object (required) + + + Returns: """ @@ -300,24 +113,44 @@ class UserApi(object): queryParams = {} headerParams = {} + formParams = {} + files = {} + bodyParam = None - postData = (params['body'] if 'body' in params else None) + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + + + + + + + if ('body' in params): + bodyParam = params['body'] + + + postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) + postData, headerParams, files=files) - - - def createUsersWithListInput(self, body, **kwargs): - """Creates list of users with given list input + + + def createUsersWithListInput(self, **kwargs): + """Creates list of users with given input array Args: - body, list[User]: List of user object (required) - - + body, list[User]: List of user object (required) + + + Returns: """ @@ -336,18 +169,338 @@ class UserApi(object): queryParams = {} headerParams = {} + formParams = {} + files = {} + bodyParam = None - postData = (params['body'] if 'body' in params else None) + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + + + + + + + if ('body' in params): + bodyParam = params['body'] + + + postData = (formParams if formParams else bodyParam) response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) + postData, headerParams, files=files) + + + + + + def loginUser(self, **kwargs): + """Logs user into the system + + Args: + + username, str: The user name for login (required) + + + password, str: The password for login in clear text (required) + + + + Returns: str + """ + + allParams = ['username', 'password'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method loginUser" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/user/login' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'GET' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + if ('username' in params): + queryParams['username'] = self.apiClient.toPathValue(params['username']) + + if ('password' in params): + queryParams['password'] = self.apiClient.toPathValue(params['password']) + + + + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + if not response: + return None + + responseObject = self.apiClient.deserialize(response, 'str') + return responseObject + + + + + def logoutUser(self, **kwargs): + """Logs out current logged in user session + + Args: + + + Returns: + """ + + allParams = [] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method logoutUser" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/user/logout' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'GET' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + + + + + + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + + + + def getUserByName(self, **kwargs): + """Get user by user name + + Args: + + username, str: The name that needs to be fetched. Use user1 for testing. (required) + + + + Returns: User + """ + + allParams = ['username'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method getUserByName" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/user/{username}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'GET' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + + + if ('username' in params): + replacement = str(self.apiClient.toPathValue(params['username'])) + resourcePath = resourcePath.replace('{' + 'username' + '}', + replacement) + + + + + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + if not response: + return None + + responseObject = self.apiClient.deserialize(response, 'User') + return responseObject + + + + + def updateUser(self, **kwargs): + """Updated user + + Args: + + username, str: name that need to be deleted (required) + + + body, User: Updated user object (required) + + + + Returns: + """ + + allParams = ['username', 'body'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method updateUser" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/user/{username}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'PUT' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + + + if ('username' in params): + replacement = str(self.apiClient.toPathValue(params['username'])) + resourcePath = resourcePath.replace('{' + 'username' + '}', + replacement) + + + + + + if ('body' in params): + bodyParam = params['body'] + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + + + + def deleteUser(self, **kwargs): + """Delete user + + Args: + + username, str: The name that needs to be deleted (required) + + + + Returns: + """ + + allParams = ['username'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method deleteUser" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/user/{username}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'DELETE' + + queryParams = {} + headerParams = {} + formParams = {} + files = {} + bodyParam = None + + headerParams['Accept'] = 'application/json,application/xml'; + headerParams['Content-Type'] = ''; + + + + + + + if ('username' in params): + replacement = str(self.apiClient.toPathValue(params['username'])) + resourcePath = resourcePath.replace('{' + 'username' + '}', + replacement) + + + + + + + postData = (formParams if formParams else bodyParam) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams, files=files) + + + + - - diff --git a/samples/client/wordnik-api/python/wordnik/models/__init__.py b/samples/client/petstore/python/client/__init__.py similarity index 63% rename from samples/client/wordnik-api/python/wordnik/models/__init__.py rename to samples/client/petstore/python/client/__init__.py index 39f84514fe91..728aacbb9ab6 100644 --- a/samples/client/wordnik-api/python/wordnik/models/__init__.py +++ b/samples/client/petstore/python/client/__init__.py @@ -5,6 +5,5 @@ import os __all__ = [] for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) - + if module != '__init__.py' and module[-3:] == '.py': + __all__.append(module[:-3]) diff --git a/samples/client/petstore/python/models/Category.py b/samples/client/petstore/python/client/models/Category.py similarity index 87% rename from samples/client/petstore/python/models/Category.py rename to samples/client/petstore/python/client/models/Category.py index 73238af39d22..245397c3f1b6 100644 --- a/samples/client/petstore/python/models/Category.py +++ b/samples/client/petstore/python/client/models/Category.py @@ -1,6 +1,6 @@ #!/usr/bin/env python """ -Copyright 2014 Wordnik, Inc. +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,6 +14,7 @@ Copyright 2014 Wordnik, Inc. See the License for the specific language governing permissions and limitations under the License. """ + class Category: """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" @@ -21,12 +22,19 @@ class Category: def __init__(self): self.swaggerTypes = { + 'id': 'long', + + 'name': 'str' - + } + + self.id = None # long + + self.name = None # str diff --git a/samples/client/petstore/python/models/Order.py b/samples/client/petstore/python/client/models/Order.py similarity index 70% rename from samples/client/petstore/python/models/Order.py rename to samples/client/petstore/python/client/models/Order.py index 24e43faad5fb..60bbc0f99131 100644 --- a/samples/client/petstore/python/models/Order.py +++ b/samples/client/petstore/python/client/models/Order.py @@ -1,6 +1,6 @@ #!/usr/bin/env python """ -Copyright 2014 Wordnik, Inc. +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,6 +14,7 @@ Copyright 2014 Wordnik, Inc. See the License for the specific language governing permissions and limitations under the License. """ + class Order: """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" @@ -21,19 +22,44 @@ class Order: def __init__(self): self.swaggerTypes = { + 'id': 'long', + + 'petId': 'long', + + 'quantity': 'int', + + + 'shipDate': 'DateTime', + + 'status': 'str', - 'shipDate': 'datetime' - + + + 'complete': 'bool' + } - self.id = None # long - self.petId = None # long - self.quantity = None # int - #Order Status - self.status = None # str - self.shipDate = None # datetime + + + self.id = None # long + + + self.petId = None # long + + + self.quantity = None # int + + + self.shipDate = None # DateTime + + #Order Status + + self.status = None # str + + + self.complete = None # bool diff --git a/samples/client/petstore/python/models/Pet.py b/samples/client/petstore/python/client/models/Pet.py similarity index 80% rename from samples/client/petstore/python/models/Pet.py rename to samples/client/petstore/python/client/models/Pet.py index 441285951e6b..c4f024b996c5 100644 --- a/samples/client/petstore/python/models/Pet.py +++ b/samples/client/petstore/python/client/models/Pet.py @@ -1,6 +1,6 @@ #!/usr/bin/env python """ -Copyright 2014 Wordnik, Inc. +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,6 +14,7 @@ Copyright 2014 Wordnik, Inc. See the License for the specific language governing permissions and limitations under the License. """ + class Pet: """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" @@ -21,22 +22,44 @@ class Pet: def __init__(self): self.swaggerTypes = { + 'id': 'long', + + 'category': 'Category', + + 'name': 'str', + + 'photoUrls': 'list[str]', + + 'tags': 'list[Tag]', + + 'status': 'str' - + } - #unique identifier for the pet + + self.id = None # long + + self.category = None # Category + + self.name = None # str + + self.photoUrls = None # list[str] + + self.tags = None # list[Tag] + #pet status in the store + self.status = None # str diff --git a/samples/client/petstore/python/models/Tag.py b/samples/client/petstore/python/client/models/Tag.py similarity index 87% rename from samples/client/petstore/python/models/Tag.py rename to samples/client/petstore/python/client/models/Tag.py index 39a54101adb2..bd565e2bab3b 100644 --- a/samples/client/petstore/python/models/Tag.py +++ b/samples/client/petstore/python/client/models/Tag.py @@ -1,6 +1,6 @@ #!/usr/bin/env python """ -Copyright 2014 Wordnik, Inc. +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,6 +14,7 @@ Copyright 2014 Wordnik, Inc. See the License for the specific language governing permissions and limitations under the License. """ + class Tag: """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" @@ -21,12 +22,19 @@ class Tag: def __init__(self): self.swaggerTypes = { + 'id': 'long', + + 'name': 'str' - + } + + self.id = None # long + + self.name = None # str diff --git a/samples/client/petstore/python/models/User.py b/samples/client/petstore/python/client/models/User.py similarity index 77% rename from samples/client/petstore/python/models/User.py rename to samples/client/petstore/python/client/models/User.py index 7779cd618eb0..81466c88530f 100644 --- a/samples/client/petstore/python/models/User.py +++ b/samples/client/petstore/python/client/models/User.py @@ -1,6 +1,6 @@ #!/usr/bin/env python """ -Copyright 2014 Wordnik, Inc. +Copyright 2015 Reverb Technologies, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,6 +14,7 @@ Copyright 2014 Wordnik, Inc. See the License for the specific language governing permissions and limitations under the License. """ + class User: """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" @@ -21,25 +22,56 @@ class User: def __init__(self): self.swaggerTypes = { + 'id': 'long', - 'firstName': 'str', + + 'username': 'str', + + + 'firstName': 'str', + + 'lastName': 'str', + + 'email': 'str', + + 'password': 'str', + + 'phone': 'str', + + 'userStatus': 'int' - + } + + self.id = None # long - self.firstName = None # str + + self.username = None # str + + + self.firstName = None # str + + self.lastName = None # str + + self.email = None # str + + self.password = None # str + + self.phone = None # str + #User Status + self.userStatus = None # int diff --git a/samples/client/wordnik-api/python/wordnik/__init__.py b/samples/client/petstore/python/client/models/__init__.py similarity index 63% rename from samples/client/wordnik-api/python/wordnik/__init__.py rename to samples/client/petstore/python/client/models/__init__.py index 39f84514fe91..728aacbb9ab6 100644 --- a/samples/client/wordnik-api/python/wordnik/__init__.py +++ b/samples/client/petstore/python/client/models/__init__.py @@ -5,6 +5,5 @@ import os __all__ = [] for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) - + if module != '__init__.py' and module[-3:] == '.py': + __all__.append(module[:-3]) diff --git a/samples/client/petstore/python/client/swagger.py b/samples/client/petstore/python/client/swagger.py new file mode 100644 index 000000000000..8d9053025d12 --- /dev/null +++ b/samples/client/petstore/python/client/swagger.py @@ -0,0 +1,246 @@ +#!/usr/bin/env python +"""Swagger generic API client. This client handles the client- +server communication, and is invariant across implementations. Specifics of +the methods and models for each application are generated from the Swagger +templates.""" + +import sys +import os +import re +import urllib +import urllib2 +import httplib +import json +import datetime +import mimetypes +import random +import string + +from models import * + + +class ApiClient: + """Generic API client for Swagger client library builds + + Attributes: + host: The base path for the server to call + headerName: a header to pass when making calls to the API + headerValue: a header value to pass when making calls to the API + """ + def __init__(self, host=None, headerName=None, headerValue=None): + self.headerName = headerName + self.headerValue = headerValue + self.host = host + self.cookie = None + self.boundary = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(30)) + + def callAPI(self, resourcePath, method, queryParams, postData, + headerParams=None, files=None): + + url = self.host + resourcePath + headers = {} + if headerParams: + for param, value in headerParams.iteritems(): + headers[param] = value + + if self.headerName: + headers[self.headerName] = self.headerValue + + if self.cookie: + headers['Cookie'] = self.cookie + + data = None + + if queryParams: + # Need to remove None values, these should not be sent + sentQueryParams = {} + for param, value in queryParams.items(): + if value != None: + sentQueryParams[param] = value + url = url + '?' + urllib.urlencode(sentQueryParams) + + if method in ['GET']: + #Options to add statements later on and for compatibility + pass + + elif method in ['POST', 'PUT', 'DELETE']: + if postData: + postData = self.sanitizeForSerialization(postData) + if 'Content-type' not in headers: + headers['Content-type'] = 'application/json' + data = json.dumps(postData) + elif headers['Content-type'] == 'multipart/form-data': + data = self.buildMultipartFormData(postData, files) + headers['Content-type'] = 'multipart/form-data; boundary={0}'.format(self.boundary) + headers['Content-length'] = str(len(data)) + else: + data = urllib.urlencode(postData) + + else: + raise Exception('Method ' + method + ' is not recognized.') + + request = MethodRequest(method=method, url=url, headers=headers, + data=data) + + # Make the request + response = urllib2.urlopen(request) + if 'Set-Cookie' in response.headers: + self.cookie = response.headers['Set-Cookie'] + string = response.read() + + try: + data = json.loads(string) + except ValueError: # PUT requests don't return anything + data = None + + return data + + def toPathValue(self, obj): + """Convert a string or object to a path-friendly value + Args: + obj -- object or string value + Returns: + string -- quoted value + """ + if type(obj) == list: + return urllib.quote(','.join(obj)) + else: + return urllib.quote(str(obj)) + + def sanitizeForSerialization(self, obj): + """Dump an object into JSON for POSTing.""" + + if type(obj) == type(None): + return None + elif type(obj) in [str, int, long, float, bool]: + return obj + elif type(obj) == list: + return [self.sanitizeForSerialization(subObj) for subObj in obj] + elif type(obj) == datetime.datetime: + return obj.isoformat() + else: + if type(obj) == dict: + objDict = obj + else: + objDict = obj.__dict__ + return {key: self.sanitizeForSerialization(val) + for (key, val) in objDict.iteritems() + if key != 'swaggerTypes'} + + if type(postData) == list: + # Could be a list of objects + if type(postData[0]) in safeToDump: + data = json.dumps(postData) + else: + data = json.dumps([datum.__dict__ for datum in postData]) + elif type(postData) not in safeToDump: + data = json.dumps(postData.__dict__) + + def buildMultipartFormData(self, postData, files): + def escape_quotes(s): + return s.replace('"', '\\"') + + lines = [] + + for name, value in postData.items(): + lines.extend(( + '--{0}'.format(self.boundary), + 'Content-Disposition: form-data; name="{0}"'.format(escape_quotes(name)), + '', + str(value), + )) + + for name, filepath in files.items(): + f = open(filepath, 'r') + filename = filepath.split('/')[-1] + mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' + lines.extend(( + '--{0}'.format(self.boundary), + 'Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(escape_quotes(name), escape_quotes(filename)), + 'Content-Type: {0}'.format(mimetype), + '', + f.read() + )) + + lines.extend(( + '--{0}--'.format(self.boundary), + '' + )) + return '\r\n'.join(lines) + + def deserialize(self, obj, objClass): + """Derialize a JSON string into an object. + + Args: + obj -- string or object to be deserialized + objClass -- class literal for deserialzied object, or string + of class name + Returns: + object -- deserialized object""" + + # Have to accept objClass as string or actual type. Type could be a + # native Python type, or one of the model classes. + if type(objClass) == str: + if 'list[' in objClass: + match = re.match('list\[(.*)\]', objClass) + subClass = match.group(1) + return [self.deserialize(subObj, subClass) for subObj in obj] + + if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str', 'bool', 'datetime']): + objClass = eval(objClass) + else: # not a native type, must be model class + objClass = eval(objClass + '.' + objClass) + + if objClass in [int, long, float, dict, list, str, bool]: + return objClass(obj) + elif objClass == datetime: + # Server will always return a time stamp in UTC, but with + # trailing +0000 indicating no offset from UTC. So don't process + # last 5 characters. + return datetime.datetime.strptime(obj[:-5], "%Y-%m-%dT%H:%M:%S.%f") + + instance = objClass() + + for attr, attrType in instance.swaggerTypes.iteritems(): + if obj is not None and attr in obj and type(obj) in [list, dict]: + value = obj[attr] + if attrType in ['str', 'int', 'long', 'float', 'bool']: + attrType = eval(attrType) + try: + value = attrType(value) + except UnicodeEncodeError: + value = unicode(value) + except TypeError: + value = value + setattr(instance, attr, value) + elif (attrType == 'datetime'): + setattr(instance, attr, datetime.datetime.strptime(value[:-5], "%Y-%m-%dT%H:%M:%S.%f")) + elif 'list[' in attrType: + match = re.match('list\[(.*)\]', attrType) + subClass = match.group(1) + subValues = [] + if not value: + setattr(instance, attr, None) + else: + for subValue in value: + subValues.append(self.deserialize(subValue, subClass)) + setattr(instance, attr, subValues) + else: + setattr(instance, attr, self.deserialize(value, objClass)) + + return instance + + +class MethodRequest(urllib2.Request): + def __init__(self, *args, **kwargs): + """Construct a MethodRequest. Usage is the same as for + `urllib2.Request` except it also takes an optional `method` + keyword argument. If supplied, `method` will be used instead of + the default.""" + + if 'method' in kwargs: + self.method = kwargs.pop('method') + return urllib2.Request.__init__(self, *args, **kwargs) + + def get_method(self): + return getattr(self, 'method', urllib2.Request.get_method(self)) \ No newline at end of file diff --git a/samples/client/petstore/python/models/__init__.py b/samples/client/petstore/python/models/__init__.py deleted file mode 100644 index 39f84514fe91..000000000000 --- a/samples/client/petstore/python/models/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" -import os - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) - diff --git a/samples/client/petstore/python/swagger.py b/samples/client/petstore/python/swagger.py deleted file mode 100644 index 1065ad800e78..000000000000 --- a/samples/client/petstore/python/swagger.py +++ /dev/null @@ -1,209 +0,0 @@ -#!/usr/bin/env python -"""Wordnik.com's Swagger generic API client. This client handles the client- -server communication, and is invariant across implementations. Specifics of -the methods and models for each application are generated from the Swagger -templates.""" - -import sys -import os -import re -import urllib -import urllib2 -import httplib -import json -import datetime - -from models import * - - -class ApiClient: - """Generic API client for Swagger client library builds""" - - def __init__(self, apiKey=None, apiServer=None): - if apiKey == None: - raise Exception('You must pass an apiKey when instantiating the ' - 'APIClient') - self.apiKey = apiKey - self.apiServer = apiServer - self.cookie = None - - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None): - - url = self.apiServer + resourcePath - headers = {} - if headerParams: - for param, value in headerParams.iteritems(): - headers[param] = value - - #headers['Content-type'] = 'application/json' - headers['api_key'] = self.apiKey - - if self.cookie: - headers['Cookie'] = self.cookie - - data = None - - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.urlencode(sentQueryParams) - - if method in ['GET']: - - #Options to add statements later on and for compatibility - pass - - elif method in ['POST', 'PUT', 'DELETE']: - - if postData: - headers['Content-type'] = 'application/json' - data = self.sanitizeForSerialization(postData) - data = json.dumps(data) - - else: - raise Exception('Method ' + method + ' is not recognized.') - - request = MethodRequest(method=method, url=url, headers=headers, - data=data) - - # Make the request - response = urllib2.urlopen(request) - if 'Set-Cookie' in response.headers: - self.cookie = response.headers['Set-Cookie'] - string = response.read() - - try: - data = json.loads(string) - except ValueError: # PUT requests don't return anything - data = None - - return data - - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value - """ - if type(obj) == list: - return urllib.quote(','.join(obj)) - else: - return urllib.quote(str(obj)) - - def sanitizeForSerialization(self, obj): - """Dump an object into JSON for POSTing.""" - - if type(obj) == type(None): - return None - elif type(obj) in [str, int, long, float, bool]: - return obj - elif type(obj) == list: - return [self.sanitizeForSerialization(subObj) for subObj in obj] - elif type(obj) == datetime.datetime: - return obj.isoformat() - else: - if type(obj) == dict: - objDict = obj - else: - objDict = obj.__dict__ - return {key: self.sanitizeForSerialization(val) - for (key, val) in objDict.iteritems() - if key != 'swaggerTypes'} - - if type(postData) == list: - # Could be a list of objects - if type(postData[0]) in safeToDump: - data = json.dumps(postData) - else: - data = json.dumps([datum.__dict__ for datum in postData]) - elif type(postData) not in safeToDump: - data = json.dumps(postData.__dict__) - - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. - - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" - - # Have to accept objClass as string or actual type. Type could be a - # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] - - if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) - else: # not a native type, must be model class - objClass = eval(objClass + '.' + objClass) - - if objClass in [int, long, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: - # Server will always return a time stamp in UTC, but with - # trailing +0000 indicating no offset from UTC. So don't process - # last 5 characters. - return datetime.datetime.strptime(obj[:-5], - "%Y-%m-%dT%H:%M:%S.%f") - - instance = objClass() - - for attr, attrType in instance.swaggerTypes.iteritems(): - if obj is not None and attr in obj and type(obj) in [list, dict]: - value = obj[attr] - if attrType in ['str', 'int', 'long', 'float', 'bool']: - attrType = eval(attrType) - try: - value = attrType(value) - except UnicodeEncodeError: - value = unicode(value) - except TypeError: - value = value - setattr(instance, attr, value) - elif (attrType == 'datetime'): - setattr(instance, attr, datetime.datetime.strptime(value[:-5], - "%Y-%m-%dT%H:%M:%S.%f")) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] - if not value: - setattr(instance, attr, None) - else: - for subValue in value: - subValues.append(self.deserialize(subValue, - subClass)) - setattr(instance, attr, subValues) - else: - setattr(instance, attr, self.deserialize(value, - objClass)) - - return instance - - -class MethodRequest(urllib2.Request): - - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib2.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" - - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib2.Request.__init__(self, *args, **kwargs) - - def get_method(self): - return getattr(self, 'method', urllib2.Request.get_method(self)) - - diff --git a/samples/client/petstore/scala/ScalaPetstoreCodegen.scala b/samples/client/petstore/scala/ScalaPetstoreCodegen.scala deleted file mode 100644 index 48e11f2777fd..000000000000 --- a/samples/client/petstore/scala/ScalaPetstoreCodegen.scala +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicScalaGenerator - -object ScalaPetstoreCodegen extends BasicScalaGenerator { - def main(args: Array[String]) = generateClient(args) - - // package for api invoker, error files - override def invokerPackage = Some("com.wordnik.client") - - // where to write generated code - override def destinationDir = "samples/client/petstore/scala/src/main/scala" - - // package for models - override def modelPackage = Some("com.wordnik.petstore.model") - - // package for api classes - override def apiPackage = Some("com.wordnik.petstore.api") - - // supporting classes - override def supportingFiles = List( - ("apiInvoker.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiInvoker.scala"), - ("pom.mustache", "samples/client/petstore/scala", "pom.xml") - ) -} \ No newline at end of file diff --git a/samples/client/petstore/scala/pom.xml b/samples/client/petstore/scala/pom.xml index fdd9eae1ba3d..0ccbebeb0dfa 100644 --- a/samples/client/petstore/scala/pom.xml +++ b/samples/client/petstore/scala/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 com.wordnik - scala-client + swagger-client jar - scala-client + swagger-client 1.0.0 2.2.0 @@ -150,33 +150,40 @@ + + com.fasterxml.jackson.module + jackson-module-scala_2.10 + ${jackson-version} + com.sun.jersey jersey-client ${jersey-version} - compile com.sun.jersey.contribs jersey-multipart ${jersey-version} + + + org.jfarcand + jersey-ahc-client + ${jersey-async-version} compile org.scala-lang scala-library ${scala-version} - compile com.wordnik - swagger-core_${scala-short-version} + swagger-core ${swagger-core-version} - compile org.scalatest - scalatest_${scala-short-version} + scalatest_2.10 ${scala-test-version} test @@ -186,45 +193,29 @@ ${junit-version} test + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + - - - scala_2.11 - - 2.11.2 - 2.11 - 1.3.10 - 2.2.2 - - - - scala_2.10 - - true - - - 2.10.3 - 2.10 - 1.3.10 - 2.1.2 - - - - scala_2.9.1 - - 2.9.1-1 - 2.9.1 - 1.3.1 - 1.9.2 - - - + 2.10.4 + 1.2 + 2.2 1.7 - 4.8.1 + 1.5.0-M1 + 1.0.5 1.0.0 + 2.4.2 + 4.8.1 - 3.2.0 + 3.1.5 + 2.1.3 - diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/common/ApiInvoker.scala b/samples/client/petstore/scala/src/main/java/io/swagger/client/ApiInvoker.scala similarity index 80% rename from samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/common/ApiInvoker.scala rename to samples/client/petstore/scala/src/main/java/io/swagger/client/ApiInvoker.scala index 794070ae89c5..329d69a8ac90 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/common/ApiInvoker.scala +++ b/samples/client/petstore/scala/src/main/java/io/swagger/client/ApiInvoker.scala @@ -1,4 +1,4 @@ -package com.wordnik.client.common +package io.swagger.client import com.sun.jersey.api.client.Client import com.sun.jersey.api.client.ClientResponse @@ -35,10 +35,14 @@ object ScalaJsonUtil { } } -object ApiInvoker { - val mapper = ScalaJsonUtil.getJsonMapper - val defaultHeaders: HashMap[String, String] = HashMap() - val hostMap: HashMap[String, Client] = HashMap() +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") @@ -151,15 +155,39 @@ object ApiInvoker { hostMap.contains(host) match { case true => hostMap(host) case false => { - val client = Client.create() + 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/scala/src/main/scala/com/wordnik/petstore/api/PetApi.scala b/samples/client/petstore/scala/src/main/java/io/swagger/client/api/PetApi.scala similarity index 57% rename from samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/api/PetApi.scala rename to samples/client/petstore/scala/src/main/java/io/swagger/client/api/PetApi.scala index 0ae8819a7065..9af297b52525 100644 --- a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/java/io/swagger/client/api/PetApi.scala @@ -1,240 +1,119 @@ -package com.wordnik.petstore.api +package io.swagger.client.api -import com.wordnik.petstore.model.Pet -import com.wordnik.client.ApiInvoker -import com.wordnik.client.ApiException +import io.swagger.client.model.Pet +import java.io.File +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException import java.io.File import java.util.Date import scala.collection.mutable.HashMap -class PetApi { - var basePath: String = "http://petstore.swagger.wordnik.com/api" - var apiInvoker = ApiInvoker - +class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value - def getPetById (petId: Long) : Option[Pet]= { - // create path and map variables - val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) - - - - val contentType = { - "application/json"} - - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - // verify required params are set - (List(petId).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } - try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { - case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[Pet]).asInstanceOf[Pet]) - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - def deletePet (petId: String) = { - // create path and map variables - val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) - - - - val contentType = { - "application/json"} - - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - // verify required params are set - (List(petId).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } - try { - apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap, contentType) match { - case s: String => - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - def partialUpdate (petId: String, body: Pet) : Option[List[Pet]]= { - // create path and map variables - val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) - - - - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - } - - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - // verify required params are set - (List(petId, body).filter(_ != null)).size match { - case 2 => // all required values set - case _ => throw new Exception("missing required params") - } - try { - apiInvoker.invokeApi(basePath, path, "PATCH", queryParams.toMap, body, headerParams.toMap, contentType) match { - case s: String => - Some(ApiInvoker.deserialize(s, "Array", classOf[Pet]).asInstanceOf[List[Pet]]) - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - def updatePetWithForm (petId: String, name: String, status: String) = { - // create path and map variables - val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) - - - - val contentType = { - "application/json"} - - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - // verify required params are set - (List(petId).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } - try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, None, headerParams.toMap, contentType) match { - case s: String => - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - def uploadFile (additionalMetadata: String, body: File) = { - // create path and map variables - val path = "/pet/uploadImage".replaceAll("\\{format\\}","json") - - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - } - - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { - case s: String => - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - def addPet (body: Pet) = { + + def updatePet (body: Pet) = { // create path and map variables val path = "/pet".replaceAll("\\{format\\}","json") + val contentType = { if(body != null && body.isInstanceOf[File] ) "multipart/form-data" else "application/json" - } + + + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] - // verify required params are set - (List(body).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } - try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { - case s: String => - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - def updatePet (body: Pet) = { - // create path and map variables - val path = "/pet".replaceAll("\\{format\\}","json") + - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - } + + + - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - // verify required params are set - (List(body).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } try { apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, body, headerParams.toMap, contentType) match { case s: String => - case _ => None + + case _ => None } } catch { case ex: ApiException if ex.code == 404 => None case ex: ApiException => throw ex } } - def findPetsByStatus (status: String= "available") : Option[List[Pet]]= { + + def addPet (body: Pet) = { + // create path and map variables + val path = "/pet".replaceAll("\\{format\\}","json") + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def findPetsByStatus (status: List[String]) : Option[List[Pet]] = { // create path and map variables val path = "/pet/findByStatus".replaceAll("\\{format\\}","json") + val contentType = { - "application/json"} + + "application/json" + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] - // verify required params are set - (List(status).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } + + if(String.valueOf(status) != "null") queryParams += "status" -> status.toString + + + + try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "Array", classOf[Pet]).asInstanceOf[List[Pet]]) + Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) + case _ => None } } catch { @@ -242,27 +121,33 @@ class PetApi { case ex: ApiException => throw ex } } - def findPetsByTags (tags: String) : Option[List[Pet]]= { + + def findPetsByTags (tags: List[String]) : Option[List[Pet]] = { // create path and map variables val path = "/pet/findByTags".replaceAll("\\{format\\}","json") + val contentType = { - "application/json"} + + "application/json" + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] - // verify required params are set - (List(tags).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } + + if(String.valueOf(tags) != "null") queryParams += "tags" -> tags.toString + + + + try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "Array", classOf[Pet]).asInstanceOf[List[Pet]]) + Some(ApiInvoker.deserialize(s, "array", classOf[Pet]).asInstanceOf[List[Pet]]) + case _ => None } } catch { @@ -270,5 +155,143 @@ class PetApi { case ex: ApiException => throw ex } } - } + + def getPetById (petId: Long) : Option[Pet] = { + // create path and map variables + val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[Pet]).asInstanceOf[Pet]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def updatePetWithForm (petId: String, name: String, status: String) = { + // create path and map variables + val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def deletePet (api_key: String, petId: Long) = { + // create path and map variables + val path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "api_key" -> api_key + + + try { + apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def uploadFile (petId: Long, additionalMetadata: String, file: File) = { + // create path and map variables + val path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escape(petId)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, None, 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/scala/src/main/scala/com/wordnik/petstore/api/StoreApi.scala b/samples/client/petstore/scala/src/main/java/io/swagger/client/api/StoreApi.scala similarity index 55% rename from samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/api/StoreApi.scala rename to samples/client/petstore/scala/src/main/java/io/swagger/client/api/StoreApi.scala index d860f3ad39c5..c5fa105fca96 100644 --- a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/api/StoreApi.scala +++ b/samples/client/petstore/scala/src/main/java/io/swagger/client/api/StoreApi.scala @@ -1,42 +1,47 @@ -package com.wordnik.petstore.api +package io.swagger.client.api -import com.wordnik.petstore.model.Order -import com.wordnik.client.ApiInvoker -import com.wordnik.client.ApiException +import io.swagger.client.model.Order +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException import java.io.File import java.util.Date import scala.collection.mutable.HashMap -class StoreApi { - var basePath: String = "http://petstore.swagger.wordnik.com/api" - var apiInvoker = ApiInvoker - +class StoreApi(val defBasePath: String = "http://petstore.swagger.io/v2", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value - def getOrderById (orderId: String) : Option[Order]= { + + def getInventory () : Option[Map[String, Integer]] = { // create path and map variables - val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId)) + val path = "/store/inventory".replaceAll("\\{format\\}","json") - val contentType = { - "application/json"} + + "application/json" + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] - // verify required params are set - (List(orderId).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } + + + + + + try { apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) + Some(ApiInvoker.deserialize(s, "map", classOf[Integer]).asInstanceOf[Map[String, Integer]]) + case _ => None } } catch { @@ -44,62 +49,110 @@ class StoreApi { case ex: ApiException => throw ex } } - def deleteOrder (orderId: String) = { + + def placeOrder (body: Order) : Option[Order] = { + // create path and map variables + val path = "/store/order".replaceAll("\\{format\\}","json") + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getOrderById (orderId: String) : Option[Order] = { // create path and map variables val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId)) + val contentType = { - "application/json"} + + "application/json" + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] - // verify required params are set - (List(orderId).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex } + } + + def deleteOrder (orderId: String) = { + // create path and map variables + val path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escape(orderId)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + try { apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => - case _ => None + + case _ => None } } catch { case ex: ApiException if ex.code == 404 => None case ex: ApiException => throw ex } } - def placeOrder (body: Order) = { - // create path and map variables - val path = "/store/order".replaceAll("\\{format\\}","json") - - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - } - - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - // verify required params are set - (List(body).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } - try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, 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/scala/src/main/scala/com/wordnik/petstore/api/UserApi.scala b/samples/client/petstore/scala/src/main/java/io/swagger/client/api/UserApi.scala similarity index 69% rename from samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/api/UserApi.scala rename to samples/client/petstore/scala/src/main/java/io/swagger/client/api/UserApi.scala index bfeece060ef1..a46f19b9e683 100644 --- a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/api/UserApi.scala +++ b/samples/client/petstore/scala/src/main/java/io/swagger/client/api/UserApi.scala @@ -1,244 +1,298 @@ -package com.wordnik.petstore.api +package io.swagger.client.api -import com.wordnik.petstore.model.User -import com.wordnik.client.ApiInvoker -import com.wordnik.client.ApiException +import io.swagger.client.model.User +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException import java.io.File import java.util.Date import scala.collection.mutable.HashMap -class UserApi { - var basePath: String = "http://petstore.swagger.wordnik.com/api" - var apiInvoker = ApiInvoker - +class UserApi(val defBasePath: String = "http://petstore.swagger.io/v2", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value - def updateUser (username: String, body: User) = { - // create path and map variables - val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) - - - - val contentType = { - if(body != null && body.isInstanceOf[File] ) - "multipart/form-data" - else "application/json" - } - - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - // verify required params are set - (List(username, body).filter(_ != null)).size match { - case 2 => // all required values set - case _ => throw new Exception("missing required params") - } - try { - apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, body, headerParams.toMap, contentType) match { - case s: String => - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - def deleteUser (username: String) = { - // create path and map variables - val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) - - - - val contentType = { - "application/json"} - - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - // verify required params are set - (List(username).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } - try { - apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap, contentType) match { - case s: String => - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - def getUserByName (username: String) : Option[User]= { - // create path and map variables - val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) - - - - val contentType = { - "application/json"} - - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - // verify required params are set - (List(username).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } - try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { - case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - def loginUser (username: String, password: String) : Option[String]= { - // create path and map variables - val path = "/user/login".replaceAll("\\{format\\}","json") - - val contentType = { - "application/json"} - - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - // verify required params are set - (List(username, password).filter(_ != null)).size match { - case 2 => // all required values set - case _ => throw new Exception("missing required params") - } - if(String.valueOf(username) != "null") queryParams += "username" -> username.toString - if(String.valueOf(password) != "null") queryParams += "password" -> password.toString - try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { - case s: String => - Some(ApiInvoker.deserialize(s, "", classOf[String]).asInstanceOf[String]) - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - def logoutUser () = { - // create path and map variables - val path = "/user/logout".replaceAll("\\{format\\}","json") - - val contentType = { - "application/json"} - - // query params - val queryParams = new HashMap[String, String] - val headerParams = new HashMap[String, String] - - try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { - case s: String => - case _ => None - } - } catch { - case ex: ApiException if ex.code == 404 => None - case ex: ApiException => throw ex - } - } - def createUser (body: User) = { + + def createUser (body: User) = { // create path and map variables val path = "/user".replaceAll("\\{format\\}","json") + val contentType = { if(body != null && body.isInstanceOf[File] ) "multipart/form-data" else "application/json" - } + + + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] - // verify required params are set - (List(body).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } + + + + + + try { apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { case s: String => - case _ => None + + case _ => None } } catch { case ex: ApiException if ex.code == 404 => None case ex: ApiException => throw ex } } - def createUsersWithArrayInput (body: List[User]) = { + + def createUsersWithArrayInput (body: List[User]) = { // create path and map variables val path = "/user/createWithArray".replaceAll("\\{format\\}","json") + val contentType = { if(body != null && body.isInstanceOf[File] ) "multipart/form-data" else "application/json" - } + + + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] - // verify required params are set - (List(body).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } + + + + + + try { apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { case s: String => - case _ => None + + case _ => None } } catch { case ex: ApiException if ex.code == 404 => None case ex: ApiException => throw ex } } - def createUsersWithListInput (body: List[User]) = { + + def createUsersWithListInput (body: List[User]) = { // create path and map variables val path = "/user/createWithList".replaceAll("\\{format\\}","json") + val contentType = { if(body != null && body.isInstanceOf[File] ) "multipart/form-data" else "application/json" - } + + + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] - // verify required params are set - (List(body).filter(_ != null)).size match { - case 1 => // all required values set - case _ => throw new Exception("missing required params") - } + + + + + + try { apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { case s: String => - case _ => None + + case _ => None } } catch { case ex: ApiException if ex.code == 404 => None case ex: ApiException => throw ex } } - } + + def loginUser (username: String, password: String) : Option[String] = { + // create path and map variables + val path = "/user/login".replaceAll("\\{format\\}","json") + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(username) != "null") queryParams += "username" -> username.toString + if(String.valueOf(password) != "null") queryParams += "password" -> password.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[String]).asInstanceOf[String]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def logoutUser () = { + // create path and map variables + val path = "/user/logout".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getUserByName (username: String) : Option[User] = { + // create path and map variables + val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def updateUser (username: String, body: User) = { + // create path and map variables + val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) + + + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def deleteUser (username: String) = { + // create path and map variables + val path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, 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/scala/src/main/scala/com/wordnik/petstore/model/Category.scala b/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Category.scala similarity index 58% rename from samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/Category.scala rename to samples/client/petstore/scala/src/main/java/io/swagger/client/model/Category.scala index 0b1041ffc4e0..122411e3ff7d 100644 --- a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/Category.scala +++ b/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Category.scala @@ -1,6 +1,9 @@ -package com.wordnik.petstore.model +package io.swagger.client.model + + + case class Category ( id: Long, name: String) - + diff --git a/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Order.scala b/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Order.scala new file mode 100644 index 000000000000..845fe32c9731 --- /dev/null +++ b/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Order.scala @@ -0,0 +1,15 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + + +case class Order ( + id: Long, + petId: Long, + quantity: Integer, + shipDate: DateTime, + /* Order Status */ + status: String, + complete: Boolean) + diff --git a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/Pet.scala b/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Pet.scala similarity index 51% rename from samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/Pet.scala rename to samples/client/petstore/scala/src/main/java/io/swagger/client/model/Pet.scala index cca2af8de7a2..430f6a3659cf 100644 --- a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/Pet.scala +++ b/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Pet.scala @@ -1,9 +1,11 @@ -package com.wordnik.petstore.model +package io.swagger.client.model + +import io.swagger.client.model.Category +import io.swagger.client.model.Tag + + -import com.wordnik.petstore.model.Category -import com.wordnik.petstore.model.Tag case class Pet ( - /* unique identifier for the pet */ id: Long, category: Category, name: String, @@ -11,4 +13,4 @@ case class Pet ( tags: List[Tag], /* pet status in the store */ status: String) - + diff --git a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/Tag.scala b/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Tag.scala similarity index 55% rename from samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/Tag.scala rename to samples/client/petstore/scala/src/main/java/io/swagger/client/model/Tag.scala index 0712c68ceca6..b0b75d4a96c7 100644 --- a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/Tag.scala +++ b/samples/client/petstore/scala/src/main/java/io/swagger/client/model/Tag.scala @@ -1,6 +1,9 @@ -package com.wordnik.petstore.model +package io.swagger.client.model + + + case class Tag ( id: Long, name: String) - + diff --git a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/User.scala b/samples/client/petstore/scala/src/main/java/io/swagger/client/model/User.scala similarity index 73% rename from samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/User.scala rename to samples/client/petstore/scala/src/main/java/io/swagger/client/model/User.scala index 517b52f84c9a..125147c0ae08 100644 --- a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/User.scala +++ b/samples/client/petstore/scala/src/main/java/io/swagger/client/model/User.scala @@ -1,13 +1,16 @@ -package com.wordnik.petstore.model +package io.swagger.client.model + + + case class User ( id: Long, - firstName: String, username: String, + firstName: String, lastName: String, email: String, password: String, phone: String, /* User Status */ - userStatus: Int) - + userStatus: Integer) + diff --git a/samples/client/petstore/tizen/client/SamiApiClient.cpp b/samples/client/petstore/tizen/client/SamiApiClient.cpp new file mode 100644 index 000000000000..35779307fa20 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiApiClient.cpp @@ -0,0 +1,124 @@ +#include "SamiApiClient.h" +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; + +namespace Swagger { + +SamiApiClient::SamiApiClient() { + enc = new Utf8Encoding(); +} + +void +SamiApiClient::success(void (*success) (HttpResponse*, void (*cb)(void*, SamiError*)), void (*cb)(void*, SamiError*)) { + this->successFunction = success; + this->cb = cb; +} + +SamiApiClient::~SamiApiClient() { + if(enc) + delete enc; +} + +result +SamiApiClient::execute(String host, String path, String method, IMap* queryParams, String* body, IMap* headerParams, IMap* formParams, String contentType) { + NetHttpMethod httpMethod; + if(method.Equals(L"GET", false)) { + httpMethod = NET_HTTP_METHOD_GET; + } + else if(method.Equals(L"PUT", false)) { + httpMethod = NET_HTTP_METHOD_PUT; + } + else if(method.Equals(L"POST", false)) { + httpMethod = NET_HTTP_METHOD_POST; + } + else if(method.Equals(L"DELETE", false)) { + httpMethod = NET_HTTP_METHOD_DELETE; + } + else if(method.Equals(L"OPTIONS", false)) { + httpMethod = NET_HTTP_METHOD_OPTIONS; + } + else if(method.Equals(L"HEAD", false)) { + httpMethod = NET_HTTP_METHOD_HEAD; + } + else if(method.Equals(L"TRACE", false)) { + httpMethod = NET_HTTP_METHOD_TRACE; + } + + String uri = String(host); + uri.Append(path); + + HttpSession* __pHttpSession = null; + HttpTransaction* pHttpTransaction = null; + HttpRequest* pHttpRequest = null; + + if (__pHttpSession == null) { + __pHttpSession = new (std::nothrow) HttpSession(); + __pHttpSession->Construct(NET_HTTP_SESSION_MODE_NORMAL, null, uri, null); + __pHttpSession->SetAutoRedirectionEnabled(true); + } + pHttpTransaction = __pHttpSession->OpenTransactionN(); + pHttpTransaction->AddHttpTransactionListener(*this); + + pHttpRequest = const_cast< HttpRequest* >(pHttpTransaction->GetRequest()); + + HttpHeader *pHeader = pHttpRequest->GetHeader(); + if(contentType != null && !contentType.Equals(L"", true)) { + pHeader->AddField(L"Accept", contentType); + } + if(queryParams != null) { + IMapEnumerator* pMapEnum = queryParams->GetMapEnumeratorN(); + String queryParam = L""; + while (pMapEnum->MoveNext() == E_SUCCESS) { + if(queryParam.GetLength() == 0) + queryParam.Append(L"?"); + else + queryParam.Append(L"&"); + + String* pKey = static_cast< String* > (pMapEnum->GetKey()); + String* pValue = static_cast< String* > (pMapEnum->GetValue()); + String encoded; + UrlEncoder::Encode(*pKey, L"UTF-8", encoded); + + queryParam.Append(encoded); + queryParam.Append("="); + UrlEncoder::Encode(*pValue, L"UTF-8", encoded); + queryParam.Append(encoded); + } + uri.Append(queryParam); + delete queryParams; + } + if(headerParams != null) { + IMapEnumerator* pMapEnum = headerParams->GetMapEnumeratorN(); + while (pMapEnum->MoveNext() == E_SUCCESS) { + String* pKey = static_cast< String* > (pMapEnum->GetKey()); + String* pValue = static_cast< String* > (pMapEnum->GetValue()); + pHeader->AddField(*pKey, *pValue); + } + delete headerParams; + } + if(body != null) { + HttpStringEntity * pEntity = new HttpStringEntity(); + String* cp = new String(*body); + result res = pEntity->Construct(*body, L"application/json", "utf-8", *enc); + res = pHttpRequest->SetEntity(*pEntity); + } + + pHttpRequest->SetUri(uri); + pHttpRequest->SetMethod(httpMethod); + + AppLog("%ls", uri.GetPointer()); + return pHttpTransaction->Submit(); +} + +void +SamiApiClient::OnTransactionCompleted(HttpSession& httpSession, HttpTransaction& pHttpTransaction) { + HttpResponse* pHttpResponse = pHttpTransaction.GetResponse(); + + if(successFunction != null) { + successFunction(pHttpResponse, cb); + } + delete &httpSession; + delete &pHttpTransaction; +} + +} /* namespace Swagger */ diff --git a/samples/client/petstore/tizen/client/SamiApiClient.h b/samples/client/petstore/tizen/client/SamiApiClient.h new file mode 100644 index 000000000000..f20eb6e158bb --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiApiClient.h @@ -0,0 +1,73 @@ +#include + +#include "SamiHelpers.h" +#include "SamiError.h" + +using namespace Tizen::Net::Http; +using namespace Tizen::Base; +using namespace Tizen::Base::Collection; +using namespace Tizen::Text; + +#ifndef APICLIENT_H_ +#define APICLIENT_H_ + +namespace Swagger { + +class SamiApiClient: public IHttpTransactionEventListener { +public: + SamiApiClient(); + virtual ~SamiApiClient(); + + result + execute(String host, String path, String method, IMap* queryParams, String* body, IMap* headerParams, IMap* formParams, String contentType); + + void success(void (*res) (HttpResponse*, void (*cb)(void*, SamiError*)), void (*cb)(void*, SamiError*)); + + virtual void + OnTransactionCompleted(HttpSession& httpSession, HttpTransaction& pHttpTransaction); + + virtual void + OnAudioInAudioFocusChanged(void) { + AppLog("OnAudioInAudioFocusChanged"); + } + + virtual void + OnTransactionCertVerificationRequiredN(HttpSession& httpSession, HttpTransaction& httpTransaction, + Tizen::Base::String* pCert) { + AppLog("OnTransactionCertVerificationRequiredN"); + httpTransaction.Resume(); + + delete pCert; + } + + virtual void + OnTransactionReadyToWrite(HttpSession& httpSession, HttpTransaction& httpTransaction, int recommendedChunkSize) { + AppLog("OnTransactionReadyToWrite"); + } + + virtual void + OnTransactionReadyToRead(HttpSession& httpSession, HttpTransaction& httpTransaction, int availableBodyLen) { + AppLog("OnTransactionReadyToRead"); + } + + virtual void + OnTransactionAborted(HttpSession& httpSession, HttpTransaction& httpTransaction, result r) { + AppLog("OnTransactionAborted: %ls", GetErrorMessage(r)); + delete &httpTransaction; + } + + virtual void + OnTransactionHeaderCompleted(HttpSession& httpSession, HttpTransaction& httpTransaction, int headerLen, bool + bAuthRequired) { + AppLog("OnTransactionHeaderCompleted"); +} + +private: + void (*successFunction) (HttpResponse*, void (*success)(void*, SamiError*)); + void (*cb)(void*, SamiError*); + Utf8Encoding* enc; +}; + + +} /* namespace Swagger */ +#endif /* APICLIENT_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiCategory.cpp b/samples/client/petstore/tizen/client/SamiCategory.cpp new file mode 100644 index 000000000000..0e79da7bebd4 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiCategory.cpp @@ -0,0 +1,182 @@ + +#include "SamiCategory.h" +#include + +using namespace Tizen::Base; +using namespace Tizen::System; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; +using namespace Tizen::Web::Json; +using namespace Tizen::Locales; + + +namespace Swagger { + +SamiCategory::SamiCategory() { + init(); +} + +SamiCategory::~SamiCategory() { + this->cleanup(); +} + +void +SamiCategory::init() { + pId = null; + pName = null; + +} + +void +SamiCategory::cleanup() { + if(pId != null) { + + delete pId; + pId = null; + } + if(pName != null) { + + delete pName; + pName = null; + } + +} + + +SamiCategory* +SamiCategory::fromJson(String* json) { + this->cleanup(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; + return this; +} + + +void +SamiCategory::fromJsonObject(IJsonValue* pJson) { + JsonObject* pJsonObject = static_cast< JsonObject* >(pJson); + + if(pJsonObject != null) { + JsonString* pIdKey = new JsonString(L"id"); + IJsonValue* pIdVal = null; + pJsonObject->GetValue(pIdKey, pIdVal); + if(pIdVal != null) { + + pId = new Long(); + jsonToValue(pId, pIdVal, L"Long", L"Long"); + } + delete pIdKey; + JsonString* pNameKey = new JsonString(L"name"); + IJsonValue* pNameVal = null; + pJsonObject->GetValue(pNameKey, pNameVal); + if(pNameVal != null) { + + pName = new String(); + jsonToValue(pName, pNameVal, L"String", L"String"); + } + delete pNameKey; + + } +} + +SamiCategory::SamiCategory(String* json) { + init(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; +} + +String +SamiCategory::asJson () +{ + JsonObject* pJsonObject = asJsonObject(); + + char *pComposeBuf = new char[256]; + JsonWriter::Compose(pJsonObject, pComposeBuf, 256); + String s = String(pComposeBuf); + + delete pComposeBuf; + pJsonObject->RemoveAll(true); + delete pJsonObject; + + return s; +} + +JsonObject* +SamiCategory::asJsonObject() { + JsonObject *pJsonObject = new JsonObject(); + pJsonObject->Construct(); + + + JsonString *pIdKey = new JsonString(L"id"); + pJsonObject->Add(pIdKey, toJson(getId(), "Long", "")); + + + JsonString *pNameKey = new JsonString(L"name"); + pJsonObject->Add(pNameKey, toJson(getName(), "String", "")); + + + return pJsonObject; +} + +Long* +SamiCategory::getId() { + return pId; +} +void +SamiCategory::setId(Long* pId) { + this->pId = pId; +} + +String* +SamiCategory::getName() { + return pName; +} +void +SamiCategory::setName(String* pName) { + this->pName = pName; +} + + + +} /* namespace Swagger */ + diff --git a/samples/client/petstore/tizen/client/SamiCategory.h b/samples/client/petstore/tizen/client/SamiCategory.h new file mode 100644 index 000000000000..6cb056535827 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiCategory.h @@ -0,0 +1,60 @@ +/* + * SamiCategory.h + * + * + */ + +#ifndef SamiCategory_H_ +#define SamiCategory_H_ + +#include +#include +#include +#include +#include "SamiHelpers.h" +#include "SamiObject.h" + +using namespace Tizen::Web::Json; + + +using Tizen::Base::Long; +using Tizen::Base::String; + + +namespace Swagger { + +class SamiCategory: public SamiObject { +public: + SamiCategory(); + SamiCategory(String* json); + virtual ~SamiCategory(); + + void init(); + + void cleanup(); + + String asJson (); + + JsonObject* asJsonObject(); + + void fromJsonObject(IJsonValue* json); + + SamiCategory* fromJson(String* obj); + + + Long* getId(); + void setId(Long* pId); + + String* getName(); + void setName(String* pName); + + +private: + Long* pId; + String* pName; + +}; + +} /* namespace Swagger */ + +#endif /* SamiCategory_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiError.cpp b/samples/client/petstore/tizen/client/SamiError.cpp new file mode 100644 index 000000000000..1aaaa9e726b0 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiError.cpp @@ -0,0 +1,55 @@ +#include "SamiError.h" + +using namespace Tizen::Base; +using namespace Tizen::System; + +namespace Swagger { + +SamiError::SamiError() { + init(); +} + +SamiError::SamiError(int code, String* message) { + init(); + this->setCode(code); + this->setMessage(message); +} + +SamiError::~SamiError() { + this->cleanup(); +} + +void +SamiError::init() { + pCode = 0; + pMessage = null; +} + +void +SamiError::cleanup() { + if(pMessage != null) { + delete pMessage; + pMessage = null; + } +} + +int +SamiError::getCode() { + return pCode; +} +void +SamiError::setCode(int pCode) { + this->pCode = pCode; +} + +String* +SamiError::getMessage() { + return pMessage; +} +void +SamiError::setMessage(String* pMessage) { + this->pMessage = pMessage; +} + +} /* namespace Swagger */ + diff --git a/samples/client/petstore/tizen/client/SamiError.h b/samples/client/petstore/tizen/client/SamiError.h new file mode 100644 index 000000000000..d3afe4596b21 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiError.h @@ -0,0 +1,35 @@ +#ifndef SamiError_H_ +#define SamiError_H_ + +#include + +using namespace Tizen::Base; + +namespace Swagger { + +class SamiError { +public: + SamiError(); + SamiError(int code, String* message); + virtual ~SamiError(); + + + void init(); + + void cleanup(); + + int getCode(); + void setCode(int pCode); + + String* getMessage(); + void setMessage(String* pMessage); + + +private: + int pCode; + String* pMessage; +}; + +} /* namespace Swagger */ + +#endif /* SamiError_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiHelpers.cpp b/samples/client/petstore/tizen/client/SamiHelpers.cpp new file mode 100644 index 000000000000..484be3246f7b --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiHelpers.cpp @@ -0,0 +1,273 @@ +#include "SamiHelpers.h" +#include "SamiModelFactory.h" + +using namespace Tizen::Base; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; +using namespace Tizen::Web::Json; +using namespace Tizen::Locales; +using namespace Tizen::System; + +namespace Swagger { + JsonObject* + toJson(void* ptr, String type, String containerType) { + if(ptr == null) + return null; + if(containerType != null && !type.Equals(L"", false)) { + if(containerType.Equals(L"array", false)) { + if(type != null) { + IList* list = static_cast< IList* >(ptr); + JsonArray* array = new JsonArray(); + int sz = list->GetCount(); + for(int i = 0; i < sz; i++) { + void* itemAt = list->GetAt(i); + JsonObject* item = toJson(itemAt, type, null); + if(item != null) + array->Add(item); + } + return (JsonObject*)array; + } + return null; + } + } + else if(type.Equals(L"Boolean", false)) { + Boolean* v = static_cast< Boolean* >(ptr); + return (JsonObject*) new JsonBool(*v); + } + else if(type.Equals(L"String", false)) { + String* v = static_cast< String* >(ptr); + return (JsonObject*) new JsonString(*v); + } + else if(type.Equals(L"Integer", false)) { + Integer* v = static_cast< Integer* >(ptr); + return (JsonObject*) new JsonNumber(v->ToInt()); + } + else if(type.Equals(L"Long", false)) { + Long* v = static_cast< Long* >(ptr); + return (JsonObject*) new JsonNumber(v->ToInt()); + } + else if(type.Equals(L"Float", false)) { + Float* v = static_cast< Float* >(ptr); + return (JsonObject*) new JsonNumber(v->ToFloat()); + } + else if(type.Equals(L"Double", false)) { + Double* v = static_cast< Double* >(ptr); + return (JsonObject*) new JsonNumber(v->ToDouble()); + } + else if(type.Equals(L"DateTime", false)) { + DateTime* v = static_cast< DateTime* >(ptr); + DateTimeFormatter* pFormatter = DateTimeFormatter::CreateDateTimeFormatterN(); + String date; + pFormatter->ApplyPattern(L"yyyy-MM-dd"); + pFormatter->Format(*v, date); + + String time; + pFormatter->ApplyPattern(L"hh:mm:ss"); + pFormatter->Format(*v, time); + String formattedString = date + "T" + time; + delete pFormatter; + return (JsonObject*)new JsonString(formattedString); + } + else if(type.StartsWith(L"Sami", 0)) { + SamiObject* obj = static_cast< SamiObject* >(ptr); + return obj->asJsonObject(); + } + return null; + } + + void + toISO8601(String str, DateTime* dt) { + int idx, start; + int year, month, day, hour, minute, second; + + start = 0; + str.IndexOf(L"-", start, idx); + String yearString; + str.SubString(0, idx, yearString); + Integer::Parse(yearString, year); + + start = idx+1; + str.IndexOf(L"-", start, idx); + String monthString; + str.SubString(start, idx - start, monthString); + Integer::Parse(monthString, month); + + start = idx+1; + str.IndexOf(L"T", start, idx); + String dayString; + str.SubString(start, idx - start, dayString); + Integer::Parse(dayString, day); + + start = idx+1; + str.IndexOf(L":", start, idx); + if(idx > 0) { + String hourString; + str.SubString(start, idx - start, hourString); + Integer::Parse(hourString, hour); + } + + start = idx+1; + str.IndexOf(L":", start, idx); + if(idx > 0) { + String minuteString; + str.SubString(start, idx - start, minuteString); + Integer::Parse(minuteString, minute); + } + + start = idx+1; + str.IndexOf(L"+", start, idx); + if(idx > 0) { + String secondString; + str.SubString(start, idx - start, secondString); + Integer::Parse(secondString, second); + } + + dt->SetValue(year, month, day, hour, minute, second); + } + + void + jsonToValue(void* target, IJsonValue* ptr, String type, String innerType) { + if(target == null || ptr == null) { + return; + } + if(type.StartsWith(L"Boolean", 0)) { + JsonBool* json = static_cast< JsonBool* >(ptr); + Boolean* val = static_cast< Boolean* > (target); + val->value = json->ToBool(); + } + else if(type.StartsWith(L"String", 0)) { + JsonString* json = static_cast< JsonString* >(ptr); + String* val = static_cast< String* > (target); + val->Clear(); + val->Append(json->GetPointer()); + } + else if(type.StartsWith(L"Integer", 0)) { + JsonNumber* json = static_cast< JsonNumber* >(ptr); + Integer* val = static_cast< Integer* > (target); + *val = json->ToInt(); + } + else if(type.StartsWith(L"Long", 0)) { + JsonNumber* json = static_cast< JsonNumber* >(ptr); + Long* val = static_cast< Long* > (target); + *val = json->ToLong(); + } + else if(type.StartsWith(L"DateTime", 0)) { + JsonString* json = static_cast< JsonString* >(ptr); + String str; + str.Append(json->GetPointer()); + + DateTime* val = static_cast< DateTime* > (target); + toISO8601(str, val); + } + else if(type.StartsWith(L"Sami", 0)) { + SamiObject* obj = static_cast< SamiObject* > (target); + obj->fromJsonObject(ptr); + } + else if(type.StartsWith(L"IList", 0)) { + IList* obj = static_cast< IList* >(target); + JsonArray* pJsonArray = static_cast< JsonArray* >(ptr); + + IEnumeratorT< IJsonValue* >* pEnum = pJsonArray->GetEnumeratorN(); + while (pEnum->MoveNext() == E_SUCCESS) { + IJsonValue* pJsonValue = null; + pEnum->GetCurrent(pJsonValue); + void* updatedTarget = null; + updatedTarget = create(innerType); + + if(updatedTarget != null) { + jsonToValue(updatedTarget, pJsonValue, innerType, L""); + obj->Add((Object*)updatedTarget); + } + } + delete pEnum; + } + } + + Integer* + jsonToInteger(IJsonValue* value) { + if(value == null) + return null; + switch(value->GetType()) { + case JSON_TYPE_STRING: + break; + case JSON_TYPE_NUMBER: { + JsonNumber* number = static_cast< JsonNumber* >(value); + int num = number->ToInt(); + return new Integer(num); + } + case JSON_TYPE_OBJECT: + break; + case JSON_TYPE_ARRAY: + break; + case JSON_TYPE_BOOL: + break; + case JSON_TYPE_NULL: + break; + } + return null; + } + + Long* + jsonToLong(IJsonValue* value) { + if(value == null) + return null; + switch(value->GetType()) { + case JSON_TYPE_STRING: + break; + case JSON_TYPE_NUMBER: { + JsonNumber* number = static_cast< JsonNumber* >(value); + long int num = number->ToLong(); + return new Long(num); + } + case JSON_TYPE_OBJECT: + break; + case JSON_TYPE_ARRAY: + break; + case JSON_TYPE_BOOL: + break; + case JSON_TYPE_NULL: + break; + } + return null; + } + + String* + jsonToString(IJsonValue* value) { + if(value == null) + return null; + switch(value->GetType()) { + case JSON_TYPE_STRING: { + JsonString* string = static_cast< JsonString* >(value); + return new String(string->GetPointer()); + } + case JSON_TYPE_NUMBER: + break; + case JSON_TYPE_OBJECT: + break; + case JSON_TYPE_ARRAY: + break; + case JSON_TYPE_BOOL: + break; + case JSON_TYPE_NULL: + break; + } + return null; + } + + String + stringify(void* ptr, String type) { + if(type.StartsWith(L"String", 0)) { + String * str = static_cast< String* > (ptr); + return String(str->GetPointer()); + } + if(type.StartsWith(L"Integer", 0)) { + Integer* pInt = static_cast< Integer* > (ptr); + return pInt->ToString(); + } + if(type.StartsWith(L"Long", 0)) { + Long* pLong = static_cast< Long* > (ptr); + return pLong->ToString(); + } + return L""; + } +} /* namespace Swagger */ diff --git a/samples/client/petstore/tizen/client/SamiHelpers.h b/samples/client/petstore/tizen/client/SamiHelpers.h new file mode 100644 index 000000000000..e29eb3cb34b0 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiHelpers.h @@ -0,0 +1,45 @@ +#ifndef HELPERS_H_ +#define HELPERS_H_ + +#include +#include +#include +#include +#include +#include "SamiHelpers.h" +#include "SamiObject.h" + +using Tizen::Base::String; +using Tizen::Base::DateTime; +using namespace Tizen::Web::Json; +using namespace Tizen::Base::Collection; + +using Tizen::Base::Long; +using Tizen::Base::DateTime; +using Tizen::Base::String; +using Tizen::Base::Integer; + +namespace Swagger { +JsonObject* +toJson(void* v, String type, String containerType); + +void +jsonToValue(void* target, IJsonValue* ptr, String type, String innerType); + +Integer* +jsonToInteger(IJsonValue* value); + +Long* +jsonToLong(IJsonValue* value); + +String* +jsonToString(IJsonValue* value); + +DateTime* +jsonToDateTime(IJsonValue* value); + +String +stringify(void* ptr, String type); + +} /* namespace Swagger */ +#endif /* HELPERS_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiModelFactory.h b/samples/client/petstore/tizen/client/SamiModelFactory.h new file mode 100644 index 000000000000..a2e1ab0e0de3 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiModelFactory.h @@ -0,0 +1,47 @@ +#ifndef ModelFactory_H_ +#define ModelFactory_H_ + +#include "SamiObject.h" + +#include "SamiUser.h" +#include "SamiCategory.h" +#include "SamiPet.h" +#include "SamiTag.h" +#include "SamiOrder.h" + +namespace Swagger { + void* + create(String type) { + if(type.Equals(L"SamiUser", true)) { + return new SamiUser(); + } + if(type.Equals(L"SamiCategory", true)) { + return new SamiCategory(); + } + if(type.Equals(L"SamiPet", true)) { + return new SamiPet(); + } + if(type.Equals(L"SamiTag", true)) { + return new SamiTag(); + } + if(type.Equals(L"SamiOrder", true)) { + return new SamiOrder(); + } + + if(type.Equals(L"String", true)) { + return new String(); + } + if(type.Equals(L"Integer", true)) { + return new Integer(); + } + if(type.Equals(L"Long", true)) { + return new Long(); + } + if(type.Equals(L"DateTime", true)) { + return new DateTime(); + } + return null; + } +} /* namespace Swagger */ + +#endif /* ModelFactory_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiObject.h b/samples/client/petstore/tizen/client/SamiObject.h new file mode 100644 index 000000000000..b0f921205add --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiObject.h @@ -0,0 +1,27 @@ +#ifndef _Sami_OBJECT_H_ +#define _Sami_OBJECT_H_ + +#include +#include +#include + +using Tizen::Base::String; + +using namespace Tizen::Web::Json; + +class SamiObject { + public: + virtual JsonObject* asJsonObject() { + return null; + } + virtual ~SamiObject() {} + virtual SamiObject* fromJson(String* obj) { + return null; + } + virtual void fromJsonObject(IJsonValue* obj) {} + virtual String asJson() { + return L""; + } +}; + +#endif /* _Sami_OBJECT_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiOrder.cpp b/samples/client/petstore/tizen/client/SamiOrder.cpp new file mode 100644 index 000000000000..35da0ca6de35 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiOrder.cpp @@ -0,0 +1,294 @@ + +#include "SamiOrder.h" +#include + +using namespace Tizen::Base; +using namespace Tizen::System; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; +using namespace Tizen::Web::Json; +using namespace Tizen::Locales; + + +namespace Swagger { + +SamiOrder::SamiOrder() { + init(); +} + +SamiOrder::~SamiOrder() { + this->cleanup(); +} + +void +SamiOrder::init() { + pId = null; + pPetId = null; + pQuantity = null; + pShipDate = null; + pStatus = null; + pComplete = null; + +} + +void +SamiOrder::cleanup() { + if(pId != null) { + + delete pId; + pId = null; + } + if(pPetId != null) { + + delete pPetId; + pPetId = null; + } + if(pQuantity != null) { + + delete pQuantity; + pQuantity = null; + } + if(pShipDate != null) { + + delete pShipDate; + pShipDate = null; + } + if(pStatus != null) { + + delete pStatus; + pStatus = null; + } + if(pComplete != null) { + + delete pComplete; + pComplete = null; + } + +} + + +SamiOrder* +SamiOrder::fromJson(String* json) { + this->cleanup(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; + return this; +} + + +void +SamiOrder::fromJsonObject(IJsonValue* pJson) { + JsonObject* pJsonObject = static_cast< JsonObject* >(pJson); + + if(pJsonObject != null) { + JsonString* pIdKey = new JsonString(L"id"); + IJsonValue* pIdVal = null; + pJsonObject->GetValue(pIdKey, pIdVal); + if(pIdVal != null) { + + pId = new Long(); + jsonToValue(pId, pIdVal, L"Long", L"Long"); + } + delete pIdKey; + JsonString* pPetIdKey = new JsonString(L"petId"); + IJsonValue* pPetIdVal = null; + pJsonObject->GetValue(pPetIdKey, pPetIdVal); + if(pPetIdVal != null) { + + pPetId = new Long(); + jsonToValue(pPetId, pPetIdVal, L"Long", L"Long"); + } + delete pPetIdKey; + JsonString* pQuantityKey = new JsonString(L"quantity"); + IJsonValue* pQuantityVal = null; + pJsonObject->GetValue(pQuantityKey, pQuantityVal); + if(pQuantityVal != null) { + + pQuantity = new Integer(); + jsonToValue(pQuantity, pQuantityVal, L"Integer", L"Integer"); + } + delete pQuantityKey; + JsonString* pShipDateKey = new JsonString(L"shipDate"); + IJsonValue* pShipDateVal = null; + pJsonObject->GetValue(pShipDateKey, pShipDateVal); + if(pShipDateVal != null) { + + pShipDate = new DateTime(); + jsonToValue(pShipDate, pShipDateVal, L"DateTime", L"DateTime"); + } + delete pShipDateKey; + JsonString* pStatusKey = new JsonString(L"status"); + IJsonValue* pStatusVal = null; + pJsonObject->GetValue(pStatusKey, pStatusVal); + if(pStatusVal != null) { + + pStatus = new String(); + jsonToValue(pStatus, pStatusVal, L"String", L"String"); + } + delete pStatusKey; + JsonString* pCompleteKey = new JsonString(L"complete"); + IJsonValue* pCompleteVal = null; + pJsonObject->GetValue(pCompleteKey, pCompleteVal); + if(pCompleteVal != null) { + + pComplete = new Boolean(false); + jsonToValue(pComplete, pCompleteVal, L"Boolean", L"Boolean"); + } + delete pCompleteKey; + + } +} + +SamiOrder::SamiOrder(String* json) { + init(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; +} + +String +SamiOrder::asJson () +{ + JsonObject* pJsonObject = asJsonObject(); + + char *pComposeBuf = new char[256]; + JsonWriter::Compose(pJsonObject, pComposeBuf, 256); + String s = String(pComposeBuf); + + delete pComposeBuf; + pJsonObject->RemoveAll(true); + delete pJsonObject; + + return s; +} + +JsonObject* +SamiOrder::asJsonObject() { + JsonObject *pJsonObject = new JsonObject(); + pJsonObject->Construct(); + + + JsonString *pIdKey = new JsonString(L"id"); + pJsonObject->Add(pIdKey, toJson(getId(), "Long", "")); + + + JsonString *pPetIdKey = new JsonString(L"petId"); + pJsonObject->Add(pPetIdKey, toJson(getPetId(), "Long", "")); + + + JsonString *pQuantityKey = new JsonString(L"quantity"); + pJsonObject->Add(pQuantityKey, toJson(getQuantity(), "Integer", "")); + + + JsonString *pShipDateKey = new JsonString(L"shipDate"); + pJsonObject->Add(pShipDateKey, toJson(getShipDate(), "DateTime", "")); + + + JsonString *pStatusKey = new JsonString(L"status"); + pJsonObject->Add(pStatusKey, toJson(getStatus(), "String", "")); + + + JsonString *pCompleteKey = new JsonString(L"complete"); + pJsonObject->Add(pCompleteKey, toJson(getComplete(), "Boolean", "")); + + + return pJsonObject; +} + +Long* +SamiOrder::getId() { + return pId; +} +void +SamiOrder::setId(Long* pId) { + this->pId = pId; +} + +Long* +SamiOrder::getPetId() { + return pPetId; +} +void +SamiOrder::setPetId(Long* pPetId) { + this->pPetId = pPetId; +} + +Integer* +SamiOrder::getQuantity() { + return pQuantity; +} +void +SamiOrder::setQuantity(Integer* pQuantity) { + this->pQuantity = pQuantity; +} + +DateTime* +SamiOrder::getShipDate() { + return pShipDate; +} +void +SamiOrder::setShipDate(DateTime* pShipDate) { + this->pShipDate = pShipDate; +} + +String* +SamiOrder::getStatus() { + return pStatus; +} +void +SamiOrder::setStatus(String* pStatus) { + this->pStatus = pStatus; +} + +Boolean* +SamiOrder::getComplete() { + return pComplete; +} +void +SamiOrder::setComplete(Boolean* pComplete) { + this->pComplete = pComplete; +} + + + +} /* namespace Swagger */ + diff --git a/samples/client/petstore/tizen/client/SamiOrder.h b/samples/client/petstore/tizen/client/SamiOrder.h new file mode 100644 index 000000000000..88dcda673953 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiOrder.h @@ -0,0 +1,79 @@ +/* + * SamiOrder.h + * + * + */ + +#ifndef SamiOrder_H_ +#define SamiOrder_H_ + +#include +#include +#include +#include +#include "SamiHelpers.h" +#include "SamiObject.h" + +using namespace Tizen::Web::Json; + + +using Tizen::Base::Long; +using Tizen::Base::DateTime; +using Tizen::Base::String; +using Tizen::Base::Boolean; +using Tizen::Base::Integer; + + +namespace Swagger { + +class SamiOrder: public SamiObject { +public: + SamiOrder(); + SamiOrder(String* json); + virtual ~SamiOrder(); + + void init(); + + void cleanup(); + + String asJson (); + + JsonObject* asJsonObject(); + + void fromJsonObject(IJsonValue* json); + + SamiOrder* fromJson(String* obj); + + + Long* getId(); + void setId(Long* pId); + + Long* getPetId(); + void setPetId(Long* pPetId); + + Integer* getQuantity(); + void setQuantity(Integer* pQuantity); + + DateTime* getShipDate(); + void setShipDate(DateTime* pShipDate); + + String* getStatus(); + void setStatus(String* pStatus); + + Boolean* getComplete(); + void setComplete(Boolean* pComplete); + + +private: + Long* pId; + Long* pPetId; + Integer* pQuantity; + DateTime* pShipDate; + String* pStatus; + Boolean* pComplete; + +}; + +} /* namespace Swagger */ + +#endif /* SamiOrder_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiPet.cpp b/samples/client/petstore/tizen/client/SamiPet.cpp new file mode 100644 index 000000000000..c45c850e35d7 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiPet.cpp @@ -0,0 +1,294 @@ + +#include "SamiPet.h" +#include + +using namespace Tizen::Base; +using namespace Tizen::System; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; +using namespace Tizen::Web::Json; +using namespace Tizen::Locales; + + +namespace Swagger { + +SamiPet::SamiPet() { + init(); +} + +SamiPet::~SamiPet() { + this->cleanup(); +} + +void +SamiPet::init() { + pId = null; + pCategory = null; + pName = null; + pPhotoUrls = null; + pTags = null; + pStatus = null; + +} + +void +SamiPet::cleanup() { + if(pId != null) { + + delete pId; + pId = null; + } + if(pCategory != null) { + + delete pCategory; + pCategory = null; + } + if(pName != null) { + + delete pName; + pName = null; + } + if(pPhotoUrls != null) { + pPhotoUrls->RemoveAll(true); + delete pPhotoUrls; + pPhotoUrls = null; + } + if(pTags != null) { + pTags->RemoveAll(true); + delete pTags; + pTags = null; + } + if(pStatus != null) { + + delete pStatus; + pStatus = null; + } + +} + + +SamiPet* +SamiPet::fromJson(String* json) { + this->cleanup(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; + return this; +} + + +void +SamiPet::fromJsonObject(IJsonValue* pJson) { + JsonObject* pJsonObject = static_cast< JsonObject* >(pJson); + + if(pJsonObject != null) { + JsonString* pIdKey = new JsonString(L"id"); + IJsonValue* pIdVal = null; + pJsonObject->GetValue(pIdKey, pIdVal); + if(pIdVal != null) { + + pId = new Long(); + jsonToValue(pId, pIdVal, L"Long", L"Long"); + } + delete pIdKey; + JsonString* pCategoryKey = new JsonString(L"category"); + IJsonValue* pCategoryVal = null; + pJsonObject->GetValue(pCategoryKey, pCategoryVal); + if(pCategoryVal != null) { + + pCategory = new SamiCategory(); + jsonToValue(pCategory, pCategoryVal, L"SamiCategory", L"SamiCategory"); + } + delete pCategoryKey; + JsonString* pNameKey = new JsonString(L"name"); + IJsonValue* pNameVal = null; + pJsonObject->GetValue(pNameKey, pNameVal); + if(pNameVal != null) { + + pName = new String(); + jsonToValue(pName, pNameVal, L"String", L"String"); + } + delete pNameKey; + JsonString* pPhotoUrlsKey = new JsonString(L"photoUrls"); + IJsonValue* pPhotoUrlsVal = null; + pJsonObject->GetValue(pPhotoUrlsKey, pPhotoUrlsVal); + if(pPhotoUrlsVal != null) { + pPhotoUrls = new ArrayList(); + + jsonToValue(pPhotoUrls, pPhotoUrlsVal, L"IList", L"String"); + } + delete pPhotoUrlsKey; + JsonString* pTagsKey = new JsonString(L"tags"); + IJsonValue* pTagsVal = null; + pJsonObject->GetValue(pTagsKey, pTagsVal); + if(pTagsVal != null) { + pTags = new ArrayList(); + + jsonToValue(pTags, pTagsVal, L"IList", L"SamiTag"); + } + delete pTagsKey; + JsonString* pStatusKey = new JsonString(L"status"); + IJsonValue* pStatusVal = null; + pJsonObject->GetValue(pStatusKey, pStatusVal); + if(pStatusVal != null) { + + pStatus = new String(); + jsonToValue(pStatus, pStatusVal, L"String", L"String"); + } + delete pStatusKey; + + } +} + +SamiPet::SamiPet(String* json) { + init(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; +} + +String +SamiPet::asJson () +{ + JsonObject* pJsonObject = asJsonObject(); + + char *pComposeBuf = new char[256]; + JsonWriter::Compose(pJsonObject, pComposeBuf, 256); + String s = String(pComposeBuf); + + delete pComposeBuf; + pJsonObject->RemoveAll(true); + delete pJsonObject; + + return s; +} + +JsonObject* +SamiPet::asJsonObject() { + JsonObject *pJsonObject = new JsonObject(); + pJsonObject->Construct(); + + + JsonString *pIdKey = new JsonString(L"id"); + pJsonObject->Add(pIdKey, toJson(getId(), "Long", "")); + + + JsonString *pCategoryKey = new JsonString(L"category"); + pJsonObject->Add(pCategoryKey, toJson(getCategory(), "SamiCategory", "")); + + + JsonString *pNameKey = new JsonString(L"name"); + pJsonObject->Add(pNameKey, toJson(getName(), "String", "")); + + + JsonString *pPhotoUrlsKey = new JsonString(L"photoUrls"); + pJsonObject->Add(pPhotoUrlsKey, toJson(getPhotoUrls(), "String", "array")); + + + JsonString *pTagsKey = new JsonString(L"tags"); + pJsonObject->Add(pTagsKey, toJson(getTags(), "SamiTag", "array")); + + + JsonString *pStatusKey = new JsonString(L"status"); + pJsonObject->Add(pStatusKey, toJson(getStatus(), "String", "")); + + + return pJsonObject; +} + +Long* +SamiPet::getId() { + return pId; +} +void +SamiPet::setId(Long* pId) { + this->pId = pId; +} + +SamiCategory* +SamiPet::getCategory() { + return pCategory; +} +void +SamiPet::setCategory(SamiCategory* pCategory) { + this->pCategory = pCategory; +} + +String* +SamiPet::getName() { + return pName; +} +void +SamiPet::setName(String* pName) { + this->pName = pName; +} + +IList* +SamiPet::getPhotoUrls() { + return pPhotoUrls; +} +void +SamiPet::setPhotoUrls(IList* pPhotoUrls) { + this->pPhotoUrls = pPhotoUrls; +} + +IList* +SamiPet::getTags() { + return pTags; +} +void +SamiPet::setTags(IList* pTags) { + this->pTags = pTags; +} + +String* +SamiPet::getStatus() { + return pStatus; +} +void +SamiPet::setStatus(String* pStatus) { + this->pStatus = pStatus; +} + + + +} /* namespace Swagger */ + diff --git a/samples/client/petstore/tizen/client/SamiPet.h b/samples/client/petstore/tizen/client/SamiPet.h new file mode 100644 index 000000000000..9e3ab43bdc7b --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiPet.h @@ -0,0 +1,79 @@ +/* + * SamiPet.h + * + * + */ + +#ifndef SamiPet_H_ +#define SamiPet_H_ + +#include +#include +#include +#include +#include "SamiHelpers.h" +#include "SamiObject.h" + +using namespace Tizen::Web::Json; + + +#include "SamiCategory.h" +using Tizen::Base::Long; +using Tizen::Base::String; +#include "SamiTag.h" +using Tizen::Base::Collection::IList; + + +namespace Swagger { + +class SamiPet: public SamiObject { +public: + SamiPet(); + SamiPet(String* json); + virtual ~SamiPet(); + + void init(); + + void cleanup(); + + String asJson (); + + JsonObject* asJsonObject(); + + void fromJsonObject(IJsonValue* json); + + SamiPet* fromJson(String* obj); + + + Long* getId(); + void setId(Long* pId); + + SamiCategory* getCategory(); + void setCategory(SamiCategory* pCategory); + + String* getName(); + void setName(String* pName); + + IList* getPhotoUrls(); + void setPhotoUrls(IList* pPhotoUrls); + + IList* getTags(); + void setTags(IList* pTags); + + String* getStatus(); + void setStatus(String* pStatus); + + +private: + Long* pId; + SamiCategory* pCategory; + String* pName; + IList* pPhotoUrls; + IList* pTags; + String* pStatus; + +}; + +} /* namespace Swagger */ + +#endif /* SamiPet_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiPetApi.cpp b/samples/client/petstore/tizen/client/SamiPetApi.cpp new file mode 100644 index 000000000000..35c4900a9ac3 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiPetApi.cpp @@ -0,0 +1,464 @@ +#include "SamiPetApi.h" + +#include "SamiHelpers.h" +#include "SamiError.h" + +using namespace Tizen::Base; + +namespace Swagger { + + +SamiPetApi::SamiPetApi() { + +} + +SamiPetApi::~SamiPetApi() { + +} + +void +updatePetProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiPetApi::updatePetWithCompletion(SamiPet* body, void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&updatePetProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + + if(body != null) { + mBody = new String(body->asJson()); + headerParams->Add(new String("Content-Type"), new String("application/json")); + } + + + + String url(L"/pet"); + + + + client->execute(SamiPetApi::getBasePath(), url, "PUT", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + +void +addPetProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiPetApi::addPetWithCompletion(SamiPet* body, void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&addPetProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + + if(body != null) { + mBody = new String(body->asJson()); + headerParams->Add(new String("Content-Type"), new String("application/json")); + } + + + + String url(L"/pet"); + + + + client->execute(SamiPetApi::getBasePath(), url, "POST", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + +void +findPetsByStatusProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + ByteBuffer* pBuffer = pHttpResponse->ReadBodyN(); + IJsonValue* pJson = JsonParser::ParseN(*pBuffer); + + IList* out = new ArrayList(); + jsonToValue(out, pJson, L"IList*", L"SamiPet"); + + if (pJson) { + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + handler(out, null); + } + else { + SamiError* error = new SamiError(0, new String(L"No parsable response received")); + handler(null, error); + } + + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + handler(null, error); + + } +} + +IList* +SamiPetApi::findPetsByStatusWithCompletion(IList* status, void (* success)(IList*, SamiError*)) { + client = new SamiApiClient(); + + client->success(&findPetsByStatusProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + int sz = status->GetCount(); + for(int i = 0; i < sz; i++) { + String itemAt = stringify(status->GetAt(i), "String*"); + queryParams->Add(new String("status"), new String(itemAt)); + } + + + + String* mBody = null; + + + + String url(L"/pet/findByStatus"); + + + + client->execute(SamiPetApi::getBasePath(), url, "GET", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + return null; +} + +void +findPetsByTagsProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + ByteBuffer* pBuffer = pHttpResponse->ReadBodyN(); + IJsonValue* pJson = JsonParser::ParseN(*pBuffer); + + IList* out = new ArrayList(); + jsonToValue(out, pJson, L"IList*", L"SamiPet"); + + if (pJson) { + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + handler(out, null); + } + else { + SamiError* error = new SamiError(0, new String(L"No parsable response received")); + handler(null, error); + } + + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + handler(null, error); + + } +} + +IList* +SamiPetApi::findPetsByTagsWithCompletion(IList* tags, void (* success)(IList*, SamiError*)) { + client = new SamiApiClient(); + + client->success(&findPetsByTagsProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + int sz = tags->GetCount(); + for(int i = 0; i < sz; i++) { + String itemAt = stringify(tags->GetAt(i), "String*"); + queryParams->Add(new String("tags"), new String(itemAt)); + } + + + + String* mBody = null; + + + + String url(L"/pet/findByTags"); + + + + client->execute(SamiPetApi::getBasePath(), url, "GET", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + return null; +} + +void +getPetByIdProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + ByteBuffer* pBuffer = pHttpResponse->ReadBodyN(); + IJsonValue* pJson = JsonParser::ParseN(*pBuffer); + + SamiPet* out = new SamiPet(); + jsonToValue(out, pJson, L"SamiPet*", L"SamiPet"); + + if (pJson) { + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + handler(out, null); + } + else { + SamiError* error = new SamiError(0, new String(L"No parsable response received")); + handler(null, error); + } + + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + handler(null, error); + + } +} + +SamiPet* +SamiPetApi::getPetByIdWithCompletion(Long* petId, void (* success)(SamiPet*, SamiError*)) { + client = new SamiApiClient(); + + client->success(&getPetByIdProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + String url(L"/pet/{petId}"); + + + String s_petId(L"{"); + s_petId.Append(L"petId"); + s_petId.Append(L"}"); + url.Replace(s_petId, stringify(petId, L"Long*")); + + + client->execute(SamiPetApi::getBasePath(), url, "GET", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + return null; +} + +void +updatePetWithFormProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiPetApi::updatePetWithFormWithCompletion(String* petId, String* name, String* status, void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&updatePetWithFormProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + String url(L"/pet/{petId}"); + + + String s_petId(L"{"); + s_petId.Append(L"petId"); + s_petId.Append(L"}"); + url.Replace(s_petId, stringify(petId, L"String*")); + + + client->execute(SamiPetApi::getBasePath(), url, "POST", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + +void +deletePetProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiPetApi::deletePetWithCompletion(String* api_key, Long* petId, void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&deletePetProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + headerParams->Add(new String("api_key"), api_key); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + String url(L"/pet/{petId}"); + + + String s_petId(L"{"); + s_petId.Append(L"petId"); + s_petId.Append(L"}"); + url.Replace(s_petId, stringify(petId, L"Long*")); + + + client->execute(SamiPetApi::getBasePath(), url, "DELETE", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + +void +uploadFileProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiPetApi::uploadFileWithCompletion(Long* petId, String* additionalMetadata, SamiFile* file, void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&uploadFileProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + String url(L"/pet/{petId}/uploadImage"); + + + String s_petId(L"{"); + s_petId.Append(L"petId"); + s_petId.Append(L"}"); + url.Replace(s_petId, stringify(petId, L"Long*")); + + + client->execute(SamiPetApi::getBasePath(), url, "POST", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + + +} /* namespace Swagger */ diff --git a/samples/client/petstore/tizen/client/SamiPetApi.h b/samples/client/petstore/tizen/client/SamiPetApi.h new file mode 100644 index 000000000000..10a957a87b8a --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiPetApi.h @@ -0,0 +1,58 @@ +#ifndef SamiPetApi_H_ +#define SamiPetApi_H_ + +#include +#include "SamiApiClient.h" +#include "SamiError.h" + +#include "SamiPet.h" +using Tizen::Base::String; +using Tizen::Base::Long; +#include "SamiFile.h" + +using namespace Tizen::Net::Http; + +namespace Swagger { + +class SamiPetApi { +public: + SamiPetApi(); + virtual ~SamiPetApi(); + + + void + updatePetWithCompletion(SamiPet* body, void(* handler)(SamiError*)); + + void + addPetWithCompletion(SamiPet* body, void(* handler)(SamiError*)); + + IList* + findPetsByStatusWithCompletion(IList* status, void (* handler)(IList*, SamiError*)); + + IList* + findPetsByTagsWithCompletion(IList* tags, void (* handler)(IList*, SamiError*)); + + SamiPet* + getPetByIdWithCompletion(Long* petId, void (* handler)(SamiPet*, SamiError*)); + + void + updatePetWithFormWithCompletion(String* petId, String* name, String* status, void(* handler)(SamiError*)); + + void + deletePetWithCompletion(String* api_key, Long* petId, void(* handler)(SamiError*)); + + void + uploadFileWithCompletion(Long* petId, String* additionalMetadata, SamiFile* file, void(* handler)(SamiError*)); + + static String getBasePath() { + return L"http://petstore.swagger.io/v2"; + } + +private: + SamiApiClient* client; +}; + + +} /* namespace Swagger */ + +#endif /* SamiPetApi_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiStoreApi.cpp b/samples/client/petstore/tizen/client/SamiStoreApi.cpp new file mode 100644 index 000000000000..c567896c48d3 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiStoreApi.cpp @@ -0,0 +1,265 @@ +#include "SamiStoreApi.h" + +#include "SamiHelpers.h" +#include "SamiError.h" + +using namespace Tizen::Base; + +namespace Swagger { + + +SamiStoreApi::SamiStoreApi() { + +} + +SamiStoreApi::~SamiStoreApi() { + +} + +void +getInventoryProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + ByteBuffer* pBuffer = pHttpResponse->ReadBodyN(); + IJsonValue* pJson = JsonParser::ParseN(*pBuffer); + + HashMap* out = new HashMap(); + jsonToValue(out, pJson, L"HashMap*", L"Integer"); + + if (pJson) { + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + handler(out, null); + } + else { + SamiError* error = new SamiError(0, new String(L"No parsable response received")); + handler(null, error); + } + + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + handler(null, error); + + } +} + +HashMap* +SamiStoreApi::getInventoryWithCompletion( void (* success)(HashMap*, SamiError*)) { + client = new SamiApiClient(); + + client->success(&getInventoryProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + String url(L"/store/inventory"); + + + + client->execute(SamiStoreApi::getBasePath(), url, "GET", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + return null; +} + +void +placeOrderProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + ByteBuffer* pBuffer = pHttpResponse->ReadBodyN(); + IJsonValue* pJson = JsonParser::ParseN(*pBuffer); + + SamiOrder* out = new SamiOrder(); + jsonToValue(out, pJson, L"SamiOrder*", L"SamiOrder"); + + if (pJson) { + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + handler(out, null); + } + else { + SamiError* error = new SamiError(0, new String(L"No parsable response received")); + handler(null, error); + } + + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + handler(null, error); + + } +} + +SamiOrder* +SamiStoreApi::placeOrderWithCompletion(SamiOrder* body, void (* success)(SamiOrder*, SamiError*)) { + client = new SamiApiClient(); + + client->success(&placeOrderProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + + if(body != null) { + mBody = new String(body->asJson()); + headerParams->Add(new String("Content-Type"), new String("application/json")); + } + + + + String url(L"/store/order"); + + + + client->execute(SamiStoreApi::getBasePath(), url, "POST", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + return null; +} + +void +getOrderByIdProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + ByteBuffer* pBuffer = pHttpResponse->ReadBodyN(); + IJsonValue* pJson = JsonParser::ParseN(*pBuffer); + + SamiOrder* out = new SamiOrder(); + jsonToValue(out, pJson, L"SamiOrder*", L"SamiOrder"); + + if (pJson) { + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + handler(out, null); + } + else { + SamiError* error = new SamiError(0, new String(L"No parsable response received")); + handler(null, error); + } + + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + handler(null, error); + + } +} + +SamiOrder* +SamiStoreApi::getOrderByIdWithCompletion(String* orderId, void (* success)(SamiOrder*, SamiError*)) { + client = new SamiApiClient(); + + client->success(&getOrderByIdProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + String url(L"/store/order/{orderId}"); + + + String s_orderId(L"{"); + s_orderId.Append(L"orderId"); + s_orderId.Append(L"}"); + url.Replace(s_orderId, stringify(orderId, L"String*")); + + + client->execute(SamiStoreApi::getBasePath(), url, "GET", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + return null; +} + +void +deleteOrderProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiStoreApi::deleteOrderWithCompletion(String* orderId, void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&deleteOrderProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + String url(L"/store/order/{orderId}"); + + + String s_orderId(L"{"); + s_orderId.Append(L"orderId"); + s_orderId.Append(L"}"); + url.Replace(s_orderId, stringify(orderId, L"String*")); + + + client->execute(SamiStoreApi::getBasePath(), url, "DELETE", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + + +} /* namespace Swagger */ diff --git a/samples/client/petstore/tizen/client/SamiStoreApi.h b/samples/client/petstore/tizen/client/SamiStoreApi.h new file mode 100644 index 000000000000..a36f4ba6ee9c --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiStoreApi.h @@ -0,0 +1,45 @@ +#ifndef SamiStoreApi_H_ +#define SamiStoreApi_H_ + +#include +#include "SamiApiClient.h" +#include "SamiError.h" + +using Tizen::Base::Integer; +#include "SamiOrder.h" +using Tizen::Base::String; + +using namespace Tizen::Net::Http; + +namespace Swagger { + +class SamiStoreApi { +public: + SamiStoreApi(); + virtual ~SamiStoreApi(); + + + HashMap* + getInventoryWithCompletion( void (* handler)(HashMap*, SamiError*)); + + SamiOrder* + placeOrderWithCompletion(SamiOrder* body, void (* handler)(SamiOrder*, SamiError*)); + + SamiOrder* + getOrderByIdWithCompletion(String* orderId, void (* handler)(SamiOrder*, SamiError*)); + + void + deleteOrderWithCompletion(String* orderId, void(* handler)(SamiError*)); + + static String getBasePath() { + return L"http://petstore.swagger.io/v2"; + } + +private: + SamiApiClient* client; +}; + + +} /* namespace Swagger */ + +#endif /* SamiStoreApi_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiTag.cpp b/samples/client/petstore/tizen/client/SamiTag.cpp new file mode 100644 index 000000000000..61cc00f35fe5 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiTag.cpp @@ -0,0 +1,182 @@ + +#include "SamiTag.h" +#include + +using namespace Tizen::Base; +using namespace Tizen::System; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; +using namespace Tizen::Web::Json; +using namespace Tizen::Locales; + + +namespace Swagger { + +SamiTag::SamiTag() { + init(); +} + +SamiTag::~SamiTag() { + this->cleanup(); +} + +void +SamiTag::init() { + pId = null; + pName = null; + +} + +void +SamiTag::cleanup() { + if(pId != null) { + + delete pId; + pId = null; + } + if(pName != null) { + + delete pName; + pName = null; + } + +} + + +SamiTag* +SamiTag::fromJson(String* json) { + this->cleanup(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; + return this; +} + + +void +SamiTag::fromJsonObject(IJsonValue* pJson) { + JsonObject* pJsonObject = static_cast< JsonObject* >(pJson); + + if(pJsonObject != null) { + JsonString* pIdKey = new JsonString(L"id"); + IJsonValue* pIdVal = null; + pJsonObject->GetValue(pIdKey, pIdVal); + if(pIdVal != null) { + + pId = new Long(); + jsonToValue(pId, pIdVal, L"Long", L"Long"); + } + delete pIdKey; + JsonString* pNameKey = new JsonString(L"name"); + IJsonValue* pNameVal = null; + pJsonObject->GetValue(pNameKey, pNameVal); + if(pNameVal != null) { + + pName = new String(); + jsonToValue(pName, pNameVal, L"String", L"String"); + } + delete pNameKey; + + } +} + +SamiTag::SamiTag(String* json) { + init(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; +} + +String +SamiTag::asJson () +{ + JsonObject* pJsonObject = asJsonObject(); + + char *pComposeBuf = new char[256]; + JsonWriter::Compose(pJsonObject, pComposeBuf, 256); + String s = String(pComposeBuf); + + delete pComposeBuf; + pJsonObject->RemoveAll(true); + delete pJsonObject; + + return s; +} + +JsonObject* +SamiTag::asJsonObject() { + JsonObject *pJsonObject = new JsonObject(); + pJsonObject->Construct(); + + + JsonString *pIdKey = new JsonString(L"id"); + pJsonObject->Add(pIdKey, toJson(getId(), "Long", "")); + + + JsonString *pNameKey = new JsonString(L"name"); + pJsonObject->Add(pNameKey, toJson(getName(), "String", "")); + + + return pJsonObject; +} + +Long* +SamiTag::getId() { + return pId; +} +void +SamiTag::setId(Long* pId) { + this->pId = pId; +} + +String* +SamiTag::getName() { + return pName; +} +void +SamiTag::setName(String* pName) { + this->pName = pName; +} + + + +} /* namespace Swagger */ + diff --git a/samples/client/petstore/tizen/client/SamiTag.h b/samples/client/petstore/tizen/client/SamiTag.h new file mode 100644 index 000000000000..53a4134a51d8 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiTag.h @@ -0,0 +1,60 @@ +/* + * SamiTag.h + * + * + */ + +#ifndef SamiTag_H_ +#define SamiTag_H_ + +#include +#include +#include +#include +#include "SamiHelpers.h" +#include "SamiObject.h" + +using namespace Tizen::Web::Json; + + +using Tizen::Base::Long; +using Tizen::Base::String; + + +namespace Swagger { + +class SamiTag: public SamiObject { +public: + SamiTag(); + SamiTag(String* json); + virtual ~SamiTag(); + + void init(); + + void cleanup(); + + String asJson (); + + JsonObject* asJsonObject(); + + void fromJsonObject(IJsonValue* json); + + SamiTag* fromJson(String* obj); + + + Long* getId(); + void setId(Long* pId); + + String* getName(); + void setName(String* pName); + + +private: + Long* pId; + String* pName; + +}; + +} /* namespace Swagger */ + +#endif /* SamiTag_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiUser.cpp b/samples/client/petstore/tizen/client/SamiUser.cpp new file mode 100644 index 000000000000..9701a45f28c5 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiUser.cpp @@ -0,0 +1,350 @@ + +#include "SamiUser.h" +#include + +using namespace Tizen::Base; +using namespace Tizen::System; +using namespace Tizen::Base::Utility; +using namespace Tizen::Base::Collection; +using namespace Tizen::Web::Json; +using namespace Tizen::Locales; + + +namespace Swagger { + +SamiUser::SamiUser() { + init(); +} + +SamiUser::~SamiUser() { + this->cleanup(); +} + +void +SamiUser::init() { + pId = null; + pUsername = null; + pFirstName = null; + pLastName = null; + pEmail = null; + pPassword = null; + pPhone = null; + pUserStatus = null; + +} + +void +SamiUser::cleanup() { + if(pId != null) { + + delete pId; + pId = null; + } + if(pUsername != null) { + + delete pUsername; + pUsername = null; + } + if(pFirstName != null) { + + delete pFirstName; + pFirstName = null; + } + if(pLastName != null) { + + delete pLastName; + pLastName = null; + } + if(pEmail != null) { + + delete pEmail; + pEmail = null; + } + if(pPassword != null) { + + delete pPassword; + pPassword = null; + } + if(pPhone != null) { + + delete pPhone; + pPhone = null; + } + if(pUserStatus != null) { + + delete pUserStatus; + pUserStatus = null; + } + +} + + +SamiUser* +SamiUser::fromJson(String* json) { + this->cleanup(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; + return this; +} + + +void +SamiUser::fromJsonObject(IJsonValue* pJson) { + JsonObject* pJsonObject = static_cast< JsonObject* >(pJson); + + if(pJsonObject != null) { + JsonString* pIdKey = new JsonString(L"id"); + IJsonValue* pIdVal = null; + pJsonObject->GetValue(pIdKey, pIdVal); + if(pIdVal != null) { + + pId = new Long(); + jsonToValue(pId, pIdVal, L"Long", L"Long"); + } + delete pIdKey; + JsonString* pUsernameKey = new JsonString(L"username"); + IJsonValue* pUsernameVal = null; + pJsonObject->GetValue(pUsernameKey, pUsernameVal); + if(pUsernameVal != null) { + + pUsername = new String(); + jsonToValue(pUsername, pUsernameVal, L"String", L"String"); + } + delete pUsernameKey; + JsonString* pFirstNameKey = new JsonString(L"firstName"); + IJsonValue* pFirstNameVal = null; + pJsonObject->GetValue(pFirstNameKey, pFirstNameVal); + if(pFirstNameVal != null) { + + pFirstName = new String(); + jsonToValue(pFirstName, pFirstNameVal, L"String", L"String"); + } + delete pFirstNameKey; + JsonString* pLastNameKey = new JsonString(L"lastName"); + IJsonValue* pLastNameVal = null; + pJsonObject->GetValue(pLastNameKey, pLastNameVal); + if(pLastNameVal != null) { + + pLastName = new String(); + jsonToValue(pLastName, pLastNameVal, L"String", L"String"); + } + delete pLastNameKey; + JsonString* pEmailKey = new JsonString(L"email"); + IJsonValue* pEmailVal = null; + pJsonObject->GetValue(pEmailKey, pEmailVal); + if(pEmailVal != null) { + + pEmail = new String(); + jsonToValue(pEmail, pEmailVal, L"String", L"String"); + } + delete pEmailKey; + JsonString* pPasswordKey = new JsonString(L"password"); + IJsonValue* pPasswordVal = null; + pJsonObject->GetValue(pPasswordKey, pPasswordVal); + if(pPasswordVal != null) { + + pPassword = new String(); + jsonToValue(pPassword, pPasswordVal, L"String", L"String"); + } + delete pPasswordKey; + JsonString* pPhoneKey = new JsonString(L"phone"); + IJsonValue* pPhoneVal = null; + pJsonObject->GetValue(pPhoneKey, pPhoneVal); + if(pPhoneVal != null) { + + pPhone = new String(); + jsonToValue(pPhone, pPhoneVal, L"String", L"String"); + } + delete pPhoneKey; + JsonString* pUserStatusKey = new JsonString(L"userStatus"); + IJsonValue* pUserStatusVal = null; + pJsonObject->GetValue(pUserStatusKey, pUserStatusVal); + if(pUserStatusVal != null) { + + pUserStatus = new Integer(); + jsonToValue(pUserStatus, pUserStatusVal, L"Integer", L"Integer"); + } + delete pUserStatusKey; + + } +} + +SamiUser::SamiUser(String* json) { + init(); + String str(json->GetPointer()); + int length = str.GetLength(); + + ByteBuffer buffer; + buffer.Construct(length); + + for (int i = 0; i < length; ++i) { + byte b = str[i]; + buffer.SetByte(b); + } + + IJsonValue* pJson = JsonParser::ParseN(buffer); + fromJsonObject(pJson); + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + delete pJson; +} + +String +SamiUser::asJson () +{ + JsonObject* pJsonObject = asJsonObject(); + + char *pComposeBuf = new char[256]; + JsonWriter::Compose(pJsonObject, pComposeBuf, 256); + String s = String(pComposeBuf); + + delete pComposeBuf; + pJsonObject->RemoveAll(true); + delete pJsonObject; + + return s; +} + +JsonObject* +SamiUser::asJsonObject() { + JsonObject *pJsonObject = new JsonObject(); + pJsonObject->Construct(); + + + JsonString *pIdKey = new JsonString(L"id"); + pJsonObject->Add(pIdKey, toJson(getId(), "Long", "")); + + + JsonString *pUsernameKey = new JsonString(L"username"); + pJsonObject->Add(pUsernameKey, toJson(getUsername(), "String", "")); + + + JsonString *pFirstNameKey = new JsonString(L"firstName"); + pJsonObject->Add(pFirstNameKey, toJson(getFirstName(), "String", "")); + + + JsonString *pLastNameKey = new JsonString(L"lastName"); + pJsonObject->Add(pLastNameKey, toJson(getLastName(), "String", "")); + + + JsonString *pEmailKey = new JsonString(L"email"); + pJsonObject->Add(pEmailKey, toJson(getEmail(), "String", "")); + + + JsonString *pPasswordKey = new JsonString(L"password"); + pJsonObject->Add(pPasswordKey, toJson(getPassword(), "String", "")); + + + JsonString *pPhoneKey = new JsonString(L"phone"); + pJsonObject->Add(pPhoneKey, toJson(getPhone(), "String", "")); + + + JsonString *pUserStatusKey = new JsonString(L"userStatus"); + pJsonObject->Add(pUserStatusKey, toJson(getUserStatus(), "Integer", "")); + + + return pJsonObject; +} + +Long* +SamiUser::getId() { + return pId; +} +void +SamiUser::setId(Long* pId) { + this->pId = pId; +} + +String* +SamiUser::getUsername() { + return pUsername; +} +void +SamiUser::setUsername(String* pUsername) { + this->pUsername = pUsername; +} + +String* +SamiUser::getFirstName() { + return pFirstName; +} +void +SamiUser::setFirstName(String* pFirstName) { + this->pFirstName = pFirstName; +} + +String* +SamiUser::getLastName() { + return pLastName; +} +void +SamiUser::setLastName(String* pLastName) { + this->pLastName = pLastName; +} + +String* +SamiUser::getEmail() { + return pEmail; +} +void +SamiUser::setEmail(String* pEmail) { + this->pEmail = pEmail; +} + +String* +SamiUser::getPassword() { + return pPassword; +} +void +SamiUser::setPassword(String* pPassword) { + this->pPassword = pPassword; +} + +String* +SamiUser::getPhone() { + return pPhone; +} +void +SamiUser::setPhone(String* pPhone) { + this->pPhone = pPhone; +} + +Integer* +SamiUser::getUserStatus() { + return pUserStatus; +} +void +SamiUser::setUserStatus(Integer* pUserStatus) { + this->pUserStatus = pUserStatus; +} + + + +} /* namespace Swagger */ + diff --git a/samples/client/petstore/tizen/client/SamiUser.h b/samples/client/petstore/tizen/client/SamiUser.h new file mode 100644 index 000000000000..dd24429dbab1 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiUser.h @@ -0,0 +1,85 @@ +/* + * SamiUser.h + * + * + */ + +#ifndef SamiUser_H_ +#define SamiUser_H_ + +#include +#include +#include +#include +#include "SamiHelpers.h" +#include "SamiObject.h" + +using namespace Tizen::Web::Json; + + +using Tizen::Base::Long; +using Tizen::Base::String; +using Tizen::Base::Integer; + + +namespace Swagger { + +class SamiUser: public SamiObject { +public: + SamiUser(); + SamiUser(String* json); + virtual ~SamiUser(); + + void init(); + + void cleanup(); + + String asJson (); + + JsonObject* asJsonObject(); + + void fromJsonObject(IJsonValue* json); + + SamiUser* fromJson(String* obj); + + + Long* getId(); + void setId(Long* pId); + + String* getUsername(); + void setUsername(String* pUsername); + + String* getFirstName(); + void setFirstName(String* pFirstName); + + String* getLastName(); + void setLastName(String* pLastName); + + String* getEmail(); + void setEmail(String* pEmail); + + String* getPassword(); + void setPassword(String* pPassword); + + String* getPhone(); + void setPhone(String* pPhone); + + Integer* getUserStatus(); + void setUserStatus(Integer* pUserStatus); + + +private: + Long* pId; + String* pUsername; + String* pFirstName; + String* pLastName; + String* pEmail; + String* pPassword; + String* pPhone; + Integer* pUserStatus; + +}; + +} /* namespace Swagger */ + +#endif /* SamiUser_H_ */ diff --git a/samples/client/petstore/tizen/client/SamiUserApi.cpp b/samples/client/petstore/tizen/client/SamiUserApi.cpp new file mode 100644 index 000000000000..7010ed6bac7e --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiUserApi.cpp @@ -0,0 +1,461 @@ +#include "SamiUserApi.h" + +#include "SamiHelpers.h" +#include "SamiError.h" + +using namespace Tizen::Base; + +namespace Swagger { + + +SamiUserApi::SamiUserApi() { + +} + +SamiUserApi::~SamiUserApi() { + +} + +void +createUserProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiUserApi::createUserWithCompletion(SamiUser* body, void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&createUserProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + + if(body != null) { + mBody = new String(body->asJson()); + headerParams->Add(new String("Content-Type"), new String("application/json")); + } + + + + String url(L"/user"); + + + + client->execute(SamiUserApi::getBasePath(), url, "POST", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + +void +createUsersWithArrayInputProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiUserApi::createUsersWithArrayInputWithCompletion(IList* body, void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&createUsersWithArrayInputProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + if(body != null) { + mBody = new String(""); + int sz = body->GetCount(); + for(int i = 0; i < sz; i++) { + SamiObject * obj = (SamiObject*)body->GetAt(i); + String json = obj->asJson(); + if(i > 0) + mBody->Append(","); + mBody->Append(json); + } + mBody->Append("]"); + headerParams->Add(new String("Content-Type"), new String("application/json")); + } + + + + + String url(L"/user/createWithArray"); + + + + client->execute(SamiUserApi::getBasePath(), url, "POST", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + +void +createUsersWithListInputProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiUserApi::createUsersWithListInputWithCompletion(IList* body, void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&createUsersWithListInputProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + if(body != null) { + mBody = new String(""); + int sz = body->GetCount(); + for(int i = 0; i < sz; i++) { + SamiObject * obj = (SamiObject*)body->GetAt(i); + String json = obj->asJson(); + if(i > 0) + mBody->Append(","); + mBody->Append(json); + } + mBody->Append("]"); + headerParams->Add(new String("Content-Type"), new String("application/json")); + } + + + + + String url(L"/user/createWithList"); + + + + client->execute(SamiUserApi::getBasePath(), url, "POST", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + +void +loginUserProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + ByteBuffer* pBuffer = pHttpResponse->ReadBodyN(); + IJsonValue* pJson = JsonParser::ParseN(*pBuffer); + + String* out = new String(); + jsonToValue(out, pJson, L"String*", L"String"); + + if (pJson) { + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + handler(out, null); + } + else { + SamiError* error = new SamiError(0, new String(L"No parsable response received")); + handler(null, error); + } + + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + handler(null, error); + + } +} + +String* +SamiUserApi::loginUserWithCompletion(String* username, String* password, void (* success)(String*, SamiError*)) { + client = new SamiApiClient(); + + client->success(&loginUserProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + queryParams->Add(new String("username"), username); + + + queryParams->Add(new String("password"), password); + + + + String* mBody = null; + + + + String url(L"/user/login"); + + + + client->execute(SamiUserApi::getBasePath(), url, "GET", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + return null; +} + +void +logoutUserProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiUserApi::logoutUserWithCompletion( void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&logoutUserProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + String url(L"/user/logout"); + + + + client->execute(SamiUserApi::getBasePath(), url, "GET", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + +void +getUserByNameProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + ByteBuffer* pBuffer = pHttpResponse->ReadBodyN(); + IJsonValue* pJson = JsonParser::ParseN(*pBuffer); + + SamiUser* out = new SamiUser(); + jsonToValue(out, pJson, L"SamiUser*", L"SamiUser"); + + if (pJson) { + if (pJson->GetType() == JSON_TYPE_OBJECT) { + JsonObject* pObject = static_cast< JsonObject* >(pJson); + pObject->RemoveAll(true); + } + else if (pJson->GetType() == JSON_TYPE_ARRAY) { + JsonArray* pArray = static_cast< JsonArray* >(pJson); + pArray->RemoveAll(true); + } + handler(out, null); + } + else { + SamiError* error = new SamiError(0, new String(L"No parsable response received")); + handler(null, error); + } + + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + handler(null, error); + + } +} + +SamiUser* +SamiUserApi::getUserByNameWithCompletion(String* username, void (* success)(SamiUser*, SamiError*)) { + client = new SamiApiClient(); + + client->success(&getUserByNameProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + String url(L"/user/{username}"); + + + String s_username(L"{"); + s_username.Append(L"username"); + s_username.Append(L"}"); + url.Replace(s_username, stringify(username, L"String*")); + + + client->execute(SamiUserApi::getBasePath(), url, "GET", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + return null; +} + +void +updateUserProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiUserApi::updateUserWithCompletion(String* username, SamiUser* body, void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&updateUserProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + + if(body != null) { + mBody = new String(body->asJson()); + headerParams->Add(new String("Content-Type"), new String("application/json")); + } + + + + String url(L"/user/{username}"); + + + String s_username(L"{"); + s_username.Append(L"username"); + s_username.Append(L"}"); + url.Replace(s_username, stringify(username, L"String*")); + + + client->execute(SamiUserApi::getBasePath(), url, "PUT", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + +void +deleteUserProcessor(HttpResponse* pHttpResponse, void (* handler)(void*, SamiError*)) { + int code = pHttpResponse->GetHttpStatusCode(); + + if(code >= 200 && code < 300) { + handler(null, null); + } + else { + SamiError* error = new SamiError(code, new String(pHttpResponse->GetStatusText())); + + handler(error, null); + } +} + +void +SamiUserApi::deleteUserWithCompletion(String* username, void(*success)(SamiError*)) { + client = new SamiApiClient(); + + client->success(&deleteUserProcessor, (void(*)(void*, SamiError*))success); + HashMap* headerParams = new HashMap(SingleObjectDeleter); + headerParams->Construct(); + + + + HashMap* queryParams = new HashMap(SingleObjectDeleter); + queryParams->Construct(); + + + + String* mBody = null; + + + + String url(L"/user/{username}"); + + + String s_username(L"{"); + s_username.Append(L"username"); + s_username.Append(L"}"); + url.Replace(s_username, stringify(username, L"String*")); + + + client->execute(SamiUserApi::getBasePath(), url, "DELETE", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json"); + +} + + +} /* namespace Swagger */ diff --git a/samples/client/petstore/tizen/client/SamiUserApi.h b/samples/client/petstore/tizen/client/SamiUserApi.h new file mode 100644 index 000000000000..1b42e3bc3b16 --- /dev/null +++ b/samples/client/petstore/tizen/client/SamiUserApi.h @@ -0,0 +1,57 @@ +#ifndef SamiUserApi_H_ +#define SamiUserApi_H_ + +#include +#include "SamiApiClient.h" +#include "SamiError.h" + +#include "SamiUser.h" +using Tizen::Base::Collection::IList; +using Tizen::Base::String; + +using namespace Tizen::Net::Http; + +namespace Swagger { + +class SamiUserApi { +public: + SamiUserApi(); + virtual ~SamiUserApi(); + + + void + createUserWithCompletion(SamiUser* body, void(* handler)(SamiError*)); + + void + createUsersWithArrayInputWithCompletion(IList* body, void(* handler)(SamiError*)); + + void + createUsersWithListInputWithCompletion(IList* body, void(* handler)(SamiError*)); + + String* + loginUserWithCompletion(String* username, String* password, void (* handler)(String*, SamiError*)); + + void + logoutUserWithCompletion( void(* handler)(SamiError*)); + + SamiUser* + getUserByNameWithCompletion(String* username, void (* handler)(SamiUser*, SamiError*)); + + void + updateUserWithCompletion(String* username, SamiUser* body, void(* handler)(SamiError*)); + + void + deleteUserWithCompletion(String* username, void(* handler)(SamiError*)); + + static String getBasePath() { + return L"http://petstore.swagger.io/v2"; + } + +private: + SamiApiClient* client; +}; + + +} /* namespace Swagger */ + +#endif /* SamiUserApi_H_ */ diff --git a/samples/client/wordnik-api-php/wordnik/AccountApi.php b/samples/client/wordnik-api-php/wordnik/AccountApi.php index 77469b43fca4..4e5e4e6d4e1e 100644 --- a/samples/client/wordnik-api-php/wordnik/AccountApi.php +++ b/samples/client/wordnik-api-php/wordnik/AccountApi.php @@ -1,6 +1,6 @@ "wordnik-android-client", - "artifactVersion" -> "1.0.0", - "groupId" -> "com.wordnik") - - // supporting classes - override def supportingFiles = - List( - ("apiInvoker.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiInvoker.java"), - ("JsonUtil.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "JsonUtil.java"), - ("apiException.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiException.java"), - ("pom.mustache", destinationRoot, "pom.xml")) -} diff --git a/samples/client/wordnik-api/android/README.md b/samples/client/wordnik-api/android/README.md deleted file mode 100644 index 6ad4cc8fe6dd..000000000000 --- a/samples/client/wordnik-api/android/README.md +++ /dev/null @@ -1,79 +0,0 @@ -# Wordnik Android client library - -## Overview -This is a full client library for the Wordnik API. It requires that you have a valid Wordnik API Key--you -can get one for free at http://developer.wordnik.com. - -This library is built using the Wordnik [Swagger](http://swagger.wordnik.com) client library generator. You -can re-generate this library by running ./bin/android-java-wordnik-api.sh from the swagger-codegen project - -## Usage -You can use maven central to add this library to your current project: - -```xml - - com.wordnik - wordnik-android-client - 4.0 - -``` - -or with gradle: - -```gradle -repositories { - mavenCentral() -} - -dependencies { - compile 'com.wordnik:wordnik-android-client:4.0' -} -``` - -or you can pull the source and re-generate the client library with Maven: - -``` -mvn package -``` - -Add the library to your project and you're ready to go: - -```java -import com.wordnik.client.api.*; -import com.wordnik.client.model.*; - -import android.os.AsyncTask; -import android.util.Log; - -class WordOfTheDayAsyncTask extends AsyncTask { - @Override - protected WordOfTheDay doInBackground(Void... params) { - WordsApi api = new WordsApi(); - api.addHeader("api_key", "YOUR_API_KEY"); - try { - return api.getWordOfTheDay("2014-02-19"); - } - catch (Exception e) { - Log.d("WordOfTheDayAsyncTask", e.getMessage()); - return null; - } - } - - @Override - protected void onPostExecute(WordOfTheDay d) { - Log.d("WordOfTheDayAsyncTask", d.toString()); - } -} -``` - -You can now invoke the async task anywhere in your app. Of course you'll want to do -something more in your `onPostExecute` function. - -```java -new WordOfTheDayAsyncTask().execute(); -``` - -This project was built with the following minimum requirements: - -* Maven 3.0 -* Java JDK 6 diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ScrabbleScoreResult.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ScrabbleScoreResult.java deleted file mode 100644 index 2528a605d1cc..000000000000 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ScrabbleScoreResult.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.wordnik.client.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -public class ScrabbleScoreResult { - @JsonProperty("value") - private Integer value = null; - public Integer getValue() { - return value; - } - public void setValue(Integer value) { - this.value = value; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ScrabbleScoreResult {\n"); - sb.append(" value: ").append(value).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} - diff --git a/samples/client/wordnik-api/java/JavaWordnikApiCodegen.scala b/samples/client/wordnik-api/java/JavaWordnikApiCodegen.scala deleted file mode 100644 index 7b79b2bc8f73..000000000000 --- a/samples/client/wordnik-api/java/JavaWordnikApiCodegen.scala +++ /dev/null @@ -1,51 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicJavaGenerator - -object JavaWordnikApiCodegen extends BasicJavaGenerator { - def main(args: Array[String]) = generateClient(args) - - // location of templates - override def templateDir = "Java" - - def destinationRoot = "samples/client/wordnik-api/java" - - // where to write generated code - override def destinationDir = destinationRoot + "/src/main/java" - - // package for api invoker, error files - override def invokerPackage = Some("com.wordnik.client.common") - - // package for models - override def modelPackage = Some("com.wordnik.client.model") - - // package for api classes - override def apiPackage = Some("com.wordnik.client.api") - - additionalParams ++= Map( - "artifactId" -> "wordnik-java-client", - "artifactVersion" -> "1.0.0", - "groupId" -> "com.wordnik") - - // supporting classes - override def supportingFiles = - List( - ("apiInvoker.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiInvoker.java"), - ("JsonUtil.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "JsonUtil.java"), - ("apiException.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiException.java"), - ("pom.mustache", destinationRoot, "pom.xml")) -} diff --git a/samples/client/wordnik-api/java/README.md b/samples/client/wordnik-api/java/README.md deleted file mode 100644 index bf545253bae3..000000000000 --- a/samples/client/wordnik-api/java/README.md +++ /dev/null @@ -1,72 +0,0 @@ -# Wordnik Java client library - -## Overview -This is a full client library for the Wordnik API. It requires that you have a valid Wordnik API Key--you -can get one for free at http://developer.wordnik.com. - -This library is built using the Wordnik [Swagger](http://swagger.wordnik.com) client library generator. You -can re-generate this library by running ./bin/java-wordnik-api.sh from the swagger-codegen project - -## Usage -You can use maven central to add this library to your current project: - -```xml - - com.wordnik - wordnik-java-client - 1.0.0 - -``` -or you can pull the source and re-generate the client library with Maven: - -``` -mvn package -``` - -Add the library to your project and you're ready to go: - -```java -import com.wordnik.client.api.*; -import com.wordnik.client.model.*; - -import com.wordnik.client.common.ApiException; - -import java.util.List; - -public class Test { - public static void main(String[] args) { - if(args.length == 0) { - System.out.println("Pass your API key as an argument"); - System.exit(0); - } - String key = args[0]; - - try { - WordApi api = new WordApi(); - api.getInvoker().addDefaultHeader("api_key", key); - List definitions = api.getDefinitions( - "Cat", // word - "noun", // only get definitions which are "nouns" - "wiktionary", // use wiktionary - 3, // fetch only 3 results max - "true", // return related words - "true", // fetch the canonical version of this word (Cat => cat) - "false" // return XML mark-up in response - ); - - for(Definition def : definitions) { - System.out.print(def); - } - } - catch (ApiException e) { - e.printStackTrace(); - } - } -} -``` - - -This project was built with the following minimum requirements: - -* Maven 3.0 -* Java JDK 6 \ No newline at end of file diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/ScrabbleScoreResult.java b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/ScrabbleScoreResult.java deleted file mode 100644 index 71086647e59b..000000000000 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/ScrabbleScoreResult.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.wordnik.client.model; - -public class ScrabbleScoreResult { - private Integer value = null; - public Integer getValue() { - return value; - } - public void setValue(Integer value) { - this.value = value; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ScrabbleScoreResult {\n"); - sb.append(" value: ").append(value).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} - diff --git a/samples/client/wordnik-api/php/PHPWordnikApiCodegen.scala b/samples/client/wordnik-api/php/PHPWordnikApiCodegen.scala deleted file mode 100644 index d66950e49917..000000000000 --- a/samples/client/wordnik-api/php/PHPWordnikApiCodegen.scala +++ /dev/null @@ -1,29 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicPHPGenerator - -import java.io.File - -object PHPWordnikApiCodegen extends BasicPHPGenerator { - def main(args: Array[String]) = generateClient(args) - - override def destinationDir = "samples/client/wordnik-api/php/wordnik" - - override def supportingFiles = List( - ("Swagger.mustache", destinationDir + File.separator + apiPackage.get, "Swagger.php") - ) -} diff --git a/samples/client/wordnik-api/php/README.md b/samples/client/wordnik-api/php/README.md deleted file mode 100644 index 9455aaf04da8..000000000000 --- a/samples/client/wordnik-api/php/README.md +++ /dev/null @@ -1,47 +0,0 @@ -# PHP client for Wordnik.com API - -## Overview - -This is a PHP client for the Wordnik.com v4 API. For more information, see http://developer.wordnik.com/ . - -## Generation - -This client was generated using the provided script: - -``` -/bin/php-wordnik-api.sh -``` - -## Testing - -These tests require PHPUnit. If you require PHPUnit to be installed, first get PEAR: - -```sh -wget http://pear.php.net/go-pear.phar -php -d detect_unicode=0 go-pear.phar -``` - -Then install PHPUnit: - -```sh -pear config-set auto_discover 1 -pear install pear.phpunit.de/PHPUnit -``` - -The tests require you to set three environment varibales: - -```sh -export API_KEY=your api key -export USER_NAME=some wordnik.com username -export PASSWORD=the user's password -``` - -The tests can be run as follows: - -```sh -phpunit tests/AccountApiTest.php -phpunit tests/WordApiTest.php -phpunit tests/WordsApiTest.php -phpunit tests/WordListApiTest.php -phpunit tests/WordListsApiTest.php -``` diff --git a/samples/client/wordnik-api/php/tests/AccountApiTest.php b/samples/client/wordnik-api/php/tests/AccountApiTest.php deleted file mode 100644 index 7f77ffc113c4..000000000000 --- a/samples/client/wordnik-api/php/tests/AccountApiTest.php +++ /dev/null @@ -1,51 +0,0 @@ -authToken = $this->accountApi->authenticate($this->username, - $this->password)->token; - date_default_timezone_set('America/Los_Angeles'); - } - - public function testAuthenticate() { - $res = $this->accountApi->authenticate($this->username, - $this->password); - $this->assertObjectHasAttribute('token', $res); - $this->assertNotEquals(0, $res->userId); - $this->assertObjectHasAttribute('userSignature', $res); - } - - public function testAuthenticatePost() { - $res = $this->accountApi->authenticatePost($this->username, - $this->password); - $this->assertObjectHasAttribute('token', $res); - $this->assertNotEquals(0, $res->userId); - $this->assertObjectHasAttribute('userSignature', $res); - } - - public function testGetWordListsForLoggedInUser() { - $res = $this->accountApi->getWordListsForLoggedInUser($this->authToken); - $this->assertNotEquals(0, count($res)); - } - - public function testGetApiTokenStatus() { - $res = $this->accountApi->getApiTokenStatus(); - $this->assertObjectHasAttribute('valid', $res); - $this->assertNotEquals(0, count($res->remainingCalls)); - } - - public function testGetLoggedInUser() { - $res = $this->accountApi->getLoggedInUser($this->authToken); - $this->assertNotEquals(0, $res->id); - $this->assertEquals($this->username, $res->username); - $this->assertEquals(0, $res->status); - $this->assertNotEquals(null, $res->email); - } - - -} -?> diff --git a/samples/client/wordnik-api/php/tests/BaseApiTest.php b/samples/client/wordnik-api/php/tests/BaseApiTest.php deleted file mode 100644 index ac32b6897782..000000000000 --- a/samples/client/wordnik-api/php/tests/BaseApiTest.php +++ /dev/null @@ -1,56 +0,0 @@ -apiUrl = 'https://api.wordnik.com/v4'; - $this->apiKey = getenv('API_KEY'); - $this->username = getenv('USER_NAME'); - $this->password = getenv('PASSWORD'); - $this->client = new APIClient($this->apiKey, $this->apiUrl); - $this->accountApi = new AccountApi($this->client); - $this->wordApi = new WordApi($this->client); - $this->wordListApi = new WordListApi($this->client); - $this->wordListsApi = new WordListsApi($this->client); - $this->wordsApi = new WordsApi($this->client); - } - - public function tearDown() { - unset($this->client); - } - -} - - -?> diff --git a/samples/client/wordnik-api/php/tests/WordApiTest.php b/samples/client/wordnik-api/php/tests/WordApiTest.php deleted file mode 100644 index e8738093d8ab..000000000000 --- a/samples/client/wordnik-api/php/tests/WordApiTest.php +++ /dev/null @@ -1,95 +0,0 @@ -assertEquals(12, count($doc->apis)); - } - - public function testGetWord() { - $res = $this->wordApi->getWord('cat'); - $this->assertEquals('cat', $res->word); - } - - public function testGetWordWithSuggestions() { - $res = $this->wordApi->getWord('cAt', $includeSuggestions=true); - $this->assertEquals('cAt', $res->word); - } - - public function testGetWordWithCanonicalForm() { - $res = $this->wordApi->getWord('cAt', $useCanonical='true'); - $this->assertEquals('cat', $res->word); - } - - public function testGetDefinitions() { - $res = $this->wordApi->getDefinitions('cat'); - $this->assertEquals(15, count($res)); - } - - public function testGetDefinitionsWithSpacesInWord() { - $res = $this->wordApi->getDefinitions('bon vivant'); - $this->assertEquals(1, count($res)); - } - - public function testGetExamples() { - $res = $this->wordApi->getExamples('cat', $limit=5); - $this->assertEquals(5, count($res->examples)); - } - - public function testGetTopExample() { - $res = $this->wordApi->getTopExample('cat', $limit=5); - $this->assertEquals('cat', $res->word); - } - - public function testGetHyphenation() { - $res = $this->wordApi->getHyphenation('catalog', $useCanonical=null, $sourceDictionary=null, $limit=1); - $this->assertEquals(1, count($res)); - } - - public function testGetWordFrequency() { - $res = $this->wordApi->getWordFrequency('catalog'); - $this->assertFalse($res->totalCount == 0); - } - - public function testGetPhrases() { - $res = $this->wordApi->getPhrases('money'); - $this->assertFalse(count($res) == 0); - } - - public function testGetRelatedWords() { - $res = $this->wordApi->getRelatedWords('cat'); - foreach ($res as $related) { - $this->assertLessThan(11, count($related->words)); - } - } - - public function testGetAudio() { - $res = $this->wordApi->getAudio('cat', $useCanonical=True, $limit=2); - $this->assertEquals(2, count($res)); - } - - public function testGetScrabbleScore() { - $res = $this->wordApi->getScrabbleScore('quixotry'); - $this->assertEquals(27, $res->value); - } - - public function testGetEtymologies() { - $res = $this->wordApi->getEtymologies('butter'); - $this->assertFalse(strpos($res[0], 'of Scythian origin') === false); - } - -} -?> diff --git a/samples/client/wordnik-api/php/tests/WordListApiTest.php b/samples/client/wordnik-api/php/tests/WordListApiTest.php deleted file mode 100644 index 126368f16c0e..000000000000 --- a/samples/client/wordnik-api/php/tests/WordListApiTest.php +++ /dev/null @@ -1,115 +0,0 @@ -authToken = $this->accountApi->authenticate($this->username, - $this->password)->token; - $lists = $this->accountApi->getWordListsForLoggedInUser($this->authToken, $skip=null, $limit=1); - $this->existingList = $lists[0]; - - $this->wordList = new WordList(); - $this->wordList->name = "my test list"; - $this->wordList->type = "PUBLIC"; - $this->wordList->description = "some words I want to play with"; - } - - - public function testGetWordListByPermalink() { - $res = $this->wordListApi->getWordListByPermalink($this->existingList->permalink, - $this->authToken); - $this->assertNotEquals(null, $res); - } - - - public function testUpdateWordList() { - $description = 'list updated at ' . time(); - $this->existingList->description = $description; - $this->wordListApi->updateWordList($this->existingList->permalink, - $body=$this->existingList, - $this->authToken); - $res = $this->wordListApi->getWordListByPermalink($this->existingList->permalink, $this->authToken); - $this->assertEquals($description, $res->description); - } - - public function testAddWordsToWordList() { - $wordsToAdd = array(); - $word1 = new StringValue(); - $word1->word = "delicious"; - $wordsToAdd[] = $word1; - $word2 = new StringValue(); - $word2->word = "tasty"; - $wordsToAdd[] = $word2; - $word3 = new StringValue(); - $word3->word = "scrumptious"; - $wordsToAdd[] = $word3; - $word4 = new StringValue(); - $word4->word = "not to be deleted"; - $wordsToAdd[] = $word4; - - $this->wordListApi->addWordsToWordList($this->existingList->permalink, - $body=$wordsToAdd, - $this->authToken); - - $res = $this->wordListApi->getWordListWords($this->existingList->permalink, $this->authToken, $sortBy=null, $sortOrder=null, $skip=null, $limit=null); - - $returnedWords = array(); - - foreach ($res as $wordListWord) { - $returnedWords[] = $wordListWord->word; - } - - $intersection = array(); - foreach ($wordsToAdd as $addedWord) { - if (in_array($addedWord->word, $returnedWords)) { - $intersection[] = $addedWord->word; - } - } - - $this->assertEquals(4, count($intersection)); - } - - - public function testDeleteWordsFromList() { - $wordsToRemove = array(); - $word1 = new StringValue(); - $word1->word = "delicious"; - $wordsToRemove[] = $word1; - $word2 = new StringValue(); - $word2->word = "tasty"; - $wordsToRemove[] = $word2; - $word3 = new StringValue(); - $word3->word = "scrumptious"; - $wordsToRemove[] = $word3; - - $res = $this->wordListApi->getWordListWords($this->existingList->permalink, $this->authToken, $sortBy=null, $sortOrder=null, $skip=null, $limit=null); - - $this->wordListApi->deleteWordsFromWordList($this->existingList->permalink, - $body=$wordsToRemove, - $this->authToken); - - $res = $this->wordListApi->getWordListWords($this->existingList->permalink, $this->authToken, $sortBy=null, $sortOrder=null, $skip=null, $limit=null); - - $returnedWords = array(); - foreach ($res as $wordListWord) { - $returnedWords[] = $wordListWord->word; - } - - $intersection = array(); - foreach ($wordsToRemove as $removedWord) { - if (in_array($removedWord->word, $returnedWords)) { - $intersection[] = $removedWord->word; - } - } - - $this->assertEquals(0, count($intersection)); - } - - -} -?> diff --git a/samples/client/wordnik-api/php/tests/WordListsApiTest.php b/samples/client/wordnik-api/php/tests/WordListsApiTest.php deleted file mode 100644 index 5692402993ef..000000000000 --- a/samples/client/wordnik-api/php/tests/WordListsApiTest.php +++ /dev/null @@ -1,40 +0,0 @@ -authToken = $this->accountApi->authenticate($this->username, - $this->password)->token; - } - - - public function testCreateWordList() { - $wordList = new WordList(); - $wordList->name = "my test list"; - $wordList->type = "PUBLIC"; - $wordList->description = "some words I want to play with"; - - $res = $this->wordListsApi->createWordList($body=$wordList, - $this->authToken); - $this->assertEquals($wordList->description, $res->description); - - $wordsToAdd = array(); - $word1 = new StringValue(); - $word1->word = "foo"; - $wordsToAdd[] = $word1; - - $this->wordListApi->addWordsToWordList($res->permalink, - $body=$wordsToAdd, - $this->authToken); - - - - } - -} -?> diff --git a/samples/client/wordnik-api/php/tests/WordsApiTest.php b/samples/client/wordnik-api/php/tests/WordsApiTest.php deleted file mode 100644 index f5fdcc7d074f..000000000000 --- a/samples/client/wordnik-api/php/tests/WordsApiTest.php +++ /dev/null @@ -1,37 +0,0 @@ -wordsApi->searchWords('tree'); - $this->assertEquals('tree', $res->searchResults[0]->word); - $this->assertNotEquals(0, $res->totalResults); - } - - public function testGetWordOfTheDay() { - $res = $this->wordsApi->getWordOfTheDay(); - $this->assertNotEquals(null, $res); - } - - public function testReverseDictionary() { - $res = $this->wordsApi->reverseDictionary('hairy'); - $this->assertNotEquals(0, $res->totalResults); - $this->assertNotEquals(0, count($res->results)); - } - - public function testGetRandomWords() { - $res = $this->wordsApi->getRandomWords(); - $this->assertEquals(10, count($res)); - } - - public function testGetRandomWord() { - $res = $this->wordsApi->getRandomWord(); - $this->assertNotEquals(null, $res); - } - -} -?> diff --git a/samples/client/wordnik-api/php/wordnik/AccountApi.php b/samples/client/wordnik-api/php/wordnik/AccountApi.php deleted file mode 100644 index 77469b43fca4..000000000000 --- a/samples/client/wordnik-api/php/wordnik/AccountApi.php +++ /dev/null @@ -1,250 +0,0 @@ -apiClient = $apiClient; - } - - /** - * authenticate - * Authenticates a User - * username, string: A confirmed Wordnik username (required) - - * password, string: The user's password (required) - - * @return AuthenticationToken - */ - - public function authenticate($username, $password) { - - //parse inputs - $resourcePath = "/account.{format}/authenticate/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($password != null) { - $queryParams['password'] = $this->apiClient->toQueryValue($password); - } - if($username != null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'AuthenticationToken'); - return $responseObject; - - } - /** - * authenticatePost - * Authenticates a user - * username, string: A confirmed Wordnik username (required) - - * body, string: The user's password (required) - - * @return AuthenticationToken - */ - - public function authenticatePost($username, $body) { - - //parse inputs - $resourcePath = "/account.{format}/authenticate/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($username != null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'AuthenticationToken'); - return $responseObject; - - } - /** - * getWordListsForLoggedInUser - * Fetches WordList objects for the logged-in user. - * auth_token, string: auth_token of logged-in user (required) - - * skip, int: Results to skip (optional) - - * limit, int: Maximum number of results to return (optional) - - * @return array[WordList] - */ - - public function getWordListsForLoggedInUser($auth_token, $skip=null, $limit=null) { - - //parse inputs - $resourcePath = "/account.{format}/wordLists"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($skip != null) { - $queryParams['skip'] = $this->apiClient->toQueryValue($skip); - } - if($limit != null) { - $queryParams['limit'] = $this->apiClient->toQueryValue($limit); - } - if($auth_token != null) { - $headerParams['auth_token'] = $this->apiClient->toHeaderValue($auth_token); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'array[WordList]'); - return $responseObject; - - } - /** - * getApiTokenStatus - * Returns usage statistics for the API account. - * api_key, string: Wordnik authentication token (optional) - - * @return ApiTokenStatus - */ - - public function getApiTokenStatus($api_key=null) { - - //parse inputs - $resourcePath = "/account.{format}/apiTokenStatus"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($api_key != null) { - $headerParams['api_key'] = $this->apiClient->toHeaderValue($api_key); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'ApiTokenStatus'); - return $responseObject; - - } - /** - * getLoggedInUser - * Returns the logged-in User - * auth_token, string: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - * @return User - */ - - public function getLoggedInUser($auth_token) { - - //parse inputs - $resourcePath = "/account.{format}/user"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($auth_token != null) { - $headerParams['auth_token'] = $this->apiClient->toHeaderValue($auth_token); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'User'); - return $responseObject; - - } - - -} - diff --git a/samples/client/wordnik-api/php/wordnik/Swagger.php b/samples/client/wordnik-api/php/wordnik/Swagger.php deleted file mode 100644 index 088f601489c7..000000000000 --- a/samples/client/wordnik-api/php/wordnik/Swagger.php +++ /dev/null @@ -1,225 +0,0 @@ -apiKey = $apiKey; - $this->apiServer = $apiServer; - } - - - /** - * @param string $resourcePath path to method endpoint - * @param string $method method to call - * @param array $queryParams parameters to be place in query URL - * @param array $postData parameters to be placed in POST body - * @param array $headerParams parameters to be place in request header - * @return mixed - */ - public function callAPI($resourcePath, $method, $queryParams, $postData, - $headerParams) { - - $headers = array(); - - # Allow API key from $headerParams to override default - $added_api_key = False; - if ($headerParams != null) { - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - if ($key == 'api_key') { - $added_api_key = True; - } - } - } - if (! $added_api_key) { - $headers[] = "api_key: " . $this->apiKey; - } - - if (is_object($postData) or is_array($postData)) { - $postData = json_encode($this->sanitizeForSerialization($postData)); - } - - $url = $this->apiServer . $resourcePath; - - $curl = curl_init(); - curl_setopt($curl, CURLOPT_TIMEOUT, 5); - // return the result on success, rather than just TRUE - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - - if (! empty($queryParams)) { - $url = ($url . '?' . http_build_query($queryParams)); - } - - if ($method == self::$POST) { - curl_setopt($curl, CURLOPT_POST, true); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PUT) { - $json_data = json_encode($postData); - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method != self::$GET) { - throw new Exception('Method ' . $method . ' is not recognized.'); - } - curl_setopt($curl, CURLOPT_URL, $url); - - // Make the request - $response = curl_exec($curl); - $response_info = curl_getinfo($curl); - - // Handle the response - if ($response_info['http_code'] == 0) { - throw new Exception("TIMEOUT: api call to " . $url . - " took more than 5s to return" ); - } else if ($response_info['http_code'] == 200) { - $data = json_decode($response); - } else if ($response_info['http_code'] == 401) { - throw new Exception("Unauthorized API request to " . $url . - ": ".json_decode($response)->message ); - } else if ($response_info['http_code'] == 404) { - $data = null; - } else { - throw new Exception("Can't connect to the api: " . $url . - " response code: " . - $response_info['http_code']); - } - - return $data; - } - - /** - * Build a JSON POST object - */ - protected function sanitizeForSerialization($data) - { - if (is_scalar($data) || null === $data) { - $sanitized = $data; - } else if ($data instanceof \DateTime) { - $sanitized = $data->format(\DateTime::ISO8601); - } else if (is_array($data)) { - foreach ($data as $property => $value) { - $data[$property] = $this->sanitizeForSerialization($value); - } - $sanitized = $data; - } else if (is_object($data)) { - $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - $values[$property] = $this->sanitizeForSerialization($data->$property); - } - $sanitized = $values; - } else { - $sanitized = (string)$data; - } - - return $sanitized; - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the path, by url-encoding. - * @param string $value a string which will be part of the path - * @return string the serialized object - */ - public static function toPathValue($value) { - return rawurlencode($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the query, by imploding comma-separated if it's an object. - * If it's a string, pass through unchanged. It will be url-encoded - * later. - * @param object $object an object to be serialized to a string - * @return string the serialized object - */ - public static function toQueryValue($object) { - if (is_array($object)) { - return implode(',', $object); - } else { - return $object; - } - } - - /** - * Just pass through the header value for now. Placeholder in case we - * find out we need to do something with header values. - * @param string $value a string which will be part of the header - * @return string the header string - */ - public static function toHeaderValue($value) { - return $value; - } - - /** - * Deserialize a JSON string into an object - * - * @param object $object object or primitive to be deserialized - * @param string $class class name is passed as a string - * @return object an instance of $class - */ - - public static function deserialize($data, $class) - { - if (null === $data) { - $deserialized = null; - } else if (substr($class, 0, 6) == 'array[') { - $subClass = substr($class, 6, -1); - $values = array(); - foreach ($data as $value) { - $values[] = self::deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { - settype($data, $class); - $deserialized = $data; - } else { - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - if (isset($data->$property)) { - $instance->$property = self::deserialize($data->$property, $type); - } - } - $deserialized = $instance; - } - - return $deserialized; - } - -} - - diff --git a/samples/client/wordnik-api/php/wordnik/WordApi.php b/samples/client/wordnik-api/php/wordnik/WordApi.php deleted file mode 100644 index 8cedbcec1be3..000000000000 --- a/samples/client/wordnik-api/php/wordnik/WordApi.php +++ /dev/null @@ -1,683 +0,0 @@ -apiClient = $apiClient; - } - - /** - * getExamples - * Returns examples for a word - * word, string: Word to return examples for (required) - - * includeDuplicates, string: Show duplicate examples from different sources (optional) - - * useCanonical, string: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - * skip, int: Results to skip (optional) - - * limit, int: Maximum number of results to return (optional) - - * @return ExampleSearchResults - */ - - public function getExamples($word, $includeDuplicates=null, $useCanonical=null, $skip=null, $limit=null) { - - //parse inputs - $resourcePath = "/word.{format}/{word}/examples"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($includeDuplicates != null) { - $queryParams['includeDuplicates'] = $this->apiClient->toQueryValue($includeDuplicates); - } - if($useCanonical != null) { - $queryParams['useCanonical'] = $this->apiClient->toQueryValue($useCanonical); - } - if($skip != null) { - $queryParams['skip'] = $this->apiClient->toQueryValue($skip); - } - if($limit != null) { - $queryParams['limit'] = $this->apiClient->toQueryValue($limit); - } - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'ExampleSearchResults'); - return $responseObject; - - } - /** - * getWord - * Given a word as a string, returns the WordObject that represents it - * word, string: String value of WordObject to return (required) - - * useCanonical, string: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - * includeSuggestions, string: Return suggestions (for correct spelling, case variants, etc.) (optional) - - * @return WordObject - */ - - public function getWord($word, $useCanonical=null, $includeSuggestions=null) { - - //parse inputs - $resourcePath = "/word.{format}/{word}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($useCanonical != null) { - $queryParams['useCanonical'] = $this->apiClient->toQueryValue($useCanonical); - } - if($includeSuggestions != null) { - $queryParams['includeSuggestions'] = $this->apiClient->toQueryValue($includeSuggestions); - } - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'WordObject'); - return $responseObject; - - } - /** - * getDefinitions - * Return definitions for a word - * word, string: Word to return definitions for (required) - - * partOfSpeech, string: CSV list of part-of-speech types (optional) - - * sourceDictionaries, string: Source dictionary to return definitions from. If 'all' is received, results are returned from all sources. If multiple values are received (e.g. 'century,wiktionary'), results are returned from the first specified dictionary that has definitions. If left blank, results are returned from the first dictionary that has definitions. By default, dictionaries are searched in this order: ahd, wiktionary, webster, century, wordnet (optional) - - * limit, int: Maximum number of results to return (optional) - - * includeRelated, string: Return related words with definitions (optional) - - * useCanonical, string: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - * includeTags, string: Return a closed set of XML tags in response (optional) - - * @return array[Definition] - */ - - public function getDefinitions($word, $partOfSpeech=null, $sourceDictionaries=null, $limit=null, $includeRelated=null, $useCanonical=null, $includeTags=null) { - - //parse inputs - $resourcePath = "/word.{format}/{word}/definitions"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($limit != null) { - $queryParams['limit'] = $this->apiClient->toQueryValue($limit); - } - if($partOfSpeech != null) { - $queryParams['partOfSpeech'] = $this->apiClient->toQueryValue($partOfSpeech); - } - if($includeRelated != null) { - $queryParams['includeRelated'] = $this->apiClient->toQueryValue($includeRelated); - } - if($sourceDictionaries != null) { - $queryParams['sourceDictionaries'] = $this->apiClient->toQueryValue($sourceDictionaries); - } - if($useCanonical != null) { - $queryParams['useCanonical'] = $this->apiClient->toQueryValue($useCanonical); - } - if($includeTags != null) { - $queryParams['includeTags'] = $this->apiClient->toQueryValue($includeTags); - } - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'array[Definition]'); - return $responseObject; - - } - /** - * getTopExample - * Returns a top example for a word - * word, string: Word to fetch examples for (required) - - * useCanonical, string: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - * @return Example - */ - - public function getTopExample($word, $useCanonical=null) { - - //parse inputs - $resourcePath = "/word.{format}/{word}/topExample"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($useCanonical != null) { - $queryParams['useCanonical'] = $this->apiClient->toQueryValue($useCanonical); - } - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'Example'); - return $responseObject; - - } - /** - * getRelatedWords - * Given a word as a string, returns relationships from the Word Graph - * word, string: Word to fetch relationships for (required) - - * relationshipTypes, string: Limits the total results per type of relationship type (optional) - - * useCanonical, string: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - * limitPerRelationshipType, int: Restrict to the supplied relatinship types (optional) - - * @return array[Related] - */ - - public function getRelatedWords($word, $relationshipTypes=null, $useCanonical=null, $limitPerRelationshipType=null) { - - //parse inputs - $resourcePath = "/word.{format}/{word}/relatedWords"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($useCanonical != null) { - $queryParams['useCanonical'] = $this->apiClient->toQueryValue($useCanonical); - } - if($relationshipTypes != null) { - $queryParams['relationshipTypes'] = $this->apiClient->toQueryValue($relationshipTypes); - } - if($limitPerRelationshipType != null) { - $queryParams['limitPerRelationshipType'] = $this->apiClient->toQueryValue($limitPerRelationshipType); - } - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'array[Related]'); - return $responseObject; - - } - /** - * getTextPronunciations - * Returns text pronunciations for a given word - * word, string: Word to get pronunciations for (required) - - * sourceDictionary, string: Get from a single dictionary (optional) - - * typeFormat, string: Text pronunciation type (optional) - - * useCanonical, string: If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - * limit, int: Maximum number of results to return (optional) - - * @return array[TextPron] - */ - - public function getTextPronunciations($word, $sourceDictionary=null, $typeFormat=null, $useCanonical=null, $limit=null) { - - //parse inputs - $resourcePath = "/word.{format}/{word}/pronunciations"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($useCanonical != null) { - $queryParams['useCanonical'] = $this->apiClient->toQueryValue($useCanonical); - } - if($sourceDictionary != null) { - $queryParams['sourceDictionary'] = $this->apiClient->toQueryValue($sourceDictionary); - } - if($typeFormat != null) { - $queryParams['typeFormat'] = $this->apiClient->toQueryValue($typeFormat); - } - if($limit != null) { - $queryParams['limit'] = $this->apiClient->toQueryValue($limit); - } - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'array[TextPron]'); - return $responseObject; - - } - /** - * getHyphenation - * Returns syllable information for a word - * word, string: Word to get syllables for (required) - - * sourceDictionary, string: Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet. (optional) - - * useCanonical, string: If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - * limit, int: Maximum number of results to return (optional) - - * @return array[Syllable] - */ - - public function getHyphenation($word, $sourceDictionary=null, $useCanonical=null, $limit=null) { - - //parse inputs - $resourcePath = "/word.{format}/{word}/hyphenation"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($useCanonical != null) { - $queryParams['useCanonical'] = $this->apiClient->toQueryValue($useCanonical); - } - if($sourceDictionary != null) { - $queryParams['sourceDictionary'] = $this->apiClient->toQueryValue($sourceDictionary); - } - if($limit != null) { - $queryParams['limit'] = $this->apiClient->toQueryValue($limit); - } - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'array[Syllable]'); - return $responseObject; - - } - /** - * getWordFrequency - * Returns word usage over time - * word, string: Word to return (required) - - * useCanonical, string: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - * startYear, int: Starting Year (optional) - - * endYear, int: Ending Year (optional) - - * @return FrequencySummary - */ - - public function getWordFrequency($word, $useCanonical=null, $startYear=null, $endYear=null) { - - //parse inputs - $resourcePath = "/word.{format}/{word}/frequency"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($useCanonical != null) { - $queryParams['useCanonical'] = $this->apiClient->toQueryValue($useCanonical); - } - if($startYear != null) { - $queryParams['startYear'] = $this->apiClient->toQueryValue($startYear); - } - if($endYear != null) { - $queryParams['endYear'] = $this->apiClient->toQueryValue($endYear); - } - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'FrequencySummary'); - return $responseObject; - - } - /** - * getPhrases - * Fetches bi-gram phrases for a word - * word, string: Word to fetch phrases for (required) - - * limit, int: Maximum number of results to return (optional) - - * wlmi, int: Minimum WLMI for the phrase (optional) - - * useCanonical, string: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - * @return array[Bigram] - */ - - public function getPhrases($word, $limit=null, $wlmi=null, $useCanonical=null) { - - //parse inputs - $resourcePath = "/word.{format}/{word}/phrases"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($limit != null) { - $queryParams['limit'] = $this->apiClient->toQueryValue($limit); - } - if($wlmi != null) { - $queryParams['wlmi'] = $this->apiClient->toQueryValue($wlmi); - } - if($useCanonical != null) { - $queryParams['useCanonical'] = $this->apiClient->toQueryValue($useCanonical); - } - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'array[Bigram]'); - return $responseObject; - - } - /** - * getEtymologies - * Fetches etymology data - * word, string: Word to return (required) - - * useCanonical, string: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - * @return array[string] - */ - - public function getEtymologies($word, $useCanonical=null) { - - //parse inputs - $resourcePath = "/word.{format}/{word}/etymologies"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($useCanonical != null) { - $queryParams['useCanonical'] = $this->apiClient->toQueryValue($useCanonical); - } - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'array[string]'); - return $responseObject; - - } - /** - * getAudio - * Fetches audio metadata for a word. - * word, string: Word to get audio for. (required) - - * useCanonical, string: Use the canonical form of the word (optional) - - * limit, int: Maximum number of results to return (optional) - - * @return array[AudioFile] - */ - - public function getAudio($word, $useCanonical=null, $limit=null) { - - //parse inputs - $resourcePath = "/word.{format}/{word}/audio"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($useCanonical != null) { - $queryParams['useCanonical'] = $this->apiClient->toQueryValue($useCanonical); - } - if($limit != null) { - $queryParams['limit'] = $this->apiClient->toQueryValue($limit); - } - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'array[AudioFile]'); - return $responseObject; - - } - /** - * getScrabbleScore - * Returns the Scrabble score for a word - * word, string: Word to get scrabble score for. (required) - - * @return ScrabbleScoreResult - */ - - public function getScrabbleScore($word) { - - //parse inputs - $resourcePath = "/word.{format}/{word}/scrabbleScore"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($word != null) { - $resourcePath = str_replace("{" . "word" . "}", - $this->apiClient->toPathValue($word), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'ScrabbleScoreResult'); - return $responseObject; - - } - - -} - diff --git a/samples/client/wordnik-api/php/wordnik/WordListApi.php b/samples/client/wordnik-api/php/wordnik/WordListApi.php deleted file mode 100644 index 65e5ee3e5ceb..000000000000 --- a/samples/client/wordnik-api/php/wordnik/WordListApi.php +++ /dev/null @@ -1,301 +0,0 @@ -apiClient = $apiClient; - } - - /** - * updateWordList - * Updates an existing WordList - * permalink, string: permalink of WordList to update (required) - - * body, WordList: Updated WordList (optional) - - * auth_token, string: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - * @return - */ - - public function updateWordList($permalink, $body=null, $auth_token) { - - //parse inputs - $resourcePath = "/wordList.{format}/{permalink}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "PUT"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($auth_token != null) { - $headerParams['auth_token'] = $this->apiClient->toHeaderValue($auth_token); - } - if($permalink != null) { - $resourcePath = str_replace("{" . "permalink" . "}", - $this->apiClient->toPathValue($permalink), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - /** - * deleteWordList - * Deletes an existing WordList - * permalink, string: ID of WordList to delete (required) - - * auth_token, string: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - * @return - */ - - public function deleteWordList($permalink, $auth_token) { - - //parse inputs - $resourcePath = "/wordList.{format}/{permalink}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($auth_token != null) { - $headerParams['auth_token'] = $this->apiClient->toHeaderValue($auth_token); - } - if($permalink != null) { - $resourcePath = str_replace("{" . "permalink" . "}", - $this->apiClient->toPathValue($permalink), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - /** - * getWordListByPermalink - * Fetches a WordList by ID - * permalink, string: permalink of WordList to fetch (required) - - * auth_token, string: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - * @return WordList - */ - - public function getWordListByPermalink($permalink, $auth_token) { - - //parse inputs - $resourcePath = "/wordList.{format}/{permalink}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($auth_token != null) { - $headerParams['auth_token'] = $this->apiClient->toHeaderValue($auth_token); - } - if($permalink != null) { - $resourcePath = str_replace("{" . "permalink" . "}", - $this->apiClient->toPathValue($permalink), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'WordList'); - return $responseObject; - - } - /** - * addWordsToWordList - * Adds words to a WordList - * permalink, string: permalink of WordList to user (required) - - * body, array[StringValue]: Array of words to add to WordList (optional) - - * auth_token, string: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - * @return - */ - - public function addWordsToWordList($permalink, $body=null, $auth_token) { - - //parse inputs - $resourcePath = "/wordList.{format}/{permalink}/words"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($auth_token != null) { - $headerParams['auth_token'] = $this->apiClient->toHeaderValue($auth_token); - } - if($permalink != null) { - $resourcePath = str_replace("{" . "permalink" . "}", - $this->apiClient->toPathValue($permalink), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - /** - * getWordListWords - * Fetches words in a WordList - * permalink, string: ID of WordList to use (required) - - * auth_token, string: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - * sortBy, string: Field to sort by (optional) - - * sortOrder, string: Direction to sort (optional) - - * skip, int: Results to skip (optional) - - * limit, int: Maximum number of results to return (optional) - - * @return array[WordListWord] - */ - - public function getWordListWords($permalink, $auth_token, $sortBy=null, $sortOrder=null, $skip=null, $limit=null) { - - //parse inputs - $resourcePath = "/wordList.{format}/{permalink}/words"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($sortBy != null) { - $queryParams['sortBy'] = $this->apiClient->toQueryValue($sortBy); - } - if($sortOrder != null) { - $queryParams['sortOrder'] = $this->apiClient->toQueryValue($sortOrder); - } - if($skip != null) { - $queryParams['skip'] = $this->apiClient->toQueryValue($skip); - } - if($limit != null) { - $queryParams['limit'] = $this->apiClient->toQueryValue($limit); - } - if($auth_token != null) { - $headerParams['auth_token'] = $this->apiClient->toHeaderValue($auth_token); - } - if($permalink != null) { - $resourcePath = str_replace("{" . "permalink" . "}", - $this->apiClient->toPathValue($permalink), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'array[WordListWord]'); - return $responseObject; - - } - /** - * deleteWordsFromWordList - * Removes words from a WordList - * permalink, string: permalink of WordList to use (required) - - * body, array[StringValue]: Words to remove from WordList (optional) - - * auth_token, string: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - * @return - */ - - public function deleteWordsFromWordList($permalink, $body=null, $auth_token) { - - //parse inputs - $resourcePath = "/wordList.{format}/{permalink}/deleteWords"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($auth_token != null) { - $headerParams['auth_token'] = $this->apiClient->toHeaderValue($auth_token); - } - if($permalink != null) { - $resourcePath = str_replace("{" . "permalink" . "}", - $this->apiClient->toPathValue($permalink), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - } - - -} - diff --git a/samples/client/wordnik-api/php/wordnik/WordListsApi.php b/samples/client/wordnik-api/php/wordnik/WordListsApi.php deleted file mode 100644 index a2db4edce7d8..000000000000 --- a/samples/client/wordnik-api/php/wordnik/WordListsApi.php +++ /dev/null @@ -1,73 +0,0 @@ -apiClient = $apiClient; - } - - /** - * createWordList - * Creates a WordList. - * body, WordList: WordList to create (optional) - - * auth_token, string: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - * @return WordList - */ - - public function createWordList($body=null, $auth_token) { - - //parse inputs - $resourcePath = "/wordLists.{format}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($auth_token != null) { - $headerParams['auth_token'] = $this->apiClient->toHeaderValue($auth_token); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'WordList'); - return $responseObject; - - } - - -} - diff --git a/samples/client/wordnik-api/php/wordnik/WordsApi.php b/samples/client/wordnik-api/php/wordnik/WordsApi.php deleted file mode 100644 index 4d776848f2eb..000000000000 --- a/samples/client/wordnik-api/php/wordnik/WordsApi.php +++ /dev/null @@ -1,457 +0,0 @@ -apiClient = $apiClient; - } - - /** - * searchWords - * Searches words - * query, string: Search query (required) - - * includePartOfSpeech, string: Only include these comma-delimited parts of speech (optional) - - * excludePartOfSpeech, string: Exclude these comma-delimited parts of speech (optional) - - * caseSensitive, string: Search case sensitive (optional) - - * minCorpusCount, int: Minimum corpus frequency for terms (optional) - - * maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - * minDictionaryCount, int: Minimum number of dictionary entries for words returned (optional) - - * maxDictionaryCount, int: Maximum dictionary definition count (optional) - - * minLength, int: Minimum word length (optional) - - * maxLength, int: Maximum word length (optional) - - * skip, int: Results to skip (optional) - - * limit, int: Maximum number of results to return (optional) - - * @return WordSearchResults - */ - - public function searchWords($query, $includePartOfSpeech=null, $excludePartOfSpeech=null, $caseSensitive=null, $minCorpusCount=null, $maxCorpusCount=null, $minDictionaryCount=null, $maxDictionaryCount=null, $minLength=null, $maxLength=null, $skip=null, $limit=null) { - - //parse inputs - $resourcePath = "/words.{format}/search/{query}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($caseSensitive != null) { - $queryParams['caseSensitive'] = $this->apiClient->toQueryValue($caseSensitive); - } - if($includePartOfSpeech != null) { - $queryParams['includePartOfSpeech'] = $this->apiClient->toQueryValue($includePartOfSpeech); - } - if($excludePartOfSpeech != null) { - $queryParams['excludePartOfSpeech'] = $this->apiClient->toQueryValue($excludePartOfSpeech); - } - if($minCorpusCount != null) { - $queryParams['minCorpusCount'] = $this->apiClient->toQueryValue($minCorpusCount); - } - if($maxCorpusCount != null) { - $queryParams['maxCorpusCount'] = $this->apiClient->toQueryValue($maxCorpusCount); - } - if($minDictionaryCount != null) { - $queryParams['minDictionaryCount'] = $this->apiClient->toQueryValue($minDictionaryCount); - } - if($maxDictionaryCount != null) { - $queryParams['maxDictionaryCount'] = $this->apiClient->toQueryValue($maxDictionaryCount); - } - if($minLength != null) { - $queryParams['minLength'] = $this->apiClient->toQueryValue($minLength); - } - if($maxLength != null) { - $queryParams['maxLength'] = $this->apiClient->toQueryValue($maxLength); - } - if($skip != null) { - $queryParams['skip'] = $this->apiClient->toQueryValue($skip); - } - if($limit != null) { - $queryParams['limit'] = $this->apiClient->toQueryValue($limit); - } - if($query != null) { - $resourcePath = str_replace("{" . "query" . "}", - $this->apiClient->toPathValue($query), $resourcePath); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'WordSearchResults'); - return $responseObject; - - } - /** - * getWordOfTheDay - * Returns a specific WordOfTheDay - * date, string: Fetches by date in yyyy-MM-dd (optional) - - * @return WordOfTheDay - */ - - public function getWordOfTheDay($date=null) { - - //parse inputs - $resourcePath = "/words.{format}/wordOfTheDay"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($date != null) { - $queryParams['date'] = $this->apiClient->toQueryValue($date); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'WordOfTheDay'); - return $responseObject; - - } - /** - * reverseDictionary - * Reverse dictionary search - * query, string: Search term (required) - - * findSenseForWord, string: Restricts words and finds closest sense (optional) - - * includeSourceDictionaries, string: Only include these comma-delimited source dictionaries (optional) - - * excludeSourceDictionaries, string: Exclude these comma-delimited source dictionaries (optional) - - * includePartOfSpeech, string: Only include these comma-delimited parts of speech (optional) - - * excludePartOfSpeech, string: Exclude these comma-delimited parts of speech (optional) - - * expandTerms, string: Expand terms (optional) - - * sortBy, string: Attribute to sort by (optional) - - * sortOrder, string: Sort direction (optional) - - * minCorpusCount, int: Minimum corpus frequency for terms (optional) - - * maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - * minLength, int: Minimum word length (optional) - - * maxLength, int: Maximum word length (optional) - - * includeTags, string: Return a closed set of XML tags in response (optional) - - * skip, string: Results to skip (optional) - - * limit, int: Maximum number of results to return (optional) - - * @return DefinitionSearchResults - */ - - public function reverseDictionary($query, $findSenseForWord=null, $includeSourceDictionaries=null, $excludeSourceDictionaries=null, $includePartOfSpeech=null, $excludePartOfSpeech=null, $expandTerms=null, $sortBy=null, $sortOrder=null, $minCorpusCount=null, $maxCorpusCount=null, $minLength=null, $maxLength=null, $includeTags=null, $skip=null, $limit=null) { - - //parse inputs - $resourcePath = "/words.{format}/reverseDictionary"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($query != null) { - $queryParams['query'] = $this->apiClient->toQueryValue($query); - } - if($findSenseForWord != null) { - $queryParams['findSenseForWord'] = $this->apiClient->toQueryValue($findSenseForWord); - } - if($includeSourceDictionaries != null) { - $queryParams['includeSourceDictionaries'] = $this->apiClient->toQueryValue($includeSourceDictionaries); - } - if($excludeSourceDictionaries != null) { - $queryParams['excludeSourceDictionaries'] = $this->apiClient->toQueryValue($excludeSourceDictionaries); - } - if($includePartOfSpeech != null) { - $queryParams['includePartOfSpeech'] = $this->apiClient->toQueryValue($includePartOfSpeech); - } - if($excludePartOfSpeech != null) { - $queryParams['excludePartOfSpeech'] = $this->apiClient->toQueryValue($excludePartOfSpeech); - } - if($minCorpusCount != null) { - $queryParams['minCorpusCount'] = $this->apiClient->toQueryValue($minCorpusCount); - } - if($maxCorpusCount != null) { - $queryParams['maxCorpusCount'] = $this->apiClient->toQueryValue($maxCorpusCount); - } - if($minLength != null) { - $queryParams['minLength'] = $this->apiClient->toQueryValue($minLength); - } - if($maxLength != null) { - $queryParams['maxLength'] = $this->apiClient->toQueryValue($maxLength); - } - if($expandTerms != null) { - $queryParams['expandTerms'] = $this->apiClient->toQueryValue($expandTerms); - } - if($includeTags != null) { - $queryParams['includeTags'] = $this->apiClient->toQueryValue($includeTags); - } - if($sortBy != null) { - $queryParams['sortBy'] = $this->apiClient->toQueryValue($sortBy); - } - if($sortOrder != null) { - $queryParams['sortOrder'] = $this->apiClient->toQueryValue($sortOrder); - } - if($skip != null) { - $queryParams['skip'] = $this->apiClient->toQueryValue($skip); - } - if($limit != null) { - $queryParams['limit'] = $this->apiClient->toQueryValue($limit); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'DefinitionSearchResults'); - return $responseObject; - - } - /** - * getRandomWords - * Returns an array of random WordObjects - * includePartOfSpeech, string: CSV part-of-speech values to include (optional) - - * excludePartOfSpeech, string: CSV part-of-speech values to exclude (optional) - - * sortBy, string: Attribute to sort by (optional) - - * sortOrder, string: Sort direction (optional) - - * hasDictionaryDef, string: Only return words with dictionary definitions (optional) - - * minCorpusCount, int: Minimum corpus frequency for terms (optional) - - * maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - * minDictionaryCount, int: Minimum dictionary count (optional) - - * maxDictionaryCount, int: Maximum dictionary count (optional) - - * minLength, int: Minimum word length (optional) - - * maxLength, int: Maximum word length (optional) - - * limit, int: Maximum number of results to return (optional) - - * @return array[WordObject] - */ - - public function getRandomWords($includePartOfSpeech=null, $excludePartOfSpeech=null, $sortBy=null, $sortOrder=null, $hasDictionaryDef=null, $minCorpusCount=null, $maxCorpusCount=null, $minDictionaryCount=null, $maxDictionaryCount=null, $minLength=null, $maxLength=null, $limit=null) { - - //parse inputs - $resourcePath = "/words.{format}/randomWords"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($hasDictionaryDef != null) { - $queryParams['hasDictionaryDef'] = $this->apiClient->toQueryValue($hasDictionaryDef); - } - if($includePartOfSpeech != null) { - $queryParams['includePartOfSpeech'] = $this->apiClient->toQueryValue($includePartOfSpeech); - } - if($excludePartOfSpeech != null) { - $queryParams['excludePartOfSpeech'] = $this->apiClient->toQueryValue($excludePartOfSpeech); - } - if($minCorpusCount != null) { - $queryParams['minCorpusCount'] = $this->apiClient->toQueryValue($minCorpusCount); - } - if($maxCorpusCount != null) { - $queryParams['maxCorpusCount'] = $this->apiClient->toQueryValue($maxCorpusCount); - } - if($minDictionaryCount != null) { - $queryParams['minDictionaryCount'] = $this->apiClient->toQueryValue($minDictionaryCount); - } - if($maxDictionaryCount != null) { - $queryParams['maxDictionaryCount'] = $this->apiClient->toQueryValue($maxDictionaryCount); - } - if($minLength != null) { - $queryParams['minLength'] = $this->apiClient->toQueryValue($minLength); - } - if($maxLength != null) { - $queryParams['maxLength'] = $this->apiClient->toQueryValue($maxLength); - } - if($sortBy != null) { - $queryParams['sortBy'] = $this->apiClient->toQueryValue($sortBy); - } - if($sortOrder != null) { - $queryParams['sortOrder'] = $this->apiClient->toQueryValue($sortOrder); - } - if($limit != null) { - $queryParams['limit'] = $this->apiClient->toQueryValue($limit); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'array[WordObject]'); - return $responseObject; - - } - /** - * getRandomWord - * Returns a single random WordObject - * includePartOfSpeech, string: CSV part-of-speech values to include (optional) - - * excludePartOfSpeech, string: CSV part-of-speech values to exclude (optional) - - * hasDictionaryDef, string: Only return words with dictionary definitions (optional) - - * minCorpusCount, int: Minimum corpus frequency for terms (optional) - - * maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - * minDictionaryCount, int: Minimum dictionary count (optional) - - * maxDictionaryCount, int: Maximum dictionary count (optional) - - * minLength, int: Minimum word length (optional) - - * maxLength, int: Maximum word length (optional) - - * @return WordObject - */ - - public function getRandomWord($includePartOfSpeech=null, $excludePartOfSpeech=null, $hasDictionaryDef=null, $minCorpusCount=null, $maxCorpusCount=null, $minDictionaryCount=null, $maxDictionaryCount=null, $minLength=null, $maxLength=null) { - - //parse inputs - $resourcePath = "/words.{format}/randomWord"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $queryParams = array(); - $headerParams = array(); - $headerParams['Accept'] = 'application/json'; - $headerParams['Content-Type'] = 'application/json'; - - if($hasDictionaryDef != null) { - $queryParams['hasDictionaryDef'] = $this->apiClient->toQueryValue($hasDictionaryDef); - } - if($includePartOfSpeech != null) { - $queryParams['includePartOfSpeech'] = $this->apiClient->toQueryValue($includePartOfSpeech); - } - if($excludePartOfSpeech != null) { - $queryParams['excludePartOfSpeech'] = $this->apiClient->toQueryValue($excludePartOfSpeech); - } - if($minCorpusCount != null) { - $queryParams['minCorpusCount'] = $this->apiClient->toQueryValue($minCorpusCount); - } - if($maxCorpusCount != null) { - $queryParams['maxCorpusCount'] = $this->apiClient->toQueryValue($maxCorpusCount); - } - if($minDictionaryCount != null) { - $queryParams['minDictionaryCount'] = $this->apiClient->toQueryValue($minDictionaryCount); - } - if($maxDictionaryCount != null) { - $queryParams['maxDictionaryCount'] = $this->apiClient->toQueryValue($maxDictionaryCount); - } - if($minLength != null) { - $queryParams['minLength'] = $this->apiClient->toQueryValue($minLength); - } - if($maxLength != null) { - $queryParams['maxLength'] = $this->apiClient->toQueryValue($maxLength); - } - //make the API Call - if (! isset($body)) { - $body = null; - } - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $body, - $headerParams); - - - if(! $response){ - return null; - } - - $responseObject = $this->apiClient->deserialize($response, - 'WordObject'); - return $responseObject; - - } - - -} - diff --git a/samples/client/wordnik-api/php/wordnik/models/ApiTokenStatus.php b/samples/client/wordnik-api/php/wordnik/models/ApiTokenStatus.php deleted file mode 100644 index 2d43edc5c092..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/ApiTokenStatus.php +++ /dev/null @@ -1,43 +0,0 @@ - 'bool', - 'token' => 'string', - 'resetsInMillis' => 'int', - 'remainingCalls' => 'int', - 'expiresInMillis' => 'int', - 'totalRequests' => 'int' - - ); - - public $valid; // bool - public $token; // string - public $resetsInMillis; // int - public $remainingCalls; // int - public $expiresInMillis; // int - public $totalRequests; // int - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/AudioFile.php b/samples/client/wordnik-api/php/wordnik/models/AudioFile.php deleted file mode 100644 index 6d9b33ed9691..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/AudioFile.php +++ /dev/null @@ -1,59 +0,0 @@ - 'string', - 'commentCount' => 'int', - 'voteCount' => 'int', - 'fileUrl' => 'string', - 'audioType' => 'string', - 'id' => 'int', - 'duration' => 'float', - 'attributionText' => 'string', - 'createdBy' => 'string', - 'description' => 'string', - 'createdAt' => 'DateTime', - 'voteWeightedAverage' => 'float', - 'voteAverage' => 'float', - 'word' => 'string' - - ); - - public $attributionUrl; // string - public $commentCount; // int - public $voteCount; // int - public $fileUrl; // string - public $audioType; // string - public $id; // int - public $duration; // float - public $attributionText; // string - public $createdBy; // string - public $description; // string - public $createdAt; // DateTime - public $voteWeightedAverage; // float - public $voteAverage; // float - public $word; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/AuthenticationToken.php b/samples/client/wordnik-api/php/wordnik/models/AuthenticationToken.php deleted file mode 100644 index 1c2d61f9d3db..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/AuthenticationToken.php +++ /dev/null @@ -1,37 +0,0 @@ - 'string', - 'userId' => 'int', - 'userSignature' => 'string' - - ); - - public $token; // string - public $userId; // int - public $userSignature; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/Bigram.php b/samples/client/wordnik-api/php/wordnik/models/Bigram.php deleted file mode 100644 index a9d5345a3efe..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/Bigram.php +++ /dev/null @@ -1,41 +0,0 @@ - 'int', - 'gram2' => 'string', - 'gram1' => 'string', - 'wlmi' => 'float', - 'mi' => 'float' - - ); - - public $count; // int - public $gram2; // string - public $gram1; // string - public $wlmi; // float - public $mi; // float - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/Citation.php b/samples/client/wordnik-api/php/wordnik/models/Citation.php deleted file mode 100644 index 2f00512527a1..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/Citation.php +++ /dev/null @@ -1,35 +0,0 @@ - 'string', - 'source' => 'string' - - ); - - public $cite; // string - public $source; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/ContentProvider.php b/samples/client/wordnik-api/php/wordnik/models/ContentProvider.php deleted file mode 100644 index 9717c59599ee..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/ContentProvider.php +++ /dev/null @@ -1,35 +0,0 @@ - 'int', - 'name' => 'string' - - ); - - public $id; // int - public $name; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/Definition.php b/samples/client/wordnik-api/php/wordnik/models/Definition.php deleted file mode 100644 index 642e194637cd..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/Definition.php +++ /dev/null @@ -1,63 +0,0 @@ - 'string', - 'text' => 'string', - 'sourceDictionary' => 'string', - 'citations' => 'array[Citation]', - 'labels' => 'array[Label]', - 'score' => 'float', - 'exampleUses' => 'array[ExampleUsage]', - 'attributionUrl' => 'string', - 'seqString' => 'string', - 'attributionText' => 'string', - 'relatedWords' => 'array[Related]', - 'sequence' => 'string', - 'word' => 'string', - 'notes' => 'array[Note]', - 'textProns' => 'array[TextPron]', - 'partOfSpeech' => 'string' - - ); - - public $extendedText; // string - public $text; // string - public $sourceDictionary; // string - public $citations; // array[Citation] - public $labels; // array[Label] - public $score; // float - public $exampleUses; // array[ExampleUsage] - public $attributionUrl; // string - public $seqString; // string - public $attributionText; // string - public $relatedWords; // array[Related] - public $sequence; // string - public $word; // string - public $notes; // array[Note] - public $textProns; // array[TextPron] - public $partOfSpeech; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/Example.php b/samples/client/wordnik-api/php/wordnik/models/Example.php deleted file mode 100644 index 610d2c748112..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/Example.php +++ /dev/null @@ -1,55 +0,0 @@ - 'int', - 'exampleId' => 'int', - 'title' => 'string', - 'text' => 'string', - 'score' => 'ScoredWord', - 'sentence' => 'Sentence', - 'word' => 'string', - 'provider' => 'ContentProvider', - 'year' => 'int', - 'rating' => 'float', - 'documentId' => 'int', - 'url' => 'string' - - ); - - public $id; // int - public $exampleId; // int - public $title; // string - public $text; // string - public $score; // ScoredWord - public $sentence; // Sentence - public $word; // string - public $provider; // ContentProvider - public $year; // int - public $rating; // float - public $documentId; // int - public $url; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/ExampleSearchResults.php b/samples/client/wordnik-api/php/wordnik/models/ExampleSearchResults.php deleted file mode 100644 index a6d0c9cb4528..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/ExampleSearchResults.php +++ /dev/null @@ -1,35 +0,0 @@ - 'array[Facet]', - 'examples' => 'array[Example]' - - ); - - public $facets; // array[Facet] - public $examples; // array[Example] - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/Facet.php b/samples/client/wordnik-api/php/wordnik/models/Facet.php deleted file mode 100644 index 16d2bcd84cef..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/Facet.php +++ /dev/null @@ -1,35 +0,0 @@ - 'array[FacetValue]', - 'name' => 'string' - - ); - - public $facetValues; // array[FacetValue] - public $name; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/FacetValue.php b/samples/client/wordnik-api/php/wordnik/models/FacetValue.php deleted file mode 100644 index d7e1465b5026..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/FacetValue.php +++ /dev/null @@ -1,35 +0,0 @@ - 'int', - 'value' => 'string' - - ); - - public $count; // int - public $value; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/Frequency.php b/samples/client/wordnik-api/php/wordnik/models/Frequency.php deleted file mode 100644 index 8e78fe0f2f55..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/Frequency.php +++ /dev/null @@ -1,35 +0,0 @@ - 'int', - 'year' => 'int' - - ); - - public $count; // int - public $year; // int - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/FrequencySummary.php b/samples/client/wordnik-api/php/wordnik/models/FrequencySummary.php deleted file mode 100644 index 48936528427d..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/FrequencySummary.php +++ /dev/null @@ -1,41 +0,0 @@ - 'int', - 'totalCount' => 'int', - 'frequencyString' => 'string', - 'word' => 'string', - 'frequency' => 'array[Frequency]' - - ); - - public $unknownYearCount; // int - public $totalCount; // int - public $frequencyString; // string - public $word; // string - public $frequency; // array[Frequency] - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/Label.php b/samples/client/wordnik-api/php/wordnik/models/Label.php deleted file mode 100644 index 235b8f7647af..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/Label.php +++ /dev/null @@ -1,35 +0,0 @@ - 'string', - 'type' => 'string' - - ); - - public $text; // string - public $type; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/Note.php b/samples/client/wordnik-api/php/wordnik/models/Note.php deleted file mode 100644 index 6d7c2b27ddd8..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/Note.php +++ /dev/null @@ -1,39 +0,0 @@ - 'string', - 'appliesTo' => 'array[string]', - 'value' => 'string', - 'pos' => 'int' - - ); - - public $noteType; // string - public $appliesTo; // array[string] - public $value; // string - public $pos; // int - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/Related.php b/samples/client/wordnik-api/php/wordnik/models/Related.php deleted file mode 100644 index 3dc72f5a3bb0..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/Related.php +++ /dev/null @@ -1,45 +0,0 @@ - 'string', - 'relationshipType' => 'string', - 'label2' => 'string', - 'label3' => 'string', - 'words' => 'array[string]', - 'gram' => 'string', - 'label4' => 'string' - - ); - - public $label1; // string - public $relationshipType; // string - public $label2; // string - public $label3; // string - public $words; // array[string] - public $gram; // string - public $label4; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/ScoredWord.php b/samples/client/wordnik-api/php/wordnik/models/ScoredWord.php deleted file mode 100644 index 3a9c7b7c04da..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/ScoredWord.php +++ /dev/null @@ -1,53 +0,0 @@ - 'int', - 'id' => 'int', - 'docTermCount' => 'int', - 'lemma' => 'string', - 'wordType' => 'string', - 'score' => 'float', - 'sentenceId' => 'int', - 'word' => 'string', - 'stopword' => 'bool', - 'baseWordScore' => 'float', - 'partOfSpeech' => 'string' - - ); - - public $position; // int - public $id; // int - public $docTermCount; // int - public $lemma; // string - public $wordType; // string - public $score; // float - public $sentenceId; // int - public $word; // string - public $stopword; // bool - public $baseWordScore; // float - public $partOfSpeech; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/ScrabbleScoreResult.php b/samples/client/wordnik-api/php/wordnik/models/ScrabbleScoreResult.php deleted file mode 100644 index ac1804239203..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/ScrabbleScoreResult.php +++ /dev/null @@ -1,33 +0,0 @@ - 'int' - - ); - - public $value; // int - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/Sentence.php b/samples/client/wordnik-api/php/wordnik/models/Sentence.php deleted file mode 100644 index 72bd5e879c8e..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/Sentence.php +++ /dev/null @@ -1,43 +0,0 @@ - 'bool', - 'id' => 'int', - 'scoredWords' => 'array[ScoredWord]', - 'display' => 'string', - 'rating' => 'int', - 'documentMetadataId' => 'int' - - ); - - public $hasScoredWords; // bool - public $id; // int - public $scoredWords; // array[ScoredWord] - public $display; // string - public $rating; // int - public $documentMetadataId; // int - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/SimpleDefinition.php b/samples/client/wordnik-api/php/wordnik/models/SimpleDefinition.php deleted file mode 100644 index c589b38b14d4..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/SimpleDefinition.php +++ /dev/null @@ -1,39 +0,0 @@ - 'string', - 'source' => 'string', - 'note' => 'string', - 'partOfSpeech' => 'string' - - ); - - public $text; // string - public $source; // string - public $note; // string - public $partOfSpeech; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/SimpleExample.php b/samples/client/wordnik-api/php/wordnik/models/SimpleExample.php deleted file mode 100644 index c287c1bb524e..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/SimpleExample.php +++ /dev/null @@ -1,39 +0,0 @@ - 'int', - 'title' => 'string', - 'text' => 'string', - 'url' => 'string' - - ); - - public $id; // int - public $title; // string - public $text; // string - public $url; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/Syllable.php b/samples/client/wordnik-api/php/wordnik/models/Syllable.php deleted file mode 100644 index 5d1954c5b7ef..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/Syllable.php +++ /dev/null @@ -1,37 +0,0 @@ - 'string', - 'seq' => 'int', - 'type' => 'string' - - ); - - public $text; // string - public $seq; // int - public $type; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/TextPron.php b/samples/client/wordnik-api/php/wordnik/models/TextPron.php deleted file mode 100644 index b841e2b530d1..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/TextPron.php +++ /dev/null @@ -1,37 +0,0 @@ - 'string', - 'seq' => 'int', - 'rawType' => 'string' - - ); - - public $raw; // string - public $seq; // int - public $rawType; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/User.php b/samples/client/wordnik-api/php/wordnik/models/User.php deleted file mode 100644 index 5256c261f122..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/User.php +++ /dev/null @@ -1,47 +0,0 @@ - 'int', - 'username' => 'string', - 'email' => 'string', - 'status' => 'int', - 'faceBookId' => 'string', - 'userName' => 'string', - 'displayName' => 'string', - 'password' => 'string' - - ); - - public $id; // int - public $username; // string - public $email; // string - public $status; // int - public $faceBookId; // string - public $userName; // string - public $displayName; // string - public $password; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/WordList.php b/samples/client/wordnik-api/php/wordnik/models/WordList.php deleted file mode 100644 index c4025dc9755f..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/WordList.php +++ /dev/null @@ -1,53 +0,0 @@ - 'int', - 'permalink' => 'string', - 'name' => 'string', - 'createdAt' => 'DateTime', - 'updatedAt' => 'DateTime', - 'lastActivityAt' => 'DateTime', - 'username' => 'string', - 'userId' => 'int', - 'description' => 'string', - 'numberWordsInList' => 'int', - 'type' => 'string' - - ); - - public $id; // int - public $permalink; // string - public $name; // string - public $createdAt; // DateTime - public $updatedAt; // DateTime - public $lastActivityAt; // DateTime - public $username; // string - public $userId; // int - public $description; // string - public $numberWordsInList; // int - public $type; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/WordListWord.php b/samples/client/wordnik-api/php/wordnik/models/WordListWord.php deleted file mode 100644 index 455444387d2e..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/WordListWord.php +++ /dev/null @@ -1,45 +0,0 @@ - 'int', - 'word' => 'string', - 'username' => 'string', - 'userId' => 'int', - 'createdAt' => 'DateTime', - 'numberCommentsOnWord' => 'int', - 'numberLists' => 'int' - - ); - - public $id; // int - public $word; // string - public $username; // string - public $userId; // int - public $createdAt; // DateTime - public $numberCommentsOnWord; // int - public $numberLists; // int - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/WordObject.php b/samples/client/wordnik-api/php/wordnik/models/WordObject.php deleted file mode 100644 index 645bf1cc2493..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/WordObject.php +++ /dev/null @@ -1,43 +0,0 @@ - 'int', - 'word' => 'string', - 'originalWord' => 'string', - 'suggestions' => 'array[string]', - 'canonicalForm' => 'string', - 'vulgar' => 'string' - - ); - - public $id; // int - public $word; // string - public $originalWord; // string - public $suggestions; // array[string] - public $canonicalForm; // string - public $vulgar; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/WordOfTheDay.php b/samples/client/wordnik-api/php/wordnik/models/WordOfTheDay.php deleted file mode 100644 index e82dc62385c9..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/WordOfTheDay.php +++ /dev/null @@ -1,55 +0,0 @@ - 'int', - 'parentId' => 'string', - 'category' => 'string', - 'createdBy' => 'string', - 'createdAt' => 'DateTime', - 'contentProvider' => 'ContentProvider', - 'htmlExtra' => 'string', - 'word' => 'string', - 'definitions' => 'array[SimpleDefinition]', - 'examples' => 'array[SimpleExample]', - 'note' => 'string', - 'publishDate' => 'DateTime' - - ); - - public $id; // int - public $parentId; // string - public $category; // string - public $createdBy; // string - public $createdAt; // DateTime - public $contentProvider; // ContentProvider - public $htmlExtra; // string - public $word; // string - public $definitions; // array[SimpleDefinition] - public $examples; // array[SimpleExample] - public $note; // string - public $publishDate; // DateTime - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/WordSearchResult.php b/samples/client/wordnik-api/php/wordnik/models/WordSearchResult.php deleted file mode 100644 index 8d68e0cdee68..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/WordSearchResult.php +++ /dev/null @@ -1,37 +0,0 @@ - 'int', - 'lexicality' => 'float', - 'word' => 'string' - - ); - - public $count; // int - public $lexicality; // float - public $word; // string - } - diff --git a/samples/client/wordnik-api/php/wordnik/models/WordSearchResults.php b/samples/client/wordnik-api/php/wordnik/models/WordSearchResults.php deleted file mode 100644 index ed1349948734..000000000000 --- a/samples/client/wordnik-api/php/wordnik/models/WordSearchResults.php +++ /dev/null @@ -1,35 +0,0 @@ - 'array[WordSearchResult]', - 'totalResults' => 'int' - - ); - - public $searchResults; // array[WordSearchResult] - public $totalResults; // int - } - diff --git a/samples/client/wordnik-api/python/PythonWordnikApiCodegen.scala b/samples/client/wordnik-api/python/PythonWordnikApiCodegen.scala deleted file mode 100644 index 6b2880346e92..000000000000 --- a/samples/client/wordnik-api/python/PythonWordnikApiCodegen.scala +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicPythonGenerator - -import java.io.File - -object PythonWordnikApiCodegen extends BasicPythonGenerator { - def main(args: Array[String]) = generateClient(args) - - def destinationRoot = "samples/client/wordnik-api/python/wordnik" - - // where to write generated code - override def destinationDir = destinationRoot - - // supporting classes - override def supportingFiles = List( - ("__init__.mustache", destinationDir, "__init__.py"), - ("swagger.mustache", destinationDir + File.separator + apiPackage.getOrElse(""), "swagger.py"), - ("__init__.mustache", destinationDir + File.separator + modelPackage.getOrElse(""), "__init__.py")) -} diff --git a/samples/client/wordnik-api/python/README.md b/samples/client/wordnik-api/python/README.md deleted file mode 100644 index 037bfb8dd216..000000000000 --- a/samples/client/wordnik-api/python/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Python client for Wordnik.com API - -## Overview - -This is a Python 2 client for the Wordnik.com v4 API. For more information, see http://developer.wordnik.com/ . - -## Generation - -This client was generated using the provided script: - -``` -/bin/python-wordnik-api.sh -``` - -## Testing - -The tests require you to set three environment varibales: - -```sh -export API_KEY=your api key -export USER_NAME=some wordnik.com username -export PASSWORD=the user's password -``` - -The tests can be run as follows: - -``` -python tests/BaseApiTest.py -``` diff --git a/samples/client/wordnik-api/python/tests/AccountApiTest.py b/samples/client/wordnik-api/python/tests/AccountApiTest.py deleted file mode 100644 index 697cc43771b8..000000000000 --- a/samples/client/wordnik-api/python/tests/AccountApiTest.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python - -import sys -import unittest -import urllib2 -import json - -from BaseApiTest import BaseApiTest - -sys.path = ['./'] + sys.path -from wordnik import * - - -class AccountApiTest(BaseApiTest): - - def setUp(self): - super(AccountApiTest, self).setUp() - self.authToken = self.accountApi.authenticate(self.username, - self.password).token - - def testAuthenticate(self): - res = self.accountApi.authenticate(self.username, self.password) - assert res, 'null authenticate result' - assert res.token, 'invalid authentication token' - assert res.userId != 0, 'userId was 0' - assert res.userSignature, 'invalid userSignature' - - def testAuthenticatePost(self): - res = self.accountApi.authenticatePost(self.username, self.password) - assert res, 'null authenticate result' - assert res.token, 'invalid authentication token' - assert res.userId != 0, 'userId was 0' - assert res.userSignature, 'invalid userSignature' - - def testGetWordListsForLoggedInUser(self): - res = self.accountApi.getWordListsForLoggedInUser(self.authToken) - assert res, 'null getWordListsForLoggedInUser result' - assert len(res) != 0, 'number of lists shouldn\'t be 0' - - def testGetApiTokenStatus(self): - res = self.accountApi.getApiTokenStatus() - assert res, 'null getApiTokenStatus result' - assert res.valid, 'token status not valid' - assert res.remainingCalls != 0, 'remainingCalls shouldn\'t be 0' - - def testGetLoggedInUser(self): - res = self.accountApi.getLoggedInUser(self.authToken) - assert res, 'null getLoggedInUser result' - assert res.id != 0, 'if shouldn\'t be 0' - assert res.username == self.username, 'username was incorrect' - assert res.status == 0, 'user status should be 0' - assert res.email, 'email shouldn\'t be null' - - -if __name__ == "__main__": - unittest.main() diff --git a/samples/client/wordnik-api/python/tests/BaseApiTest.py b/samples/client/wordnik-api/python/tests/BaseApiTest.py deleted file mode 100644 index b257152419ca..000000000000 --- a/samples/client/wordnik-api/python/tests/BaseApiTest.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python -"""Unit tests for Python Wordnik API client. - -Requires you to set three environment varibales: - API_KEY your API key - USER_NAME the username of a user - PASSWORD the user's password - -Run all tests: - - python BaseApiTest.py - -""" - -import sys -import os -import unittest - -sys.path = ['./'] + sys.path -from wordnik import * - - -class BaseApiTest(unittest.TestCase): - - def setUp(self): - self.apiUrl = 'http://api.wordnik.com/v4' - self.apiKey = os.environ.get('API_KEY') - self.username = os.environ.get('USER_NAME') - self.password = os.environ.get('PASSWORD') - - client = swagger.ApiClient(self.apiKey, self.apiUrl) - self.accountApi = AccountApi.AccountApi(client) - self.wordApi = WordApi.WordApi(client) - self.wordListApi = WordListApi.WordListApi(client) - self.wordsApi = WordsApi.WordsApi(client) - -if __name__ == "__main__": - - from AccountApiTest import AccountApiTest - from WordApiTest import WordApiTest - from WordListApiTest import WordListApiTest - from WordsApiTest import WordsApiTest - - unittest.main() diff --git a/samples/client/wordnik-api/python/tests/WordApiTest.py b/samples/client/wordnik-api/python/tests/WordApiTest.py deleted file mode 100644 index cb15c4213d17..000000000000 --- a/samples/client/wordnik-api/python/tests/WordApiTest.py +++ /dev/null @@ -1,92 +0,0 @@ -#!/usr/bin/env python - -import sys -import unittest -import urllib2 -import json - -from BaseApiTest import BaseApiTest - -sys.path = ['./'] + sys.path -from wordnik import * - - -class WordApiTest(BaseApiTest): - - def testWordApis(self): - response = urllib2.urlopen('http://api.wordnik.com/v4/word.json') - doc = json.loads(response.read()) - assert len(doc['apis']) == 12, 'there should be 10 word apis' - - def testGetWord(self): - res = self.wordApi.getWord('cat') - assert res, 'null getWord result' - assert res.word == 'cat', 'word should be "cat"' - - def testGetWordWithSuggestions(self): - res = self.wordApi.getWord('cAt', includeSuggestions=True) - assert res, 'null getWord result' - assert res.word == 'cAt', 'word should be "cAt"' - - def testGetWordWithCanonicalForm(self): - res = self.wordApi.getWord('cAt', useCanonical=True) - assert res, 'null getWord result' - assert res.word == 'cat', 'word should be "cAt"' - - def testGetDefinitions(self): - res = self.wordApi.getDefinitions('cat', limit=10) - assert res, 'null getDefinitions result' - assert len(res) == 10, 'should have 10 definitions' - - def testGetDefinitionsWithSpacesInWord(self): - res = self.wordApi.getDefinitions('bon vivant') - assert res, 'null getDefinitions result' - assert len(res) == 1, 'should have 1 definition' - - def testGetExamples(self): - res = self.wordApi.getExamples('cat', limit=5) - assert res, 'null getExamples result' - assert len(res.examples) == 5, 'should have 5 definitions' - - def testGetTopExample(self): - res = self.wordApi.getTopExample('cat') - assert res, 'null getTopExample result' - assert res.word == 'cat', 'word should be "cat"' - - def testGetHyphenation(self): - res = self.wordApi.getHyphenation('catalog', limit=1) - assert res, 'null getHyphenation result' - assert len(res) == 1, 'hypenation length should be 1' - - def testGetWordFrequency(self): - res = self.wordApi.getWordFrequency('cat') - assert res, 'null getWordFrequency result' - assert res.totalCount != 0, 'total count should not be 0' - - def testGetPhrases(self): - res = self.wordApi.getPhrases('money') - assert res, 'null getPhrases result' - assert len(res) != 0, 'getPhrases length should not be 0' - - def testGetRelatedWords(self): - res = self.wordApi.getRelatedWords('cat') - assert res, 'null getRelatedWords result' - for related in res: - assert len(related.words) <= 10, 'should have <= 10 related words' - - def testGetAudio(self): - res = self.wordApi.getAudio('cat', useCanonical=True, limit=2) - assert res, 'null getAudio result' - assert len(res) == 2, 'getAudio size should be 2' - - def testGetScrabbleScore(self): - res = self.wordApi.getScrabbleScore('quixotry') - assert res.value == 27, 'quixotry should have a Scrabble score of 27' - - def testGetEtymologies(self): - res = self.wordApi.getEtymologies('butter') - assert 'of Scythian origin' in res[0], 'etymology of "butter" should contain the phrase "of Scythian origin"' - - -if __name__ == "__main__": - unittest.main() diff --git a/samples/client/wordnik-api/python/tests/WordListApiTest.py b/samples/client/wordnik-api/python/tests/WordListApiTest.py deleted file mode 100644 index 87afd59432b0..000000000000 --- a/samples/client/wordnik-api/python/tests/WordListApiTest.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python - -import sys -import unittest -import urllib2 -import json -from pprint import pprint -from BaseApiTest import BaseApiTest - -sys.path = ['./'] + sys.path -from wordnik import * - - -class WordListApiTest(BaseApiTest): - - def setUp(self): - super(WordListApiTest, self).setUp() - self.authToken = self.accountApi.authenticate(self.username, - self.password).token - self.existingList = self.accountApi.getWordListsForLoggedInUser(self.authToken, - limit=1)[0] - - from wordnik.models import WordList - wordList = WordList.WordList() - wordList.name = "my test list" - wordList.type = "PUBLIC" - wordList.description = "some words I want to play with" - - # sampleList = self.wordListApi.createWordList(wordList, - # self.authToken) - - # if not sampleList: - # raise Exception("can't create test list to run tests with") - - def testGetWordListByPermalink(self): - res = self.wordListApi.getWordListByPermalink(self.existingList.permalink, - self.authToken) - assert res, 'null getWordListByPermalink result' - - def testGetWordListByPermalink(self): - res = self.wordListApi.getWordListByPermalink(self.existingList.permalink, - self.authToken) - assert res, 'null getWordListByPermalink result' - - def testUpdateWordList(self): - import time - description = 'list updated at ' + str(time.time()) - self.existingList.description = description - self.wordListApi.updateWordList(self.existingList.permalink, - self.authToken, body=self.existingList) - - res = self.wordListApi.getWordListByPermalink(self.existingList.permalink, - self.authToken) - - assert res.description == description, 'did not update wordlist' - - def testAddWordsToWordList(self): - - from wordnik.models import StringValue - wordsToAdd = [] - word1 = StringValue.StringValue() - word1.word = "delicious" - wordsToAdd.append(word1) - word2 = StringValue.StringValue() - word2.word = "tasty" - wordsToAdd.append(word2) - word3 = StringValue.StringValue() - word3.word = "scrumptious" - wordsToAdd.append(word3) - self.wordListApi.addWordsToWordList(self.existingList.permalink, - self.authToken, body=wordsToAdd) - - res = self.wordListApi.getWordListWords(self.existingList.permalink, - self.authToken) - listSet = set([word.word for word in res]) - addedSet = set(["delicious", "tasty", "scrumptious"]) - assert len(listSet.intersection(addedSet)) == 3, 'did not get added words' - - def testDeleteWordsFromList(self): - from wordnik.models import StringValue - wordsToRemove = [] - word1 = StringValue.StringValue() - word1.word = "delicious" - wordsToRemove.append(word1) - word2 = StringValue.StringValue() - word2.word = "tasty" - wordsToRemove.append(word2) - word3 = StringValue.StringValue() - word3.word = "scrumptious" - wordsToRemove.append(word3) - self.wordListApi.deleteWordsFromWordList(self.existingList.permalink, - self.authToken, - body=wordsToRemove) - - res = self.wordListApi.getWordListWords(self.existingList.permalink, - self.authToken) - listSet = set([word.word for word in res]) - addedSet = set(["delicious", "tasty", "scrumptious"]) - assert len(listSet.intersection(addedSet)) == 0, 'did not get removed words' - - -if __name__ == "__main__": - unittest.main() diff --git a/samples/client/wordnik-api/python/tests/WordsApiTest.py b/samples/client/wordnik-api/python/tests/WordsApiTest.py deleted file mode 100644 index 9ef397aa4bdf..000000000000 --- a/samples/client/wordnik-api/python/tests/WordsApiTest.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python - -import sys -import unittest -import urllib2 -import json - -from BaseApiTest import BaseApiTest - -sys.path = ['./'] + sys.path -from wordnik import * - - -class WordsApiTest(BaseApiTest): - - def testSearchWords(self): - res = self.wordsApi.searchWords('tree') - assert res, 'null search result' - assert res.searchResults[0].word == 'tree', 'word should be "tree"' - assert res.totalResults != 0, 'should not have 0 results' - - def testGetWordOfTheDay(self): - res = self.wordsApi.getWordOfTheDay() - assert res, 'null wordOfTheDay result' - - def testReverseDictionary(self): - res = self.wordsApi.reverseDictionary("hairy") - assert res, 'null reverseDictionary result' - assert res.totalResults != 0, 'should not have 0 results' - assert len(res.results) != 0, 'should not have 0 results' - - def testGetRandomWords(self): - res = self.wordsApi.getRandomWords() - assert res, 'null getRandomWords result' - assert len(res) == 10, 'should get 10 random words' - - def testGetRandomWords(self): - res = self.wordsApi.getRandomWords() - assert res, 'null getRandomWord result' - - def testGetRandomWord(self): - res = self.wordsApi.getRandomWords() - assert res, 'null getRandomWord result' - - -if __name__ == "__main__": - unittest.main() diff --git a/samples/client/wordnik-api/python/wordnik/AccountApi.py b/samples/client/wordnik-api/python/wordnik/AccountApi.py deleted file mode 100644 index 7f5aac0466c1..000000000000 --- a/samples/client/wordnik-api/python/wordnik/AccountApi.py +++ /dev/null @@ -1,270 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - 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. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from models import * - - -class AccountApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def authenticate(self, username, password, **kwargs): - """Authenticates a User - - Args: - username, str: A confirmed Wordnik username (required) - - password, str: The user's password (required) - - - - Returns: AuthenticationToken - """ - - allParams = ['username', 'password'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method authenticate" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/account.{format}/authenticate/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('password' in params): - queryParams['password'] = self.apiClient.toPathValue(params['password']) - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'AuthenticationToken') - return responseObject - - - - - def authenticatePost(self, username, body, **kwargs): - """Authenticates a user - - Args: - username, str: A confirmed Wordnik username (required) - - body, str: The user's password (required) - - - - Returns: AuthenticationToken - """ - - allParams = ['username', 'body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method authenticatePost" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/account.{format}/authenticate/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'AuthenticationToken') - return responseObject - - - - - def getWordListsForLoggedInUser(self, auth_token, **kwargs): - """Fetches WordList objects for the logged-in user. - - Args: - auth_token, str: auth_token of logged-in user (required) - - skip, int: Results to skip (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[WordList] - """ - - allParams = ['auth_token', 'skip', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWordListsForLoggedInUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/account.{format}/wordLists' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('skip' in params): - queryParams['skip'] = self.apiClient.toPathValue(params['skip']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[WordList]') - return responseObject - - - - - def getApiTokenStatus(self, **kwargs): - """Returns usage statistics for the API account. - - Args: - api_key, str: Wordnik authentication token (optional) - - - - Returns: ApiTokenStatus - """ - - allParams = ['api_key'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getApiTokenStatus" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/account.{format}/apiTokenStatus' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('api_key' in params): - headerParams['api_key'] = params['api_key'] - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'ApiTokenStatus') - return responseObject - - - - - def getLoggedInUser(self, auth_token, **kwargs): - """Returns the logged-in User - - Args: - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: User - """ - - allParams = ['auth_token'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getLoggedInUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/account.{format}/user' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'User') - return responseObject - - - - - - - - - diff --git a/samples/client/wordnik-api/python/wordnik/WordApi.py b/samples/client/wordnik-api/python/wordnik/WordApi.py deleted file mode 100644 index 730b812cbe0a..000000000000 --- a/samples/client/wordnik-api/python/wordnik/WordApi.py +++ /dev/null @@ -1,705 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - 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. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from models import * - - -class WordApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def getExamples(self, word, **kwargs): - """Returns examples for a word - - Args: - word, str: Word to return examples for (required) - - includeDuplicates, str: Show duplicate examples from different sources (optional) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - skip, int: Results to skip (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: ExampleSearchResults - """ - - allParams = ['word', 'includeDuplicates', 'useCanonical', 'skip', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getExamples" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/examples' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('includeDuplicates' in params): - queryParams['includeDuplicates'] = self.apiClient.toPathValue(params['includeDuplicates']) - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('skip' in params): - queryParams['skip'] = self.apiClient.toPathValue(params['skip']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'ExampleSearchResults') - return responseObject - - - - - def getWord(self, word, **kwargs): - """Given a word as a string, returns the WordObject that represents it - - Args: - word, str: String value of WordObject to return (required) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - includeSuggestions, str: Return suggestions (for correct spelling, case variants, etc.) (optional) - - - - Returns: WordObject - """ - - allParams = ['word', 'useCanonical', 'includeSuggestions'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWord" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('includeSuggestions' in params): - queryParams['includeSuggestions'] = self.apiClient.toPathValue(params['includeSuggestions']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordObject') - return responseObject - - - - - def getDefinitions(self, word, **kwargs): - """Return definitions for a word - - Args: - word, str: Word to return definitions for (required) - - partOfSpeech, str: CSV list of part-of-speech types (optional) - - sourceDictionaries, str: Source dictionary to return definitions from. If 'all' is received, results are returned from all sources. If multiple values are received (e.g. 'century,wiktionary'), results are returned from the first specified dictionary that has definitions. If left blank, results are returned from the first dictionary that has definitions. By default, dictionaries are searched in this order: ahd, wiktionary, webster, century, wordnet (optional) - - limit, int: Maximum number of results to return (optional) - - includeRelated, str: Return related words with definitions (optional) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - includeTags, str: Return a closed set of XML tags in response (optional) - - - - Returns: list[Definition] - """ - - allParams = ['word', 'partOfSpeech', 'sourceDictionaries', 'limit', 'includeRelated', 'useCanonical', 'includeTags'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getDefinitions" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/definitions' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('partOfSpeech' in params): - queryParams['partOfSpeech'] = self.apiClient.toPathValue(params['partOfSpeech']) - if ('includeRelated' in params): - queryParams['includeRelated'] = self.apiClient.toPathValue(params['includeRelated']) - if ('sourceDictionaries' in params): - queryParams['sourceDictionaries'] = self.apiClient.toPathValue(params['sourceDictionaries']) - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('includeTags' in params): - queryParams['includeTags'] = self.apiClient.toPathValue(params['includeTags']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Definition]') - return responseObject - - - - - def getTopExample(self, word, **kwargs): - """Returns a top example for a word - - Args: - word, str: Word to fetch examples for (required) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - - - Returns: Example - """ - - allParams = ['word', 'useCanonical'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getTopExample" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/topExample' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Example') - return responseObject - - - - - def getRelatedWords(self, word, **kwargs): - """Given a word as a string, returns relationships from the Word Graph - - Args: - word, str: Word to fetch relationships for (required) - - relationshipTypes, str: Limits the total results per type of relationship type (optional) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - limitPerRelationshipType, int: Restrict to the supplied relatinship types (optional) - - - - Returns: list[Related] - """ - - allParams = ['word', 'relationshipTypes', 'useCanonical', 'limitPerRelationshipType'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getRelatedWords" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/relatedWords' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('relationshipTypes' in params): - queryParams['relationshipTypes'] = self.apiClient.toPathValue(params['relationshipTypes']) - if ('limitPerRelationshipType' in params): - queryParams['limitPerRelationshipType'] = self.apiClient.toPathValue(params['limitPerRelationshipType']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Related]') - return responseObject - - - - - def getTextPronunciations(self, word, **kwargs): - """Returns text pronunciations for a given word - - Args: - word, str: Word to get pronunciations for (required) - - sourceDictionary, str: Get from a single dictionary (optional) - - typeFormat, str: Text pronunciation type (optional) - - useCanonical, str: If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[TextPron] - """ - - allParams = ['word', 'sourceDictionary', 'typeFormat', 'useCanonical', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getTextPronunciations" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/pronunciations' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('sourceDictionary' in params): - queryParams['sourceDictionary'] = self.apiClient.toPathValue(params['sourceDictionary']) - if ('typeFormat' in params): - queryParams['typeFormat'] = self.apiClient.toPathValue(params['typeFormat']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[TextPron]') - return responseObject - - - - - def getHyphenation(self, word, **kwargs): - """Returns syllable information for a word - - Args: - word, str: Word to get syllables for (required) - - sourceDictionary, str: Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet. (optional) - - useCanonical, str: If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[Syllable] - """ - - allParams = ['word', 'sourceDictionary', 'useCanonical', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getHyphenation" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/hyphenation' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('sourceDictionary' in params): - queryParams['sourceDictionary'] = self.apiClient.toPathValue(params['sourceDictionary']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Syllable]') - return responseObject - - - - - def getWordFrequency(self, word, **kwargs): - """Returns word usage over time - - Args: - word, str: Word to return (required) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - startYear, int: Starting Year (optional) - - endYear, int: Ending Year (optional) - - - - Returns: FrequencySummary - """ - - allParams = ['word', 'useCanonical', 'startYear', 'endYear'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWordFrequency" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/frequency' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('startYear' in params): - queryParams['startYear'] = self.apiClient.toPathValue(params['startYear']) - if ('endYear' in params): - queryParams['endYear'] = self.apiClient.toPathValue(params['endYear']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'FrequencySummary') - return responseObject - - - - - def getPhrases(self, word, **kwargs): - """Fetches bi-gram phrases for a word - - Args: - word, str: Word to fetch phrases for (required) - - limit, int: Maximum number of results to return (optional) - - wlmi, int: Minimum WLMI for the phrase (optional) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - - - Returns: list[Bigram] - """ - - allParams = ['word', 'limit', 'wlmi', 'useCanonical'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getPhrases" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/phrases' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('wlmi' in params): - queryParams['wlmi'] = self.apiClient.toPathValue(params['wlmi']) - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Bigram]') - return responseObject - - - - - def getEtymologies(self, word, **kwargs): - """Fetches etymology data - - Args: - word, str: Word to return (required) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - - - Returns: list[str] - """ - - allParams = ['word', 'useCanonical'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getEtymologies" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/etymologies' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[str]') - return responseObject - - - - - def getAudio(self, word, **kwargs): - """Fetches audio metadata for a word. - - Args: - word, str: Word to get audio for. (required) - - useCanonical, str: Use the canonical form of the word (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[AudioFile] - """ - - allParams = ['word', 'useCanonical', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getAudio" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/audio' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[AudioFile]') - return responseObject - - - - - def getScrabbleScore(self, word, **kwargs): - """Returns the Scrabble score for a word - - Args: - word, str: Word to get scrabble score for. (required) - - - - Returns: ScrabbleScoreResult - """ - - allParams = ['word'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getScrabbleScore" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/scrabbleScore' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'ScrabbleScoreResult') - return responseObject - - - - - - - - - diff --git a/samples/client/wordnik-api/python/wordnik/WordListApi.py b/samples/client/wordnik-api/python/wordnik/WordListApi.py deleted file mode 100644 index da1155cd3427..000000000000 --- a/samples/client/wordnik-api/python/wordnik/WordListApi.py +++ /dev/null @@ -1,333 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - 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. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from models import * - - -class WordListApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def updateWordList(self, permalink, auth_token, **kwargs): - """Updates an existing WordList - - Args: - permalink, str: permalink of WordList to update (required) - - body, WordList: Updated WordList (optional) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: - """ - - allParams = ['permalink', 'body', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method updateWordList" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PUT' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def deleteWordList(self, permalink, auth_token, **kwargs): - """Deletes an existing WordList - - Args: - permalink, str: ID of WordList to delete (required) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: - """ - - allParams = ['permalink', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method deleteWordList" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def getWordListByPermalink(self, permalink, auth_token, **kwargs): - """Fetches a WordList by ID - - Args: - permalink, str: permalink of WordList to fetch (required) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: WordList - """ - - allParams = ['permalink', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWordListByPermalink" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordList') - return responseObject - - - - - def addWordsToWordList(self, permalink, auth_token, **kwargs): - """Adds words to a WordList - - Args: - permalink, str: permalink of WordList to user (required) - - body, list[StringValue]: Array of words to add to WordList (optional) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: - """ - - allParams = ['permalink', 'body', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method addWordsToWordList" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}/words' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def getWordListWords(self, permalink, auth_token, **kwargs): - """Fetches words in a WordList - - Args: - permalink, str: ID of WordList to use (required) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - sortBy, str: Field to sort by (optional) - - sortOrder, str: Direction to sort (optional) - - skip, int: Results to skip (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[WordListWord] - """ - - allParams = ['permalink', 'auth_token', 'sortBy', 'sortOrder', 'skip', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWordListWords" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}/words' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('sortBy' in params): - queryParams['sortBy'] = self.apiClient.toPathValue(params['sortBy']) - if ('sortOrder' in params): - queryParams['sortOrder'] = self.apiClient.toPathValue(params['sortOrder']) - if ('skip' in params): - queryParams['skip'] = self.apiClient.toPathValue(params['skip']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[WordListWord]') - return responseObject - - - - - def deleteWordsFromWordList(self, permalink, auth_token, **kwargs): - """Removes words from a WordList - - Args: - permalink, str: permalink of WordList to use (required) - - body, list[StringValue]: Words to remove from WordList (optional) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: - """ - - allParams = ['permalink', 'body', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method deleteWordsFromWordList" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}/deleteWords' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - - - - - diff --git a/samples/client/wordnik-api/python/wordnik/WordListsApi.py b/samples/client/wordnik-api/python/wordnik/WordListsApi.py deleted file mode 100644 index 409d6f7b3cfa..000000000000 --- a/samples/client/wordnik-api/python/wordnik/WordListsApi.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - 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. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from models import * - - -class WordListsApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def createWordList(self, auth_token, **kwargs): - """Creates a WordList. - - Args: - body, WordList: WordList to create (optional) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: WordList - """ - - allParams = ['body', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method createWordList" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordLists.{format}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordList') - return responseObject - - - - - - - - - diff --git a/samples/client/wordnik-api/python/wordnik/WordsApi.py b/samples/client/wordnik-api/python/wordnik/WordsApi.py deleted file mode 100644 index a6b1f0bfc8ae..000000000000 --- a/samples/client/wordnik-api/python/wordnik/WordsApi.py +++ /dev/null @@ -1,434 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - 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. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from models import * - - -class WordsApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def searchWords(self, query, **kwargs): - """Searches words - - Args: - query, str: Search query (required) - - includePartOfSpeech, str: Only include these comma-delimited parts of speech (optional) - - excludePartOfSpeech, str: Exclude these comma-delimited parts of speech (optional) - - caseSensitive, str: Search case sensitive (optional) - - minCorpusCount, int: Minimum corpus frequency for terms (optional) - - maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - minDictionaryCount, int: Minimum number of dictionary entries for words returned (optional) - - maxDictionaryCount, int: Maximum dictionary definition count (optional) - - minLength, int: Minimum word length (optional) - - maxLength, int: Maximum word length (optional) - - skip, int: Results to skip (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: WordSearchResults - """ - - allParams = ['query', 'includePartOfSpeech', 'excludePartOfSpeech', 'caseSensitive', 'minCorpusCount', 'maxCorpusCount', 'minDictionaryCount', 'maxDictionaryCount', 'minLength', 'maxLength', 'skip', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method searchWords" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/words.{format}/search/{query}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('caseSensitive' in params): - queryParams['caseSensitive'] = self.apiClient.toPathValue(params['caseSensitive']) - if ('includePartOfSpeech' in params): - queryParams['includePartOfSpeech'] = self.apiClient.toPathValue(params['includePartOfSpeech']) - if ('excludePartOfSpeech' in params): - queryParams['excludePartOfSpeech'] = self.apiClient.toPathValue(params['excludePartOfSpeech']) - if ('minCorpusCount' in params): - queryParams['minCorpusCount'] = self.apiClient.toPathValue(params['minCorpusCount']) - if ('maxCorpusCount' in params): - queryParams['maxCorpusCount'] = self.apiClient.toPathValue(params['maxCorpusCount']) - if ('minDictionaryCount' in params): - queryParams['minDictionaryCount'] = self.apiClient.toPathValue(params['minDictionaryCount']) - if ('maxDictionaryCount' in params): - queryParams['maxDictionaryCount'] = self.apiClient.toPathValue(params['maxDictionaryCount']) - if ('minLength' in params): - queryParams['minLength'] = self.apiClient.toPathValue(params['minLength']) - if ('maxLength' in params): - queryParams['maxLength'] = self.apiClient.toPathValue(params['maxLength']) - if ('skip' in params): - queryParams['skip'] = self.apiClient.toPathValue(params['skip']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('query' in params): - replacement = str(self.apiClient.toPathValue(params['query'])) - resourcePath = resourcePath.replace('{' + 'query' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordSearchResults') - return responseObject - - - - - def getWordOfTheDay(self, **kwargs): - """Returns a specific WordOfTheDay - - Args: - date, str: Fetches by date in yyyy-MM-dd (optional) - - - - Returns: WordOfTheDay - """ - - allParams = ['date'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWordOfTheDay" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/words.{format}/wordOfTheDay' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('date' in params): - queryParams['date'] = self.apiClient.toPathValue(params['date']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordOfTheDay') - return responseObject - - - - - def reverseDictionary(self, query, **kwargs): - """Reverse dictionary search - - Args: - query, str: Search term (required) - - findSenseForWord, str: Restricts words and finds closest sense (optional) - - includeSourceDictionaries, str: Only include these comma-delimited source dictionaries (optional) - - excludeSourceDictionaries, str: Exclude these comma-delimited source dictionaries (optional) - - includePartOfSpeech, str: Only include these comma-delimited parts of speech (optional) - - excludePartOfSpeech, str: Exclude these comma-delimited parts of speech (optional) - - expandTerms, str: Expand terms (optional) - - sortBy, str: Attribute to sort by (optional) - - sortOrder, str: Sort direction (optional) - - minCorpusCount, int: Minimum corpus frequency for terms (optional) - - maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - minLength, int: Minimum word length (optional) - - maxLength, int: Maximum word length (optional) - - includeTags, str: Return a closed set of XML tags in response (optional) - - skip, str: Results to skip (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: DefinitionSearchResults - """ - - allParams = ['query', 'findSenseForWord', 'includeSourceDictionaries', 'excludeSourceDictionaries', 'includePartOfSpeech', 'excludePartOfSpeech', 'expandTerms', 'sortBy', 'sortOrder', 'minCorpusCount', 'maxCorpusCount', 'minLength', 'maxLength', 'includeTags', 'skip', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method reverseDictionary" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/words.{format}/reverseDictionary' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('query' in params): - queryParams['query'] = self.apiClient.toPathValue(params['query']) - if ('findSenseForWord' in params): - queryParams['findSenseForWord'] = self.apiClient.toPathValue(params['findSenseForWord']) - if ('includeSourceDictionaries' in params): - queryParams['includeSourceDictionaries'] = self.apiClient.toPathValue(params['includeSourceDictionaries']) - if ('excludeSourceDictionaries' in params): - queryParams['excludeSourceDictionaries'] = self.apiClient.toPathValue(params['excludeSourceDictionaries']) - if ('includePartOfSpeech' in params): - queryParams['includePartOfSpeech'] = self.apiClient.toPathValue(params['includePartOfSpeech']) - if ('excludePartOfSpeech' in params): - queryParams['excludePartOfSpeech'] = self.apiClient.toPathValue(params['excludePartOfSpeech']) - if ('minCorpusCount' in params): - queryParams['minCorpusCount'] = self.apiClient.toPathValue(params['minCorpusCount']) - if ('maxCorpusCount' in params): - queryParams['maxCorpusCount'] = self.apiClient.toPathValue(params['maxCorpusCount']) - if ('minLength' in params): - queryParams['minLength'] = self.apiClient.toPathValue(params['minLength']) - if ('maxLength' in params): - queryParams['maxLength'] = self.apiClient.toPathValue(params['maxLength']) - if ('expandTerms' in params): - queryParams['expandTerms'] = self.apiClient.toPathValue(params['expandTerms']) - if ('includeTags' in params): - queryParams['includeTags'] = self.apiClient.toPathValue(params['includeTags']) - if ('sortBy' in params): - queryParams['sortBy'] = self.apiClient.toPathValue(params['sortBy']) - if ('sortOrder' in params): - queryParams['sortOrder'] = self.apiClient.toPathValue(params['sortOrder']) - if ('skip' in params): - queryParams['skip'] = self.apiClient.toPathValue(params['skip']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'DefinitionSearchResults') - return responseObject - - - - - def getRandomWords(self, **kwargs): - """Returns an array of random WordObjects - - Args: - includePartOfSpeech, str: CSV part-of-speech values to include (optional) - - excludePartOfSpeech, str: CSV part-of-speech values to exclude (optional) - - sortBy, str: Attribute to sort by (optional) - - sortOrder, str: Sort direction (optional) - - hasDictionaryDef, str: Only return words with dictionary definitions (optional) - - minCorpusCount, int: Minimum corpus frequency for terms (optional) - - maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - minDictionaryCount, int: Minimum dictionary count (optional) - - maxDictionaryCount, int: Maximum dictionary count (optional) - - minLength, int: Minimum word length (optional) - - maxLength, int: Maximum word length (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[WordObject] - """ - - allParams = ['includePartOfSpeech', 'excludePartOfSpeech', 'sortBy', 'sortOrder', 'hasDictionaryDef', 'minCorpusCount', 'maxCorpusCount', 'minDictionaryCount', 'maxDictionaryCount', 'minLength', 'maxLength', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getRandomWords" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/words.{format}/randomWords' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('hasDictionaryDef' in params): - queryParams['hasDictionaryDef'] = self.apiClient.toPathValue(params['hasDictionaryDef']) - if ('includePartOfSpeech' in params): - queryParams['includePartOfSpeech'] = self.apiClient.toPathValue(params['includePartOfSpeech']) - if ('excludePartOfSpeech' in params): - queryParams['excludePartOfSpeech'] = self.apiClient.toPathValue(params['excludePartOfSpeech']) - if ('minCorpusCount' in params): - queryParams['minCorpusCount'] = self.apiClient.toPathValue(params['minCorpusCount']) - if ('maxCorpusCount' in params): - queryParams['maxCorpusCount'] = self.apiClient.toPathValue(params['maxCorpusCount']) - if ('minDictionaryCount' in params): - queryParams['minDictionaryCount'] = self.apiClient.toPathValue(params['minDictionaryCount']) - if ('maxDictionaryCount' in params): - queryParams['maxDictionaryCount'] = self.apiClient.toPathValue(params['maxDictionaryCount']) - if ('minLength' in params): - queryParams['minLength'] = self.apiClient.toPathValue(params['minLength']) - if ('maxLength' in params): - queryParams['maxLength'] = self.apiClient.toPathValue(params['maxLength']) - if ('sortBy' in params): - queryParams['sortBy'] = self.apiClient.toPathValue(params['sortBy']) - if ('sortOrder' in params): - queryParams['sortOrder'] = self.apiClient.toPathValue(params['sortOrder']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[WordObject]') - return responseObject - - - - - def getRandomWord(self, **kwargs): - """Returns a single random WordObject - - Args: - includePartOfSpeech, str: CSV part-of-speech values to include (optional) - - excludePartOfSpeech, str: CSV part-of-speech values to exclude (optional) - - hasDictionaryDef, str: Only return words with dictionary definitions (optional) - - minCorpusCount, int: Minimum corpus frequency for terms (optional) - - maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - minDictionaryCount, int: Minimum dictionary count (optional) - - maxDictionaryCount, int: Maximum dictionary count (optional) - - minLength, int: Minimum word length (optional) - - maxLength, int: Maximum word length (optional) - - - - Returns: WordObject - """ - - allParams = ['includePartOfSpeech', 'excludePartOfSpeech', 'hasDictionaryDef', 'minCorpusCount', 'maxCorpusCount', 'minDictionaryCount', 'maxDictionaryCount', 'minLength', 'maxLength'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getRandomWord" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/words.{format}/randomWord' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('hasDictionaryDef' in params): - queryParams['hasDictionaryDef'] = self.apiClient.toPathValue(params['hasDictionaryDef']) - if ('includePartOfSpeech' in params): - queryParams['includePartOfSpeech'] = self.apiClient.toPathValue(params['includePartOfSpeech']) - if ('excludePartOfSpeech' in params): - queryParams['excludePartOfSpeech'] = self.apiClient.toPathValue(params['excludePartOfSpeech']) - if ('minCorpusCount' in params): - queryParams['minCorpusCount'] = self.apiClient.toPathValue(params['minCorpusCount']) - if ('maxCorpusCount' in params): - queryParams['maxCorpusCount'] = self.apiClient.toPathValue(params['maxCorpusCount']) - if ('minDictionaryCount' in params): - queryParams['minDictionaryCount'] = self.apiClient.toPathValue(params['minDictionaryCount']) - if ('maxDictionaryCount' in params): - queryParams['maxDictionaryCount'] = self.apiClient.toPathValue(params['maxDictionaryCount']) - if ('minLength' in params): - queryParams['minLength'] = self.apiClient.toPathValue(params['minLength']) - if ('maxLength' in params): - queryParams['maxLength'] = self.apiClient.toPathValue(params['maxLength']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordObject') - return responseObject - - - - - - - - - diff --git a/samples/client/wordnik-api/python/wordnik/models/ApiTokenStatus.py b/samples/client/wordnik-api/python/wordnik/models/ApiTokenStatus.py deleted file mode 100644 index e39f286e4a88..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/ApiTokenStatus.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ApiTokenStatus: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'valid': 'bool', - 'token': 'str', - 'resetsInMillis': 'long', - 'remainingCalls': 'long', - 'expiresInMillis': 'long', - 'totalRequests': 'long' - - } - - - self.valid = None # bool - self.token = None # str - self.resetsInMillis = None # long - self.remainingCalls = None # long - self.expiresInMillis = None # long - self.totalRequests = None # long - diff --git a/samples/client/wordnik-api/python/wordnik/models/AudioFile.py b/samples/client/wordnik-api/python/wordnik/models/AudioFile.py deleted file mode 100644 index 24bb915a1156..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/AudioFile.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 AudioFile: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'attributionUrl': 'str', - 'commentCount': 'int', - 'voteCount': 'int', - 'fileUrl': 'str', - 'audioType': 'str', - 'id': 'long', - 'duration': 'float', - 'attributionText': 'str', - 'createdBy': 'str', - 'description': 'str', - 'createdAt': 'datetime', - 'voteWeightedAverage': 'float', - 'voteAverage': 'float', - 'word': 'str' - - } - - - self.attributionUrl = None # str - self.commentCount = None # int - self.voteCount = None # int - self.fileUrl = None # str - self.audioType = None # str - self.id = None # long - self.duration = None # float - self.attributionText = None # str - self.createdBy = None # str - self.description = None # str - self.createdAt = None # datetime - self.voteWeightedAverage = None # float - self.voteAverage = None # float - self.word = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/AuthenticationToken.py b/samples/client/wordnik-api/python/wordnik/models/AuthenticationToken.py deleted file mode 100644 index 73e2c76f4001..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/AuthenticationToken.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 AuthenticationToken: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'token': 'str', - 'userId': 'long', - 'userSignature': 'str' - - } - - - self.token = None # str - self.userId = None # long - self.userSignature = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/Bigram.py b/samples/client/wordnik-api/python/wordnik/models/Bigram.py deleted file mode 100644 index 61edbc8767da..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/Bigram.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Bigram: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'count': 'long', - 'gram2': 'str', - 'gram1': 'str', - 'wlmi': 'float', - 'mi': 'float' - - } - - - self.count = None # long - self.gram2 = None # str - self.gram1 = None # str - self.wlmi = None # float - self.mi = None # float - diff --git a/samples/client/wordnik-api/python/wordnik/models/Citation.py b/samples/client/wordnik-api/python/wordnik/models/Citation.py deleted file mode 100644 index bf62800aa26f..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/Citation.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Citation: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'cite': 'str', - 'source': 'str' - - } - - - self.cite = None # str - self.source = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/ContentProvider.py b/samples/client/wordnik-api/python/wordnik/models/ContentProvider.py deleted file mode 100644 index 7b7808a2c2cb..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/ContentProvider.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ContentProvider: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'name': 'str' - - } - - - self.id = None # int - self.name = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/Definition.py b/samples/client/wordnik-api/python/wordnik/models/Definition.py deleted file mode 100644 index 8cbe3a1dee62..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/Definition.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Definition: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'extendedText': 'str', - 'text': 'str', - 'sourceDictionary': 'str', - 'citations': 'list[Citation]', - 'labels': 'list[Label]', - 'score': 'float', - 'exampleUses': 'list[ExampleUsage]', - 'attributionUrl': 'str', - 'seqString': 'str', - 'attributionText': 'str', - 'relatedWords': 'list[Related]', - 'sequence': 'str', - 'word': 'str', - 'notes': 'list[Note]', - 'textProns': 'list[TextPron]', - 'partOfSpeech': 'str' - - } - - - self.extendedText = None # str - self.text = None # str - self.sourceDictionary = None # str - self.citations = None # list[Citation] - self.labels = None # list[Label] - self.score = None # float - self.exampleUses = None # list[ExampleUsage] - self.attributionUrl = None # str - self.seqString = None # str - self.attributionText = None # str - self.relatedWords = None # list[Related] - self.sequence = None # str - self.word = None # str - self.notes = None # list[Note] - self.textProns = None # list[TextPron] - self.partOfSpeech = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/DefinitionSearchResults.py b/samples/client/wordnik-api/python/wordnik/models/DefinitionSearchResults.py deleted file mode 100644 index ae7bf5d20d23..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/DefinitionSearchResults.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 DefinitionSearchResults: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'results': 'list[Definition]', - 'totalResults': 'int' - - } - - - self.results = None # list[Definition] - self.totalResults = None # int - diff --git a/samples/client/wordnik-api/python/wordnik/models/Example.py b/samples/client/wordnik-api/python/wordnik/models/Example.py deleted file mode 100644 index f103c2a00706..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/Example.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Example: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'long', - 'exampleId': 'long', - 'title': 'str', - 'text': 'str', - 'score': 'ScoredWord', - 'sentence': 'Sentence', - 'word': 'str', - 'provider': 'ContentProvider', - 'year': 'int', - 'rating': 'float', - 'documentId': 'long', - 'url': 'str' - - } - - - self.id = None # long - self.exampleId = None # long - self.title = None # str - self.text = None # str - self.score = None # ScoredWord - self.sentence = None # Sentence - self.word = None # str - self.provider = None # ContentProvider - self.year = None # int - self.rating = None # float - self.documentId = None # long - self.url = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/ExampleSearchResults.py b/samples/client/wordnik-api/python/wordnik/models/ExampleSearchResults.py deleted file mode 100644 index 01e05d9ca5b1..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/ExampleSearchResults.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ExampleSearchResults: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'facets': 'list[Facet]', - 'examples': 'list[Example]' - - } - - - self.facets = None # list[Facet] - self.examples = None # list[Example] - diff --git a/samples/client/wordnik-api/python/wordnik/models/ExampleUsage.py b/samples/client/wordnik-api/python/wordnik/models/ExampleUsage.py deleted file mode 100644 index a42d3397681f..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/ExampleUsage.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ExampleUsage: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'text': 'str' - - } - - - self.text = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/Facet.py b/samples/client/wordnik-api/python/wordnik/models/Facet.py deleted file mode 100644 index 086c7229c1e6..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/Facet.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Facet: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'facetValues': 'list[FacetValue]', - 'name': 'str' - - } - - - self.facetValues = None # list[FacetValue] - self.name = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/FacetValue.py b/samples/client/wordnik-api/python/wordnik/models/FacetValue.py deleted file mode 100644 index c4cb9fa5d5ca..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/FacetValue.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 FacetValue: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'count': 'long', - 'value': 'str' - - } - - - self.count = None # long - self.value = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/Frequency.py b/samples/client/wordnik-api/python/wordnik/models/Frequency.py deleted file mode 100644 index f30616460824..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/Frequency.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Frequency: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'count': 'long', - 'year': 'int' - - } - - - self.count = None # long - self.year = None # int - diff --git a/samples/client/wordnik-api/python/wordnik/models/FrequencySummary.py b/samples/client/wordnik-api/python/wordnik/models/FrequencySummary.py deleted file mode 100644 index b994a44820da..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/FrequencySummary.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 FrequencySummary: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'unknownYearCount': 'int', - 'totalCount': 'long', - 'frequencyString': 'str', - 'word': 'str', - 'frequency': 'list[Frequency]' - - } - - - self.unknownYearCount = None # int - self.totalCount = None # long - self.frequencyString = None # str - self.word = None # str - self.frequency = None # list[Frequency] - diff --git a/samples/client/wordnik-api/python/wordnik/models/Label.py b/samples/client/wordnik-api/python/wordnik/models/Label.py deleted file mode 100644 index daa9136de3ea..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/Label.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Label: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'text': 'str', - 'type': 'str' - - } - - - self.text = None # str - self.type = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/Note.py b/samples/client/wordnik-api/python/wordnik/models/Note.py deleted file mode 100644 index ba19aa068a25..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/Note.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Note: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'noteType': 'str', - 'appliesTo': 'list[str]', - 'value': 'str', - 'pos': 'int' - - } - - - self.noteType = None # str - self.appliesTo = None # list[str] - self.value = None # str - self.pos = None # int - diff --git a/samples/client/wordnik-api/python/wordnik/models/Related.py b/samples/client/wordnik-api/python/wordnik/models/Related.py deleted file mode 100644 index 8a62f3a3accc..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/Related.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Related: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'label1': 'str', - 'relationshipType': 'str', - 'label2': 'str', - 'label3': 'str', - 'words': 'list[str]', - 'gram': 'str', - 'label4': 'str' - - } - - - self.label1 = None # str - self.relationshipType = None # str - self.label2 = None # str - self.label3 = None # str - self.words = None # list[str] - self.gram = None # str - self.label4 = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/ScoredWord.py b/samples/client/wordnik-api/python/wordnik/models/ScoredWord.py deleted file mode 100644 index 3044f21a877a..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/ScoredWord.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ScoredWord: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'position': 'int', - 'id': 'long', - 'docTermCount': 'int', - 'lemma': 'str', - 'wordType': 'str', - 'score': 'float', - 'sentenceId': 'long', - 'word': 'str', - 'stopword': 'bool', - 'baseWordScore': 'float', - 'partOfSpeech': 'str' - - } - - - self.position = None # int - self.id = None # long - self.docTermCount = None # int - self.lemma = None # str - self.wordType = None # str - self.score = None # float - self.sentenceId = None # long - self.word = None # str - self.stopword = None # bool - self.baseWordScore = None # float - self.partOfSpeech = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/ScrabbleScoreResult.py b/samples/client/wordnik-api/python/wordnik/models/ScrabbleScoreResult.py deleted file mode 100644 index 343029aa5b42..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/ScrabbleScoreResult.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ScrabbleScoreResult: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'value': 'int' - - } - - - self.value = None # int - diff --git a/samples/client/wordnik-api/python/wordnik/models/Sentence.py b/samples/client/wordnik-api/python/wordnik/models/Sentence.py deleted file mode 100644 index 77b11b9e1e8c..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/Sentence.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Sentence: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'hasScoredWords': 'bool', - 'id': 'long', - 'scoredWords': 'list[ScoredWord]', - 'display': 'str', - 'rating': 'int', - 'documentMetadataId': 'long' - - } - - - self.hasScoredWords = None # bool - self.id = None # long - self.scoredWords = None # list[ScoredWord] - self.display = None # str - self.rating = None # int - self.documentMetadataId = None # long - diff --git a/samples/client/wordnik-api/python/wordnik/models/SimpleDefinition.py b/samples/client/wordnik-api/python/wordnik/models/SimpleDefinition.py deleted file mode 100644 index 47be04d14077..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/SimpleDefinition.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 SimpleDefinition: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'text': 'str', - 'source': 'str', - 'note': 'str', - 'partOfSpeech': 'str' - - } - - - self.text = None # str - self.source = None # str - self.note = None # str - self.partOfSpeech = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/SimpleExample.py b/samples/client/wordnik-api/python/wordnik/models/SimpleExample.py deleted file mode 100644 index 032731ea389b..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/SimpleExample.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 SimpleExample: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'long', - 'title': 'str', - 'text': 'str', - 'url': 'str' - - } - - - self.id = None # long - self.title = None # str - self.text = None # str - self.url = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/StringValue.py b/samples/client/wordnik-api/python/wordnik/models/StringValue.py deleted file mode 100644 index bd3e111a6e16..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/StringValue.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 StringValue: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'word': 'str' - - } - - - self.word = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/Syllable.py b/samples/client/wordnik-api/python/wordnik/models/Syllable.py deleted file mode 100644 index ef6dac3e3b2b..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/Syllable.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Syllable: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'text': 'str', - 'seq': 'int', - 'type': 'str' - - } - - - self.text = None # str - self.seq = None # int - self.type = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/TextPron.py b/samples/client/wordnik-api/python/wordnik/models/TextPron.py deleted file mode 100644 index d7e2e40d63ea..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/TextPron.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 TextPron: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'raw': 'str', - 'seq': 'int', - 'rawType': 'str' - - } - - - self.raw = None # str - self.seq = None # int - self.rawType = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/User.py b/samples/client/wordnik-api/python/wordnik/models/User.py deleted file mode 100644 index 75e4f86eac58..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/User.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 User: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'long', - 'username': 'str', - 'email': 'str', - 'status': 'int', - 'faceBookId': 'str', - 'userName': 'str', - 'displayName': 'str', - 'password': 'str' - - } - - - self.id = None # long - self.username = None # str - self.email = None # str - self.status = None # int - self.faceBookId = None # str - self.userName = None # str - self.displayName = None # str - self.password = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/WordList.py b/samples/client/wordnik-api/python/wordnik/models/WordList.py deleted file mode 100644 index 86db47e572cf..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/WordList.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordList: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'long', - 'permalink': 'str', - 'name': 'str', - 'createdAt': 'datetime', - 'updatedAt': 'datetime', - 'lastActivityAt': 'datetime', - 'username': 'str', - 'userId': 'long', - 'description': 'str', - 'numberWordsInList': 'long', - 'type': 'str' - - } - - - self.id = None # long - self.permalink = None # str - self.name = None # str - self.createdAt = None # datetime - self.updatedAt = None # datetime - self.lastActivityAt = None # datetime - self.username = None # str - self.userId = None # long - self.description = None # str - self.numberWordsInList = None # long - self.type = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/WordListWord.py b/samples/client/wordnik-api/python/wordnik/models/WordListWord.py deleted file mode 100644 index bd69cc074355..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/WordListWord.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordListWord: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'long', - 'word': 'str', - 'username': 'str', - 'userId': 'long', - 'createdAt': 'datetime', - 'numberCommentsOnWord': 'long', - 'numberLists': 'long' - - } - - - self.id = None # long - self.word = None # str - self.username = None # str - self.userId = None # long - self.createdAt = None # datetime - self.numberCommentsOnWord = None # long - self.numberLists = None # long - diff --git a/samples/client/wordnik-api/python/wordnik/models/WordObject.py b/samples/client/wordnik-api/python/wordnik/models/WordObject.py deleted file mode 100644 index cfaf0b8cb991..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/WordObject.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordObject: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'long', - 'word': 'str', - 'originalWord': 'str', - 'suggestions': 'list[str]', - 'canonicalForm': 'str', - 'vulgar': 'str' - - } - - - self.id = None # long - self.word = None # str - self.originalWord = None # str - self.suggestions = None # list[str] - self.canonicalForm = None # str - self.vulgar = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/WordOfTheDay.py b/samples/client/wordnik-api/python/wordnik/models/WordOfTheDay.py deleted file mode 100644 index 122cf35a022e..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/WordOfTheDay.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordOfTheDay: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'long', - 'parentId': 'str', - 'category': 'str', - 'createdBy': 'str', - 'createdAt': 'datetime', - 'contentProvider': 'ContentProvider', - 'htmlExtra': 'str', - 'word': 'str', - 'definitions': 'list[SimpleDefinition]', - 'examples': 'list[SimpleExample]', - 'note': 'str', - 'publishDate': 'datetime' - - } - - - self.id = None # long - self.parentId = None # str - self.category = None # str - self.createdBy = None # str - self.createdAt = None # datetime - self.contentProvider = None # ContentProvider - self.htmlExtra = None # str - self.word = None # str - self.definitions = None # list[SimpleDefinition] - self.examples = None # list[SimpleExample] - self.note = None # str - self.publishDate = None # datetime - diff --git a/samples/client/wordnik-api/python/wordnik/models/WordSearchResult.py b/samples/client/wordnik-api/python/wordnik/models/WordSearchResult.py deleted file mode 100644 index bbb48b7ae011..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/WordSearchResult.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordSearchResult: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'count': 'long', - 'lexicality': 'float', - 'word': 'str' - - } - - - self.count = None # long - self.lexicality = None # float - self.word = None # str - diff --git a/samples/client/wordnik-api/python/wordnik/models/WordSearchResults.py b/samples/client/wordnik-api/python/wordnik/models/WordSearchResults.py deleted file mode 100644 index 49182e5ac77d..000000000000 --- a/samples/client/wordnik-api/python/wordnik/models/WordSearchResults.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordSearchResults: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'searchResults': 'list[WordSearchResult]', - 'totalResults': 'int' - - } - - - self.searchResults = None # list[WordSearchResult] - self.totalResults = None # int - diff --git a/samples/client/wordnik-api/python/wordnik/swagger.py b/samples/client/wordnik-api/python/wordnik/swagger.py deleted file mode 100644 index 1065ad800e78..000000000000 --- a/samples/client/wordnik-api/python/wordnik/swagger.py +++ /dev/null @@ -1,209 +0,0 @@ -#!/usr/bin/env python -"""Wordnik.com's Swagger generic API client. This client handles the client- -server communication, and is invariant across implementations. Specifics of -the methods and models for each application are generated from the Swagger -templates.""" - -import sys -import os -import re -import urllib -import urllib2 -import httplib -import json -import datetime - -from models import * - - -class ApiClient: - """Generic API client for Swagger client library builds""" - - def __init__(self, apiKey=None, apiServer=None): - if apiKey == None: - raise Exception('You must pass an apiKey when instantiating the ' - 'APIClient') - self.apiKey = apiKey - self.apiServer = apiServer - self.cookie = None - - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None): - - url = self.apiServer + resourcePath - headers = {} - if headerParams: - for param, value in headerParams.iteritems(): - headers[param] = value - - #headers['Content-type'] = 'application/json' - headers['api_key'] = self.apiKey - - if self.cookie: - headers['Cookie'] = self.cookie - - data = None - - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.urlencode(sentQueryParams) - - if method in ['GET']: - - #Options to add statements later on and for compatibility - pass - - elif method in ['POST', 'PUT', 'DELETE']: - - if postData: - headers['Content-type'] = 'application/json' - data = self.sanitizeForSerialization(postData) - data = json.dumps(data) - - else: - raise Exception('Method ' + method + ' is not recognized.') - - request = MethodRequest(method=method, url=url, headers=headers, - data=data) - - # Make the request - response = urllib2.urlopen(request) - if 'Set-Cookie' in response.headers: - self.cookie = response.headers['Set-Cookie'] - string = response.read() - - try: - data = json.loads(string) - except ValueError: # PUT requests don't return anything - data = None - - return data - - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value - """ - if type(obj) == list: - return urllib.quote(','.join(obj)) - else: - return urllib.quote(str(obj)) - - def sanitizeForSerialization(self, obj): - """Dump an object into JSON for POSTing.""" - - if type(obj) == type(None): - return None - elif type(obj) in [str, int, long, float, bool]: - return obj - elif type(obj) == list: - return [self.sanitizeForSerialization(subObj) for subObj in obj] - elif type(obj) == datetime.datetime: - return obj.isoformat() - else: - if type(obj) == dict: - objDict = obj - else: - objDict = obj.__dict__ - return {key: self.sanitizeForSerialization(val) - for (key, val) in objDict.iteritems() - if key != 'swaggerTypes'} - - if type(postData) == list: - # Could be a list of objects - if type(postData[0]) in safeToDump: - data = json.dumps(postData) - else: - data = json.dumps([datum.__dict__ for datum in postData]) - elif type(postData) not in safeToDump: - data = json.dumps(postData.__dict__) - - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. - - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" - - # Have to accept objClass as string or actual type. Type could be a - # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] - - if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) - else: # not a native type, must be model class - objClass = eval(objClass + '.' + objClass) - - if objClass in [int, long, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: - # Server will always return a time stamp in UTC, but with - # trailing +0000 indicating no offset from UTC. So don't process - # last 5 characters. - return datetime.datetime.strptime(obj[:-5], - "%Y-%m-%dT%H:%M:%S.%f") - - instance = objClass() - - for attr, attrType in instance.swaggerTypes.iteritems(): - if obj is not None and attr in obj and type(obj) in [list, dict]: - value = obj[attr] - if attrType in ['str', 'int', 'long', 'float', 'bool']: - attrType = eval(attrType) - try: - value = attrType(value) - except UnicodeEncodeError: - value = unicode(value) - except TypeError: - value = value - setattr(instance, attr, value) - elif (attrType == 'datetime'): - setattr(instance, attr, datetime.datetime.strptime(value[:-5], - "%Y-%m-%dT%H:%M:%S.%f")) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] - if not value: - setattr(instance, attr, None) - else: - for subValue in value: - subValues.append(self.deserialize(subValue, - subClass)) - setattr(instance, attr, subValues) - else: - setattr(instance, attr, self.deserialize(value, - objClass)) - - return instance - - -class MethodRequest(urllib2.Request): - - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib2.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" - - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib2.Request.__init__(self, *args, **kwargs) - - def get_method(self): - return getattr(self, 'method', urllib2.Request.get_method(self)) - - diff --git a/samples/client/wordnik-api/python3/Python3WordnikApiCodegen.scala b/samples/client/wordnik-api/python3/Python3WordnikApiCodegen.scala deleted file mode 100644 index 169e896f461d..000000000000 --- a/samples/client/wordnik-api/python3/Python3WordnikApiCodegen.scala +++ /dev/null @@ -1,34 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicPython3Generator - -import java.io.File - -object Python3WordnikApiCodegen extends BasicPython3Generator { - def main(args: Array[String]) = generateClient(args) - - def destinationRoot = "samples/client/wordnik-api/python3/wordnik" - - // where to write generated code - override def destinationDir = destinationRoot - - // supporting classes - override def supportingFiles = List( - ("__init__.mustache", destinationDir, "__init__.py"), - ("swagger.mustache", destinationDir + File.separator + apiPackage.getOrElse(""), "swagger.py"), - ("__init__.mustache", destinationDir + File.separator + modelPackage.getOrElse(""), "__init__.py")) -} diff --git a/samples/client/wordnik-api/python3/README.md b/samples/client/wordnik-api/python3/README.md deleted file mode 100644 index 5130bf1dbfe6..000000000000 --- a/samples/client/wordnik-api/python3/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Python 3 client for Wordnik.com API - -## Overview - -This is a Python 3 client for the Wordnik.com v4 API. For more information, see http://developer.wordnik.com/ . - -## Generation - -This client was generated using the provided script: - -``` -/bin/python3-wordnik-api.sh -``` - -## Testing - -The tests require you to set three environment varibales: - -```sh -export API_KEY=your api key -export USER_NAME=some wordnik.com username -export PASSWORD=the user's password -``` - -The tests can be run as follows, e.g: - -``` -python3.2 tests/BaseApiTest.py -``` diff --git a/samples/client/wordnik-api/python3/tests/AccountApiTest.py b/samples/client/wordnik-api/python3/tests/AccountApiTest.py deleted file mode 100644 index ea8384b11052..000000000000 --- a/samples/client/wordnik-api/python3/tests/AccountApiTest.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python - -import sys -import unittest -import urllib.request, urllib.error, urllib.parse -import json - -from BaseApiTest import BaseApiTest - -sys.path = ['./'] + sys.path -from wordnik import * - - -class AccountApiTest(BaseApiTest): - - def setUp(self): - super(AccountApiTest, self).setUp() - self.authToken = self.accountApi.authenticate(self.username, - self.password).token - - def testAuthenticate(self): - res = self.accountApi.authenticate(self.username, self.password) - assert res, 'null authenticate result' - assert res.token, 'invalid authentication token' - assert res.userId != 0, 'userId was 0' - assert res.userSignature, 'invalid userSignature' - - def testAuthenticatePost(self): - res = self.accountApi.authenticatePost(self.username, self.password) - assert res, 'null authenticate result' - assert res.token, 'invalid authentication token' - assert res.userId != 0, 'userId was 0' - assert res.userSignature, 'invalid userSignature' - - def testGetWordListsForLoggedInUser(self): - res = self.accountApi.getWordListsForLoggedInUser(self.authToken) - assert res, 'null getWordListsForLoggedInUser result' - assert len(res) != 0, 'number of lists shouldn\'t be 0' - - def testGetApiTokenStatus(self): - res = self.accountApi.getApiTokenStatus() - assert res, 'null getApiTokenStatus result' - assert res.valid, 'token status not valid' - assert res.remainingCalls != 0, 'remainingCalls shouldn\'t be 0' - - def testGetLoggedInUser(self): - res = self.accountApi.getLoggedInUser(self.authToken) - assert res, 'null getLoggedInUser result' - assert res.id != 0, 'if shouldn\'t be 0' - assert res.username == self.username, 'username was incorrect' - assert res.status == 0, 'user status should be 0' - assert res.email, 'email shouldn\'t be null' - - -if __name__ == "__main__": - unittest.main() diff --git a/samples/client/wordnik-api/python3/tests/BaseApiTest.py b/samples/client/wordnik-api/python3/tests/BaseApiTest.py deleted file mode 100644 index 69c338e59473..000000000000 --- a/samples/client/wordnik-api/python3/tests/BaseApiTest.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python -"""Unit tests for Python3 Wordnik API client. - -Requires you to set three environment varibales: - API_KEY your API key - USER_NAME the username of a user - PASSWORD the user's password - -Run all tests: - - python3.2 BaseApiTest.py - -""" - -import sys -import os -import unittest - -sys.path = ['./'] + sys.path -from wordnik import * - - -class BaseApiTest(unittest.TestCase): - - def setUp(self): - self.apiUrl = 'http://api.wordnik.com/v4' - self.apiKey = os.environ.get('API_KEY') - self.username = os.environ.get('USER_NAME') - self.password = os.environ.get('PASSWORD') - - client = swagger.ApiClient(self.apiKey, self.apiUrl) - self.accountApi = AccountApi.AccountApi(client) - self.wordApi = WordApi.WordApi(client) - self.wordListApi = WordListApi.WordListApi(client) - self.wordsApi = WordsApi.WordsApi(client) - -if __name__ == "__main__": - - from AccountApiTest import AccountApiTest - from WordApiTest import WordApiTest - from WordListApiTest import WordListApiTest - from WordsApiTest import WordsApiTest - - unittest.main() diff --git a/samples/client/wordnik-api/python3/tests/WordApiTest.py b/samples/client/wordnik-api/python3/tests/WordApiTest.py deleted file mode 100644 index 7be40634c66c..000000000000 --- a/samples/client/wordnik-api/python3/tests/WordApiTest.py +++ /dev/null @@ -1,91 +0,0 @@ -#!/usr/bin/env python - -import sys -import unittest -import urllib.request, urllib.error, urllib.parse -import json - -from BaseApiTest import BaseApiTest - -sys.path = ['./'] + sys.path -from wordnik import * - - -class WordApiTest(BaseApiTest): - - def testWordApis(self): - url = 'http://api.wordnik.com/v4/word.json' - request = urllib.request.urlopen(url) - encoding = request.headers.get_content_charset() - if not encoding: - encoding = 'iso-8859-1' - response = request.read().decode(encoding) - doc = json.loads(response) - assert len(doc['apis']) == 12, 'there should be 12 word apis' - - def testGetWord(self): - res = self.wordApi.getWord('cat') - assert res, 'null getWord result' - assert res.word == 'cat', 'word should be "cat"' - - def testGetWordWithSuggestions(self): - res = self.wordApi.getWord('cAt', includeSuggestions=True) - assert res, 'null getWord result' - assert res.word == 'cAt', 'word should be "cAt"' - - def testGetWordWithCanonicalForm(self): - res = self.wordApi.getWord('cAt', useCanonical=True) - assert res, 'null getWord result' - assert res.word == 'cat', 'word should be "cAt"' - - def testGetDefinitions(self): - res = self.wordApi.getDefinitions('cat', limit=10) - assert res, 'null getDefinitions result' - assert len(res) == 10, 'should have 10 definitions' - - def testGetExamples(self): - res = self.wordApi.getExamples('cat', limit=5) - assert res, 'null getExamples result' - assert len(res.examples) == 5, 'should have 5 definitions' - - def testGetTopExample(self): - res = self.wordApi.getTopExample('cat') - assert res, 'null getTopExample result' - assert res.word == 'cat', 'word should be "cat"' - - def testGetHyphenation(self): - res = self.wordApi.getHyphenation('catalog', limit=1) - assert res, 'null getHyphenation result' - assert len(res) == 1, 'hypenation length should be 1' - - def testGetWordFrequency(self): - res = self.wordApi.getWordFrequency('cat') - assert res, 'null getWordFrequency result' - assert res.totalCount != 0, 'total count should not be 0' - - def testGetPhrases(self): - res = self.wordApi.getPhrases('money') - assert res, 'null getPhrases result' - assert len(res) != 0, 'getPhrases length should not be 0' - - def testGetRelatedWords(self): - res = self.wordApi.getRelatedWords('cat') - assert res, 'null getRelatedWords result' - for related in res: - assert len(related.words) <= 10, 'should have <= 10 related words' - - def testGetAudio(self): - res = self.wordApi.getAudio('cat', useCanonical=True, limit=2) - assert res, 'null getAudio result' - assert len(res) == 2, 'getAudio size should be 2' - - def testGetScrabbleScore(self): - res = self.wordApi.getScrabbleScore('quixotry') - assert res.value == 27, 'quixotry should have a Scrabble score of 27' - - def testGetEtymologies(self): - res = self.wordApi.getEtymologies('butter') - assert 'of Scythian origin' in res[0], 'etymology of "butter" should contain the phrase "of Scythian origin"' - -if __name__ == "__main__": - unittest.main() diff --git a/samples/client/wordnik-api/python3/tests/WordListApiTest.py b/samples/client/wordnik-api/python3/tests/WordListApiTest.py deleted file mode 100644 index cdf651b40fa1..000000000000 --- a/samples/client/wordnik-api/python3/tests/WordListApiTest.py +++ /dev/null @@ -1,103 +0,0 @@ -#!/usr/bin/env python - -import sys -import unittest -import urllib.request, urllib.error, urllib.parse -import json - -from BaseApiTest import BaseApiTest - -sys.path = ['./'] + sys.path -from wordnik import * - - -class WordListApiTest(BaseApiTest): - - def setUp(self): - super(WordListApiTest, self).setUp() - self.authToken = self.accountApi.authenticate(self.username, - self.password).token - self.existingList = self.accountApi.getWordListsForLoggedInUser(self.authToken, - limit=1)[0] - - from wordnik.models import WordList - wordList = WordList.WordList() - wordList.name = "my test list" - wordList.type = "PUBLIC" - wordList.description = "some words I want to play with" - - # sampleList = self.wordListApi.createWordList(wordList, - # self.authToken) - - # if not sampleList: - # raise Exception("can't create test list to run tests with") - - def testGetWordListByPermalink(self): - res = self.wordListApi.getWordListByPermalink(self.existingList.permalink, - self.authToken) - assert res, 'null getWordListByPermalink result' - - def testGetWordListByPermalink(self): - res = self.wordListApi.getWordListByPermalink(self.existingList.permalink, - self.authToken) - assert res, 'null getWordListByPermalink result' - - def testUpdateWordList(self): - import time - description = 'list updated at ' + str(time.time()) - self.existingList.description = description - self.wordListApi.updateWordList(self.existingList.permalink, - self.authToken, body=self.existingList) - - res = self.wordListApi.getWordListByPermalink(self.existingList.permalink, - self.authToken) - - assert res.description == description, 'did not update wordlist' - - def testAddWordsToWordList(self): - - from wordnik.models import StringValue - wordsToAdd = [] - word1 = StringValue.StringValue() - word1.word = "delicious" - wordsToAdd.append(word1) - word2 = StringValue.StringValue() - word2.word = "tasty" - wordsToAdd.append(word2) - word3 = StringValue.StringValue() - word3.word = "scrumptious" - wordsToAdd.append(word3) - self.wordListApi.addWordsToWordList(self.existingList.permalink, - self.authToken, body=wordsToAdd) - - res = self.wordListApi.getWordListWords(self.existingList.permalink, - self.authToken) - listSet = set([word.word for word in res]) - addedSet = set(["delicious", "tasty", "scrumptious"]) - assert len(listSet.intersection(addedSet)) == 3, 'did not get added words' - - def testDeleteWordsFromList(self): - from wordnik.models import StringValue - wordsToRemove = [] - word1 = StringValue.StringValue() - word1.word = "delicious" - wordsToRemove.append(word1) - word2 = StringValue.StringValue() - word2.word = "tasty" - wordsToRemove.append(word2) - word3 = StringValue.StringValue() - word3.word = "scrumptious" - wordsToRemove.append(word3) - self.wordListApi.deleteWordsFromWordList(self.existingList.permalink, - self.authToken, - body=wordsToRemove) - - res = self.wordListApi.getWordListWords(self.existingList.permalink, - self.authToken) - listSet = set([word.word for word in res]) - addedSet = set(["delicious", "tasty", "scrumptious"]) - assert len(listSet.intersection(addedSet)) == 0, 'did not get removed words' - - -if __name__ == "__main__": - unittest.main() diff --git a/samples/client/wordnik-api/python3/tests/WordsApiTest.py b/samples/client/wordnik-api/python3/tests/WordsApiTest.py deleted file mode 100644 index d11240eb6bed..000000000000 --- a/samples/client/wordnik-api/python3/tests/WordsApiTest.py +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env python - -import sys -import unittest -import urllib.request, urllib.error, urllib.parse -import json - -from BaseApiTest import BaseApiTest - -sys.path = ['./'] + sys.path -from wordnik import * - - -class WordsApiTest(BaseApiTest): - - def testSearchWords(self): - res = self.wordsApi.searchWords('tree') - assert res, 'null search result' - assert res.searchResults[0].word == 'tree', 'word should be "tree"' - assert res.totalResults != 0, 'should not have 0 results' - - def testGetWordOfTheDay(self): - res = self.wordsApi.getWordOfTheDay() - assert res, 'null wordOfTheDay result' - - def testReverseDictionary(self): - res = self.wordsApi.reverseDictionary("hairy") - assert res, 'null reverseDictionary result' - assert res.totalResults != 0, 'should not have 0 results' - assert len(res.results) != 0, 'should not have 0 results' - - def testGetRandomWords(self): - res = self.wordsApi.getRandomWords() - assert res, 'null getRandomWords result' - assert len(res) == 10, 'should get 10 random words' - - def testGetRandomWords(self): - res = self.wordsApi.getRandomWords() - assert res, 'null getRandomWord result' - - def testGetRandomWord(self): - res = self.wordsApi.getRandomWords() - assert res, 'null getRandomWord result' - - -if __name__ == "__main__": - unittest.main() diff --git a/samples/client/wordnik-api/python3/wordnik/AccountApi.py b/samples/client/wordnik-api/python3/wordnik/AccountApi.py deleted file mode 100644 index 7890f3e4c338..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/AccountApi.py +++ /dev/null @@ -1,270 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - 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. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -class AccountApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def authenticate(self, username, password, **kwargs): - """Authenticates a User - - Args: - username, str: A confirmed Wordnik username (required) - - password, str: The user's password (required) - - - - Returns: AuthenticationToken - """ - - allParams = ['username', 'password'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method authenticate" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/account.{format}/authenticate/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('password' in params): - queryParams['password'] = self.apiClient.toPathValue(params['password']) - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'AuthenticationToken') - return responseObject - - - - - def authenticatePost(self, username, body, **kwargs): - """Authenticates a user - - Args: - username, str: A confirmed Wordnik username (required) - - body, str: The user's password (required) - - - - Returns: AuthenticationToken - """ - - allParams = ['username', 'body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method authenticatePost" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/account.{format}/authenticate/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'AuthenticationToken') - return responseObject - - - - - def getWordListsForLoggedInUser(self, auth_token, **kwargs): - """Fetches WordList objects for the logged-in user. - - Args: - auth_token, str: auth_token of logged-in user (required) - - skip, int: Results to skip (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[WordList] - """ - - allParams = ['auth_token', 'skip', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWordListsForLoggedInUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/account.{format}/wordLists' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('skip' in params): - queryParams['skip'] = self.apiClient.toPathValue(params['skip']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[WordList]') - return responseObject - - - - - def getApiTokenStatus(self, **kwargs): - """Returns usage statistics for the API account. - - Args: - api_key, str: Wordnik authentication token (optional) - - - - Returns: ApiTokenStatus - """ - - allParams = ['api_key'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getApiTokenStatus" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/account.{format}/apiTokenStatus' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('api_key' in params): - headerParams['api_key'] = params['api_key'] - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'ApiTokenStatus') - return responseObject - - - - - def getLoggedInUser(self, auth_token, **kwargs): - """Returns the logged-in User - - Args: - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: User - """ - - allParams = ['auth_token'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getLoggedInUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/account.{format}/user' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'User') - return responseObject - - - - - - - - - diff --git a/samples/client/wordnik-api/python3/wordnik/WordApi.py b/samples/client/wordnik-api/python3/wordnik/WordApi.py deleted file mode 100644 index 133df6af59f4..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/WordApi.py +++ /dev/null @@ -1,705 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - 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. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -class WordApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def getExamples(self, word, **kwargs): - """Returns examples for a word - - Args: - word, str: Word to return examples for (required) - - includeDuplicates, str: Show duplicate examples from different sources (optional) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - skip, int: Results to skip (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: ExampleSearchResults - """ - - allParams = ['word', 'includeDuplicates', 'useCanonical', 'skip', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getExamples" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/examples' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('includeDuplicates' in params): - queryParams['includeDuplicates'] = self.apiClient.toPathValue(params['includeDuplicates']) - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('skip' in params): - queryParams['skip'] = self.apiClient.toPathValue(params['skip']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'ExampleSearchResults') - return responseObject - - - - - def getWord(self, word, **kwargs): - """Given a word as a string, returns the WordObject that represents it - - Args: - word, str: String value of WordObject to return (required) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - includeSuggestions, str: Return suggestions (for correct spelling, case variants, etc.) (optional) - - - - Returns: WordObject - """ - - allParams = ['word', 'useCanonical', 'includeSuggestions'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWord" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('includeSuggestions' in params): - queryParams['includeSuggestions'] = self.apiClient.toPathValue(params['includeSuggestions']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordObject') - return responseObject - - - - - def getDefinitions(self, word, **kwargs): - """Return definitions for a word - - Args: - word, str: Word to return definitions for (required) - - partOfSpeech, str: CSV list of part-of-speech types (optional) - - sourceDictionaries, str: Source dictionary to return definitions from. If 'all' is received, results are returned from all sources. If multiple values are received (e.g. 'century,wiktionary'), results are returned from the first specified dictionary that has definitions. If left blank, results are returned from the first dictionary that has definitions. By default, dictionaries are searched in this order: ahd, wiktionary, webster, century, wordnet (optional) - - limit, int: Maximum number of results to return (optional) - - includeRelated, str: Return related words with definitions (optional) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - includeTags, str: Return a closed set of XML tags in response (optional) - - - - Returns: list[Definition] - """ - - allParams = ['word', 'partOfSpeech', 'sourceDictionaries', 'limit', 'includeRelated', 'useCanonical', 'includeTags'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getDefinitions" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/definitions' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('partOfSpeech' in params): - queryParams['partOfSpeech'] = self.apiClient.toPathValue(params['partOfSpeech']) - if ('includeRelated' in params): - queryParams['includeRelated'] = self.apiClient.toPathValue(params['includeRelated']) - if ('sourceDictionaries' in params): - queryParams['sourceDictionaries'] = self.apiClient.toPathValue(params['sourceDictionaries']) - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('includeTags' in params): - queryParams['includeTags'] = self.apiClient.toPathValue(params['includeTags']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Definition]') - return responseObject - - - - - def getTopExample(self, word, **kwargs): - """Returns a top example for a word - - Args: - word, str: Word to fetch examples for (required) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - - - Returns: Example - """ - - allParams = ['word', 'useCanonical'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getTopExample" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/topExample' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Example') - return responseObject - - - - - def getRelatedWords(self, word, **kwargs): - """Given a word as a string, returns relationships from the Word Graph - - Args: - word, str: Word to fetch relationships for (required) - - relationshipTypes, str: Limits the total results per type of relationship type (optional) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - limitPerRelationshipType, int: Restrict to the supplied relatinship types (optional) - - - - Returns: list[Related] - """ - - allParams = ['word', 'relationshipTypes', 'useCanonical', 'limitPerRelationshipType'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getRelatedWords" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/relatedWords' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('relationshipTypes' in params): - queryParams['relationshipTypes'] = self.apiClient.toPathValue(params['relationshipTypes']) - if ('limitPerRelationshipType' in params): - queryParams['limitPerRelationshipType'] = self.apiClient.toPathValue(params['limitPerRelationshipType']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Related]') - return responseObject - - - - - def getTextPronunciations(self, word, **kwargs): - """Returns text pronunciations for a given word - - Args: - word, str: Word to get pronunciations for (required) - - sourceDictionary, str: Get from a single dictionary (optional) - - typeFormat, str: Text pronunciation type (optional) - - useCanonical, str: If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[TextPron] - """ - - allParams = ['word', 'sourceDictionary', 'typeFormat', 'useCanonical', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getTextPronunciations" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/pronunciations' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('sourceDictionary' in params): - queryParams['sourceDictionary'] = self.apiClient.toPathValue(params['sourceDictionary']) - if ('typeFormat' in params): - queryParams['typeFormat'] = self.apiClient.toPathValue(params['typeFormat']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[TextPron]') - return responseObject - - - - - def getHyphenation(self, word, **kwargs): - """Returns syllable information for a word - - Args: - word, str: Word to get syllables for (required) - - sourceDictionary, str: Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet. (optional) - - useCanonical, str: If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[Syllable] - """ - - allParams = ['word', 'sourceDictionary', 'useCanonical', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getHyphenation" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/hyphenation' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('sourceDictionary' in params): - queryParams['sourceDictionary'] = self.apiClient.toPathValue(params['sourceDictionary']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Syllable]') - return responseObject - - - - - def getWordFrequency(self, word, **kwargs): - """Returns word usage over time - - Args: - word, str: Word to return (required) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - startYear, int: Starting Year (optional) - - endYear, int: Ending Year (optional) - - - - Returns: FrequencySummary - """ - - allParams = ['word', 'useCanonical', 'startYear', 'endYear'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWordFrequency" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/frequency' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('startYear' in params): - queryParams['startYear'] = self.apiClient.toPathValue(params['startYear']) - if ('endYear' in params): - queryParams['endYear'] = self.apiClient.toPathValue(params['endYear']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'FrequencySummary') - return responseObject - - - - - def getPhrases(self, word, **kwargs): - """Fetches bi-gram phrases for a word - - Args: - word, str: Word to fetch phrases for (required) - - limit, int: Maximum number of results to return (optional) - - wlmi, int: Minimum WLMI for the phrase (optional) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - - - Returns: list[Bigram] - """ - - allParams = ['word', 'limit', 'wlmi', 'useCanonical'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getPhrases" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/phrases' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('wlmi' in params): - queryParams['wlmi'] = self.apiClient.toPathValue(params['wlmi']) - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Bigram]') - return responseObject - - - - - def getEtymologies(self, word, **kwargs): - """Fetches etymology data - - Args: - word, str: Word to return (required) - - useCanonical, str: If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. (optional) - - - - Returns: list[str] - """ - - allParams = ['word', 'useCanonical'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getEtymologies" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/etymologies' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[str]') - return responseObject - - - - - def getAudio(self, word, **kwargs): - """Fetches audio metadata for a word. - - Args: - word, str: Word to get audio for. (required) - - useCanonical, str: Use the canonical form of the word (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[AudioFile] - """ - - allParams = ['word', 'useCanonical', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getAudio" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/audio' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('useCanonical' in params): - queryParams['useCanonical'] = self.apiClient.toPathValue(params['useCanonical']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[AudioFile]') - return responseObject - - - - - def getScrabbleScore(self, word, **kwargs): - """Returns the Scrabble score for a word - - Args: - word, str: Word to get scrabble score for. (required) - - - - Returns: ScrabbleScoreResult - """ - - allParams = ['word'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getScrabbleScore" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/word.{format}/{word}/scrabbleScore' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('word' in params): - replacement = str(self.apiClient.toPathValue(params['word'])) - resourcePath = resourcePath.replace('{' + 'word' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'ScrabbleScoreResult') - return responseObject - - - - - - - - - diff --git a/samples/client/wordnik-api/python3/wordnik/WordListApi.py b/samples/client/wordnik-api/python3/wordnik/WordListApi.py deleted file mode 100644 index d395147798dc..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/WordListApi.py +++ /dev/null @@ -1,333 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - 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. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -class WordListApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def updateWordList(self, permalink, auth_token, **kwargs): - """Updates an existing WordList - - Args: - permalink, str: permalink of WordList to update (required) - - body, WordList: Updated WordList (optional) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: - """ - - allParams = ['permalink', 'body', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method updateWordList" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PUT' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def deleteWordList(self, permalink, auth_token, **kwargs): - """Deletes an existing WordList - - Args: - permalink, str: ID of WordList to delete (required) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: - """ - - allParams = ['permalink', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method deleteWordList" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def getWordListByPermalink(self, permalink, auth_token, **kwargs): - """Fetches a WordList by ID - - Args: - permalink, str: permalink of WordList to fetch (required) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: WordList - """ - - allParams = ['permalink', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWordListByPermalink" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordList') - return responseObject - - - - - def addWordsToWordList(self, permalink, auth_token, **kwargs): - """Adds words to a WordList - - Args: - permalink, str: permalink of WordList to user (required) - - body, list[StringValue]: Array of words to add to WordList (optional) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: - """ - - allParams = ['permalink', 'body', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method addWordsToWordList" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}/words' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def getWordListWords(self, permalink, auth_token, **kwargs): - """Fetches words in a WordList - - Args: - permalink, str: ID of WordList to use (required) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - sortBy, str: Field to sort by (optional) - - sortOrder, str: Direction to sort (optional) - - skip, int: Results to skip (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[WordListWord] - """ - - allParams = ['permalink', 'auth_token', 'sortBy', 'sortOrder', 'skip', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWordListWords" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}/words' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('sortBy' in params): - queryParams['sortBy'] = self.apiClient.toPathValue(params['sortBy']) - if ('sortOrder' in params): - queryParams['sortOrder'] = self.apiClient.toPathValue(params['sortOrder']) - if ('skip' in params): - queryParams['skip'] = self.apiClient.toPathValue(params['skip']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[WordListWord]') - return responseObject - - - - - def deleteWordsFromWordList(self, permalink, auth_token, **kwargs): - """Removes words from a WordList - - Args: - permalink, str: permalink of WordList to use (required) - - body, list[StringValue]: Words to remove from WordList (optional) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: - """ - - allParams = ['permalink', 'body', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method deleteWordsFromWordList" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordList.{format}/{permalink}/deleteWords' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - if ('permalink' in params): - replacement = str(self.apiClient.toPathValue(params['permalink'])) - resourcePath = resourcePath.replace('{' + 'permalink' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - - - - - diff --git a/samples/client/wordnik-api/python3/wordnik/WordListsApi.py b/samples/client/wordnik-api/python3/wordnik/WordListsApi.py deleted file mode 100644 index f30c40466f33..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/WordListsApi.py +++ /dev/null @@ -1,82 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - 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. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -class WordListsApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def createWordList(self, auth_token, **kwargs): - """Creates a WordList. - - Args: - body, WordList: WordList to create (optional) - - auth_token, str: The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above) (required) - - - - Returns: WordList - """ - - allParams = ['body', 'auth_token'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method createWordList" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/wordLists.{format}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - if ('auth_token' in params): - headerParams['auth_token'] = params['auth_token'] - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordList') - return responseObject - - - - - - - - - diff --git a/samples/client/wordnik-api/python3/wordnik/WordsApi.py b/samples/client/wordnik-api/python3/wordnik/WordsApi.py deleted file mode 100644 index c8e4394f5d1b..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/WordsApi.py +++ /dev/null @@ -1,434 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - 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. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -class WordsApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def searchWords(self, query, **kwargs): - """Searches words - - Args: - query, str: Search query (required) - - includePartOfSpeech, str: Only include these comma-delimited parts of speech (optional) - - excludePartOfSpeech, str: Exclude these comma-delimited parts of speech (optional) - - caseSensitive, str: Search case sensitive (optional) - - minCorpusCount, int: Minimum corpus frequency for terms (optional) - - maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - minDictionaryCount, int: Minimum number of dictionary entries for words returned (optional) - - maxDictionaryCount, int: Maximum dictionary definition count (optional) - - minLength, int: Minimum word length (optional) - - maxLength, int: Maximum word length (optional) - - skip, int: Results to skip (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: WordSearchResults - """ - - allParams = ['query', 'includePartOfSpeech', 'excludePartOfSpeech', 'caseSensitive', 'minCorpusCount', 'maxCorpusCount', 'minDictionaryCount', 'maxDictionaryCount', 'minLength', 'maxLength', 'skip', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method searchWords" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/words.{format}/search/{query}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('caseSensitive' in params): - queryParams['caseSensitive'] = self.apiClient.toPathValue(params['caseSensitive']) - if ('includePartOfSpeech' in params): - queryParams['includePartOfSpeech'] = self.apiClient.toPathValue(params['includePartOfSpeech']) - if ('excludePartOfSpeech' in params): - queryParams['excludePartOfSpeech'] = self.apiClient.toPathValue(params['excludePartOfSpeech']) - if ('minCorpusCount' in params): - queryParams['minCorpusCount'] = self.apiClient.toPathValue(params['minCorpusCount']) - if ('maxCorpusCount' in params): - queryParams['maxCorpusCount'] = self.apiClient.toPathValue(params['maxCorpusCount']) - if ('minDictionaryCount' in params): - queryParams['minDictionaryCount'] = self.apiClient.toPathValue(params['minDictionaryCount']) - if ('maxDictionaryCount' in params): - queryParams['maxDictionaryCount'] = self.apiClient.toPathValue(params['maxDictionaryCount']) - if ('minLength' in params): - queryParams['minLength'] = self.apiClient.toPathValue(params['minLength']) - if ('maxLength' in params): - queryParams['maxLength'] = self.apiClient.toPathValue(params['maxLength']) - if ('skip' in params): - queryParams['skip'] = self.apiClient.toPathValue(params['skip']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - if ('query' in params): - replacement = str(self.apiClient.toPathValue(params['query'])) - resourcePath = resourcePath.replace('{' + 'query' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordSearchResults') - return responseObject - - - - - def getWordOfTheDay(self, **kwargs): - """Returns a specific WordOfTheDay - - Args: - date, str: Fetches by date in yyyy-MM-dd (optional) - - - - Returns: WordOfTheDay - """ - - allParams = ['date'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getWordOfTheDay" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/words.{format}/wordOfTheDay' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('date' in params): - queryParams['date'] = self.apiClient.toPathValue(params['date']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordOfTheDay') - return responseObject - - - - - def reverseDictionary(self, query, **kwargs): - """Reverse dictionary search - - Args: - query, str: Search term (required) - - findSenseForWord, str: Restricts words and finds closest sense (optional) - - includeSourceDictionaries, str: Only include these comma-delimited source dictionaries (optional) - - excludeSourceDictionaries, str: Exclude these comma-delimited source dictionaries (optional) - - includePartOfSpeech, str: Only include these comma-delimited parts of speech (optional) - - excludePartOfSpeech, str: Exclude these comma-delimited parts of speech (optional) - - expandTerms, str: Expand terms (optional) - - sortBy, str: Attribute to sort by (optional) - - sortOrder, str: Sort direction (optional) - - minCorpusCount, int: Minimum corpus frequency for terms (optional) - - maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - minLength, int: Minimum word length (optional) - - maxLength, int: Maximum word length (optional) - - includeTags, str: Return a closed set of XML tags in response (optional) - - skip, str: Results to skip (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: DefinitionSearchResults - """ - - allParams = ['query', 'findSenseForWord', 'includeSourceDictionaries', 'excludeSourceDictionaries', 'includePartOfSpeech', 'excludePartOfSpeech', 'expandTerms', 'sortBy', 'sortOrder', 'minCorpusCount', 'maxCorpusCount', 'minLength', 'maxLength', 'includeTags', 'skip', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method reverseDictionary" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/words.{format}/reverseDictionary' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('query' in params): - queryParams['query'] = self.apiClient.toPathValue(params['query']) - if ('findSenseForWord' in params): - queryParams['findSenseForWord'] = self.apiClient.toPathValue(params['findSenseForWord']) - if ('includeSourceDictionaries' in params): - queryParams['includeSourceDictionaries'] = self.apiClient.toPathValue(params['includeSourceDictionaries']) - if ('excludeSourceDictionaries' in params): - queryParams['excludeSourceDictionaries'] = self.apiClient.toPathValue(params['excludeSourceDictionaries']) - if ('includePartOfSpeech' in params): - queryParams['includePartOfSpeech'] = self.apiClient.toPathValue(params['includePartOfSpeech']) - if ('excludePartOfSpeech' in params): - queryParams['excludePartOfSpeech'] = self.apiClient.toPathValue(params['excludePartOfSpeech']) - if ('minCorpusCount' in params): - queryParams['minCorpusCount'] = self.apiClient.toPathValue(params['minCorpusCount']) - if ('maxCorpusCount' in params): - queryParams['maxCorpusCount'] = self.apiClient.toPathValue(params['maxCorpusCount']) - if ('minLength' in params): - queryParams['minLength'] = self.apiClient.toPathValue(params['minLength']) - if ('maxLength' in params): - queryParams['maxLength'] = self.apiClient.toPathValue(params['maxLength']) - if ('expandTerms' in params): - queryParams['expandTerms'] = self.apiClient.toPathValue(params['expandTerms']) - if ('includeTags' in params): - queryParams['includeTags'] = self.apiClient.toPathValue(params['includeTags']) - if ('sortBy' in params): - queryParams['sortBy'] = self.apiClient.toPathValue(params['sortBy']) - if ('sortOrder' in params): - queryParams['sortOrder'] = self.apiClient.toPathValue(params['sortOrder']) - if ('skip' in params): - queryParams['skip'] = self.apiClient.toPathValue(params['skip']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'DefinitionSearchResults') - return responseObject - - - - - def getRandomWords(self, **kwargs): - """Returns an array of random WordObjects - - Args: - includePartOfSpeech, str: CSV part-of-speech values to include (optional) - - excludePartOfSpeech, str: CSV part-of-speech values to exclude (optional) - - sortBy, str: Attribute to sort by (optional) - - sortOrder, str: Sort direction (optional) - - hasDictionaryDef, str: Only return words with dictionary definitions (optional) - - minCorpusCount, int: Minimum corpus frequency for terms (optional) - - maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - minDictionaryCount, int: Minimum dictionary count (optional) - - maxDictionaryCount, int: Maximum dictionary count (optional) - - minLength, int: Minimum word length (optional) - - maxLength, int: Maximum word length (optional) - - limit, int: Maximum number of results to return (optional) - - - - Returns: list[WordObject] - """ - - allParams = ['includePartOfSpeech', 'excludePartOfSpeech', 'sortBy', 'sortOrder', 'hasDictionaryDef', 'minCorpusCount', 'maxCorpusCount', 'minDictionaryCount', 'maxDictionaryCount', 'minLength', 'maxLength', 'limit'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getRandomWords" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/words.{format}/randomWords' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('hasDictionaryDef' in params): - queryParams['hasDictionaryDef'] = self.apiClient.toPathValue(params['hasDictionaryDef']) - if ('includePartOfSpeech' in params): - queryParams['includePartOfSpeech'] = self.apiClient.toPathValue(params['includePartOfSpeech']) - if ('excludePartOfSpeech' in params): - queryParams['excludePartOfSpeech'] = self.apiClient.toPathValue(params['excludePartOfSpeech']) - if ('minCorpusCount' in params): - queryParams['minCorpusCount'] = self.apiClient.toPathValue(params['minCorpusCount']) - if ('maxCorpusCount' in params): - queryParams['maxCorpusCount'] = self.apiClient.toPathValue(params['maxCorpusCount']) - if ('minDictionaryCount' in params): - queryParams['minDictionaryCount'] = self.apiClient.toPathValue(params['minDictionaryCount']) - if ('maxDictionaryCount' in params): - queryParams['maxDictionaryCount'] = self.apiClient.toPathValue(params['maxDictionaryCount']) - if ('minLength' in params): - queryParams['minLength'] = self.apiClient.toPathValue(params['minLength']) - if ('maxLength' in params): - queryParams['maxLength'] = self.apiClient.toPathValue(params['maxLength']) - if ('sortBy' in params): - queryParams['sortBy'] = self.apiClient.toPathValue(params['sortBy']) - if ('sortOrder' in params): - queryParams['sortOrder'] = self.apiClient.toPathValue(params['sortOrder']) - if ('limit' in params): - queryParams['limit'] = self.apiClient.toPathValue(params['limit']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[WordObject]') - return responseObject - - - - - def getRandomWord(self, **kwargs): - """Returns a single random WordObject - - Args: - includePartOfSpeech, str: CSV part-of-speech values to include (optional) - - excludePartOfSpeech, str: CSV part-of-speech values to exclude (optional) - - hasDictionaryDef, str: Only return words with dictionary definitions (optional) - - minCorpusCount, int: Minimum corpus frequency for terms (optional) - - maxCorpusCount, int: Maximum corpus frequency for terms (optional) - - minDictionaryCount, int: Minimum dictionary count (optional) - - maxDictionaryCount, int: Maximum dictionary count (optional) - - minLength, int: Minimum word length (optional) - - maxLength, int: Maximum word length (optional) - - - - Returns: WordObject - """ - - allParams = ['includePartOfSpeech', 'excludePartOfSpeech', 'hasDictionaryDef', 'minCorpusCount', 'maxCorpusCount', 'minDictionaryCount', 'maxDictionaryCount', 'minLength', 'maxLength'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getRandomWord" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/words.{format}/randomWord' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('hasDictionaryDef' in params): - queryParams['hasDictionaryDef'] = self.apiClient.toPathValue(params['hasDictionaryDef']) - if ('includePartOfSpeech' in params): - queryParams['includePartOfSpeech'] = self.apiClient.toPathValue(params['includePartOfSpeech']) - if ('excludePartOfSpeech' in params): - queryParams['excludePartOfSpeech'] = self.apiClient.toPathValue(params['excludePartOfSpeech']) - if ('minCorpusCount' in params): - queryParams['minCorpusCount'] = self.apiClient.toPathValue(params['minCorpusCount']) - if ('maxCorpusCount' in params): - queryParams['maxCorpusCount'] = self.apiClient.toPathValue(params['maxCorpusCount']) - if ('minDictionaryCount' in params): - queryParams['minDictionaryCount'] = self.apiClient.toPathValue(params['minDictionaryCount']) - if ('maxDictionaryCount' in params): - queryParams['maxDictionaryCount'] = self.apiClient.toPathValue(params['maxDictionaryCount']) - if ('minLength' in params): - queryParams['minLength'] = self.apiClient.toPathValue(params['minLength']) - if ('maxLength' in params): - queryParams['maxLength'] = self.apiClient.toPathValue(params['maxLength']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'WordObject') - return responseObject - - - - - - - - - diff --git a/samples/client/wordnik-api/python3/wordnik/__init__.py b/samples/client/wordnik-api/python3/wordnik/__init__.py deleted file mode 100644 index 39f84514fe91..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" -import os - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) - diff --git a/samples/client/wordnik-api/python3/wordnik/models/ApiTokenStatus.py b/samples/client/wordnik-api/python3/wordnik/models/ApiTokenStatus.py deleted file mode 100644 index 56b78b9ff353..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/ApiTokenStatus.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ApiTokenStatus: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'valid': 'bool', - 'token': 'str', - 'resetsInMillis': 'int', - 'remainingCalls': 'int', - 'expiresInMillis': 'int', - 'totalRequests': 'int' - - } - - - self.valid = None # bool - self.token = None # str - self.resetsInMillis = None # int - self.remainingCalls = None # int - self.expiresInMillis = None # int - self.totalRequests = None # int - diff --git a/samples/client/wordnik-api/python3/wordnik/models/AudioFile.py b/samples/client/wordnik-api/python3/wordnik/models/AudioFile.py deleted file mode 100644 index 340666f8860b..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/AudioFile.py +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 AudioFile: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'attributionUrl': 'str', - 'commentCount': 'int', - 'voteCount': 'int', - 'fileUrl': 'str', - 'audioType': 'str', - 'id': 'int', - 'duration': 'float', - 'attributionText': 'str', - 'createdBy': 'str', - 'description': 'str', - 'createdAt': 'datetime', - 'voteWeightedAverage': 'float', - 'voteAverage': 'float', - 'word': 'str' - - } - - - self.attributionUrl = None # str - self.commentCount = None # int - self.voteCount = None # int - self.fileUrl = None # str - self.audioType = None # str - self.id = None # int - self.duration = None # float - self.attributionText = None # str - self.createdBy = None # str - self.description = None # str - self.createdAt = None # datetime - self.voteWeightedAverage = None # float - self.voteAverage = None # float - self.word = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/AuthenticationToken.py b/samples/client/wordnik-api/python3/wordnik/models/AuthenticationToken.py deleted file mode 100644 index de35ab4083ed..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/AuthenticationToken.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 AuthenticationToken: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'token': 'str', - 'userId': 'int', - 'userSignature': 'str' - - } - - - self.token = None # str - self.userId = None # int - self.userSignature = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/Bigram.py b/samples/client/wordnik-api/python3/wordnik/models/Bigram.py deleted file mode 100644 index 5c7e489da5f5..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/Bigram.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Bigram: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'count': 'int', - 'gram2': 'str', - 'gram1': 'str', - 'wlmi': 'float', - 'mi': 'float' - - } - - - self.count = None # int - self.gram2 = None # str - self.gram1 = None # str - self.wlmi = None # float - self.mi = None # float - diff --git a/samples/client/wordnik-api/python3/wordnik/models/Citation.py b/samples/client/wordnik-api/python3/wordnik/models/Citation.py deleted file mode 100644 index bf62800aa26f..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/Citation.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Citation: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'cite': 'str', - 'source': 'str' - - } - - - self.cite = None # str - self.source = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/ContentProvider.py b/samples/client/wordnik-api/python3/wordnik/models/ContentProvider.py deleted file mode 100644 index 7b7808a2c2cb..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/ContentProvider.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ContentProvider: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'name': 'str' - - } - - - self.id = None # int - self.name = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/Definition.py b/samples/client/wordnik-api/python3/wordnik/models/Definition.py deleted file mode 100644 index 8cbe3a1dee62..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/Definition.py +++ /dev/null @@ -1,60 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Definition: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'extendedText': 'str', - 'text': 'str', - 'sourceDictionary': 'str', - 'citations': 'list[Citation]', - 'labels': 'list[Label]', - 'score': 'float', - 'exampleUses': 'list[ExampleUsage]', - 'attributionUrl': 'str', - 'seqString': 'str', - 'attributionText': 'str', - 'relatedWords': 'list[Related]', - 'sequence': 'str', - 'word': 'str', - 'notes': 'list[Note]', - 'textProns': 'list[TextPron]', - 'partOfSpeech': 'str' - - } - - - self.extendedText = None # str - self.text = None # str - self.sourceDictionary = None # str - self.citations = None # list[Citation] - self.labels = None # list[Label] - self.score = None # float - self.exampleUses = None # list[ExampleUsage] - self.attributionUrl = None # str - self.seqString = None # str - self.attributionText = None # str - self.relatedWords = None # list[Related] - self.sequence = None # str - self.word = None # str - self.notes = None # list[Note] - self.textProns = None # list[TextPron] - self.partOfSpeech = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/DefinitionSearchResults.py b/samples/client/wordnik-api/python3/wordnik/models/DefinitionSearchResults.py deleted file mode 100644 index ae7bf5d20d23..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/DefinitionSearchResults.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 DefinitionSearchResults: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'results': 'list[Definition]', - 'totalResults': 'int' - - } - - - self.results = None # list[Definition] - self.totalResults = None # int - diff --git a/samples/client/wordnik-api/python3/wordnik/models/Example.py b/samples/client/wordnik-api/python3/wordnik/models/Example.py deleted file mode 100644 index 9ce4b7c45008..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/Example.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Example: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'exampleId': 'int', - 'title': 'str', - 'text': 'str', - 'score': 'ScoredWord', - 'sentence': 'Sentence', - 'word': 'str', - 'provider': 'ContentProvider', - 'year': 'int', - 'rating': 'float', - 'documentId': 'int', - 'url': 'str' - - } - - - self.id = None # int - self.exampleId = None # int - self.title = None # str - self.text = None # str - self.score = None # ScoredWord - self.sentence = None # Sentence - self.word = None # str - self.provider = None # ContentProvider - self.year = None # int - self.rating = None # float - self.documentId = None # int - self.url = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/ExampleSearchResults.py b/samples/client/wordnik-api/python3/wordnik/models/ExampleSearchResults.py deleted file mode 100644 index 01e05d9ca5b1..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/ExampleSearchResults.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ExampleSearchResults: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'facets': 'list[Facet]', - 'examples': 'list[Example]' - - } - - - self.facets = None # list[Facet] - self.examples = None # list[Example] - diff --git a/samples/client/wordnik-api/python3/wordnik/models/ExampleUsage.py b/samples/client/wordnik-api/python3/wordnik/models/ExampleUsage.py deleted file mode 100644 index a42d3397681f..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/ExampleUsage.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ExampleUsage: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'text': 'str' - - } - - - self.text = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/Facet.py b/samples/client/wordnik-api/python3/wordnik/models/Facet.py deleted file mode 100644 index 086c7229c1e6..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/Facet.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Facet: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'facetValues': 'list[FacetValue]', - 'name': 'str' - - } - - - self.facetValues = None # list[FacetValue] - self.name = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/FacetValue.py b/samples/client/wordnik-api/python3/wordnik/models/FacetValue.py deleted file mode 100644 index f02f16ff1ca8..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/FacetValue.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 FacetValue: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'count': 'int', - 'value': 'str' - - } - - - self.count = None # int - self.value = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/Frequency.py b/samples/client/wordnik-api/python3/wordnik/models/Frequency.py deleted file mode 100644 index 73201364d028..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/Frequency.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Frequency: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'count': 'int', - 'year': 'int' - - } - - - self.count = None # int - self.year = None # int - diff --git a/samples/client/wordnik-api/python3/wordnik/models/FrequencySummary.py b/samples/client/wordnik-api/python3/wordnik/models/FrequencySummary.py deleted file mode 100644 index 148c7be5f3cf..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/FrequencySummary.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 FrequencySummary: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'unknownYearCount': 'int', - 'totalCount': 'int', - 'frequencyString': 'str', - 'word': 'str', - 'frequency': 'list[Frequency]' - - } - - - self.unknownYearCount = None # int - self.totalCount = None # int - self.frequencyString = None # str - self.word = None # str - self.frequency = None # list[Frequency] - diff --git a/samples/client/wordnik-api/python3/wordnik/models/Label.py b/samples/client/wordnik-api/python3/wordnik/models/Label.py deleted file mode 100644 index daa9136de3ea..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/Label.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Label: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'text': 'str', - 'type': 'str' - - } - - - self.text = None # str - self.type = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/Note.py b/samples/client/wordnik-api/python3/wordnik/models/Note.py deleted file mode 100644 index ba19aa068a25..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/Note.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Note: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'noteType': 'str', - 'appliesTo': 'list[str]', - 'value': 'str', - 'pos': 'int' - - } - - - self.noteType = None # str - self.appliesTo = None # list[str] - self.value = None # str - self.pos = None # int - diff --git a/samples/client/wordnik-api/python3/wordnik/models/Related.py b/samples/client/wordnik-api/python3/wordnik/models/Related.py deleted file mode 100644 index 8a62f3a3accc..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/Related.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Related: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'label1': 'str', - 'relationshipType': 'str', - 'label2': 'str', - 'label3': 'str', - 'words': 'list[str]', - 'gram': 'str', - 'label4': 'str' - - } - - - self.label1 = None # str - self.relationshipType = None # str - self.label2 = None # str - self.label3 = None # str - self.words = None # list[str] - self.gram = None # str - self.label4 = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/ScoredWord.py b/samples/client/wordnik-api/python3/wordnik/models/ScoredWord.py deleted file mode 100644 index a3069177db50..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/ScoredWord.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ScoredWord: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'position': 'int', - 'id': 'int', - 'docTermCount': 'int', - 'lemma': 'str', - 'wordType': 'str', - 'score': 'float', - 'sentenceId': 'int', - 'word': 'str', - 'stopword': 'bool', - 'baseWordScore': 'float', - 'partOfSpeech': 'str' - - } - - - self.position = None # int - self.id = None # int - self.docTermCount = None # int - self.lemma = None # str - self.wordType = None # str - self.score = None # float - self.sentenceId = None # int - self.word = None # str - self.stopword = None # bool - self.baseWordScore = None # float - self.partOfSpeech = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/ScrabbleScoreResult.py b/samples/client/wordnik-api/python3/wordnik/models/ScrabbleScoreResult.py deleted file mode 100644 index 343029aa5b42..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/ScrabbleScoreResult.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 ScrabbleScoreResult: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'value': 'int' - - } - - - self.value = None # int - diff --git a/samples/client/wordnik-api/python3/wordnik/models/Sentence.py b/samples/client/wordnik-api/python3/wordnik/models/Sentence.py deleted file mode 100644 index b1925b638c0a..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/Sentence.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Sentence: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'hasScoredWords': 'bool', - 'id': 'int', - 'scoredWords': 'list[ScoredWord]', - 'display': 'str', - 'rating': 'int', - 'documentMetadataId': 'int' - - } - - - self.hasScoredWords = None # bool - self.id = None # int - self.scoredWords = None # list[ScoredWord] - self.display = None # str - self.rating = None # int - self.documentMetadataId = None # int - diff --git a/samples/client/wordnik-api/python3/wordnik/models/SimpleDefinition.py b/samples/client/wordnik-api/python3/wordnik/models/SimpleDefinition.py deleted file mode 100644 index 47be04d14077..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/SimpleDefinition.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 SimpleDefinition: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'text': 'str', - 'source': 'str', - 'note': 'str', - 'partOfSpeech': 'str' - - } - - - self.text = None # str - self.source = None # str - self.note = None # str - self.partOfSpeech = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/SimpleExample.py b/samples/client/wordnik-api/python3/wordnik/models/SimpleExample.py deleted file mode 100644 index 3419d1bc2709..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/SimpleExample.py +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 SimpleExample: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'title': 'str', - 'text': 'str', - 'url': 'str' - - } - - - self.id = None # int - self.title = None # str - self.text = None # str - self.url = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/StringValue.py b/samples/client/wordnik-api/python3/wordnik/models/StringValue.py deleted file mode 100644 index bd3e111a6e16..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/StringValue.py +++ /dev/null @@ -1,30 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 StringValue: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'word': 'str' - - } - - - self.word = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/Syllable.py b/samples/client/wordnik-api/python3/wordnik/models/Syllable.py deleted file mode 100644 index ef6dac3e3b2b..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/Syllable.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 Syllable: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'text': 'str', - 'seq': 'int', - 'type': 'str' - - } - - - self.text = None # str - self.seq = None # int - self.type = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/TextPron.py b/samples/client/wordnik-api/python3/wordnik/models/TextPron.py deleted file mode 100644 index d7e2e40d63ea..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/TextPron.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 TextPron: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'raw': 'str', - 'seq': 'int', - 'rawType': 'str' - - } - - - self.raw = None # str - self.seq = None # int - self.rawType = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/User.py b/samples/client/wordnik-api/python3/wordnik/models/User.py deleted file mode 100644 index 534cbd0a0af7..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/User.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 User: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'username': 'str', - 'email': 'str', - 'status': 'int', - 'faceBookId': 'str', - 'userName': 'str', - 'displayName': 'str', - 'password': 'str' - - } - - - self.id = None # int - self.username = None # str - self.email = None # str - self.status = None # int - self.faceBookId = None # str - self.userName = None # str - self.displayName = None # str - self.password = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/WordList.py b/samples/client/wordnik-api/python3/wordnik/models/WordList.py deleted file mode 100644 index b2be16b322a4..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/WordList.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordList: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'permalink': 'str', - 'name': 'str', - 'createdAt': 'datetime', - 'updatedAt': 'datetime', - 'lastActivityAt': 'datetime', - 'username': 'str', - 'userId': 'int', - 'description': 'str', - 'numberWordsInList': 'int', - 'type': 'str' - - } - - - self.id = None # int - self.permalink = None # str - self.name = None # str - self.createdAt = None # datetime - self.updatedAt = None # datetime - self.lastActivityAt = None # datetime - self.username = None # str - self.userId = None # int - self.description = None # str - self.numberWordsInList = None # int - self.type = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/WordListWord.py b/samples/client/wordnik-api/python3/wordnik/models/WordListWord.py deleted file mode 100644 index 1fc93ef30e08..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/WordListWord.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordListWord: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'word': 'str', - 'username': 'str', - 'userId': 'int', - 'createdAt': 'datetime', - 'numberCommentsOnWord': 'int', - 'numberLists': 'int' - - } - - - self.id = None # int - self.word = None # str - self.username = None # str - self.userId = None # int - self.createdAt = None # datetime - self.numberCommentsOnWord = None # int - self.numberLists = None # int - diff --git a/samples/client/wordnik-api/python3/wordnik/models/WordObject.py b/samples/client/wordnik-api/python3/wordnik/models/WordObject.py deleted file mode 100644 index a0dde636a796..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/WordObject.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordObject: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'word': 'str', - 'originalWord': 'str', - 'suggestions': 'list[str]', - 'canonicalForm': 'str', - 'vulgar': 'str' - - } - - - self.id = None # int - self.word = None # str - self.originalWord = None # str - self.suggestions = None # list[str] - self.canonicalForm = None # str - self.vulgar = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/WordOfTheDay.py b/samples/client/wordnik-api/python3/wordnik/models/WordOfTheDay.py deleted file mode 100644 index 35b76cf4c2d5..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/WordOfTheDay.py +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordOfTheDay: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'parentId': 'str', - 'category': 'str', - 'createdBy': 'str', - 'createdAt': 'datetime', - 'contentProvider': 'ContentProvider', - 'htmlExtra': 'str', - 'word': 'str', - 'definitions': 'list[SimpleDefinition]', - 'examples': 'list[SimpleExample]', - 'note': 'str', - 'publishDate': 'datetime' - - } - - - self.id = None # int - self.parentId = None # str - self.category = None # str - self.createdBy = None # str - self.createdAt = None # datetime - self.contentProvider = None # ContentProvider - self.htmlExtra = None # str - self.word = None # str - self.definitions = None # list[SimpleDefinition] - self.examples = None # list[SimpleExample] - self.note = None # str - self.publishDate = None # datetime - diff --git a/samples/client/wordnik-api/python3/wordnik/models/WordSearchResult.py b/samples/client/wordnik-api/python3/wordnik/models/WordSearchResult.py deleted file mode 100644 index e6491d691f90..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/WordSearchResult.py +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordSearchResult: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'count': 'int', - 'lexicality': 'float', - 'word': 'str' - - } - - - self.count = None # int - self.lexicality = None # float - self.word = None # str - diff --git a/samples/client/wordnik-api/python3/wordnik/models/WordSearchResults.py b/samples/client/wordnik-api/python3/wordnik/models/WordSearchResults.py deleted file mode 100644 index 49182e5ac77d..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/WordSearchResults.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - 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 WordSearchResults: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'searchResults': 'list[WordSearchResult]', - 'totalResults': 'int' - - } - - - self.searchResults = None # list[WordSearchResult] - self.totalResults = None # int - diff --git a/samples/client/wordnik-api/python3/wordnik/models/__init__.py b/samples/client/wordnik-api/python3/wordnik/models/__init__.py deleted file mode 100644 index 39f84514fe91..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/models/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" -import os - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) - diff --git a/samples/client/wordnik-api/python3/wordnik/swagger.py b/samples/client/wordnik-api/python3/wordnik/swagger.py deleted file mode 100644 index 293cc09cb552..000000000000 --- a/samples/client/wordnik-api/python3/wordnik/swagger.py +++ /dev/null @@ -1,204 +0,0 @@ -#!/usr/bin/env python -"""Wordnik.com's Swagger generic API client. This client handles the client- -server communication, and is invariant across implementations. Specifics of -the methods and models for each application are generated from the Swagger -templates.""" - -import sys -import os -import re -import urllib.request, urllib.error, urllib.parse -import http.client -import json -import datetime - -from .models import * - - -class ApiClient: - """Generic API client for Swagger client library builds""" - - def __init__(self, apiKey=None, apiServer=None): - if apiKey == None: - raise Exception('You must pass an apiKey when instantiating the ' - 'APIClient') - self.apiKey = apiKey - self.apiServer = apiServer - self.cookie = None - - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None): - - url = self.apiServer + resourcePath - headers = {} - if headerParams: - for param, value in headerParams.items(): - headers[param] = value - - #headers['Content-type'] = 'application/json' - headers['api_key'] = self.apiKey - - if self.cookie: - headers['Cookie'] = self.cookie - - data = None - - - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.parse.urlencode(sentQueryParams) - - if method in ['GET']: - - #Options to add statements later on and for compatibility - pass - - elif method in ['POST', 'PUT', 'DELETE']: - - if postData: - headers['Content-type'] = 'application/json' - data = self.sanitizeForSerialization(postData) - data = json.dumps(data) - - else: - raise Exception('Method ' + method + ' is not recognized.') - - if data: - data = data.encode('utf-8') - - requestParams = MethodRequest(method=method, url=url, - headers=headers, data=data) - - # Make the request - request = urllib.request.urlopen(requestParams) - encoding = request.headers.get_content_charset() - if not encoding: - encoding = 'iso-8859-1' - response = request.read().decode(encoding) - - try: - data = json.loads(response) - except ValueError: # PUT requests don't return anything - data = None - - return data - - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value - """ - if type(obj) == list: - return urllib.parse.quote(','.join(obj)) - else: - return urllib.parse.quote(str(obj)) - - def sanitizeForSerialization(self, obj): - """Dump an object into JSON for POSTing.""" - - if type(obj) == type(None): - return None - elif type(obj) in [str, int, float, bool]: - return obj - elif type(obj) == list: - return [self.sanitizeForSerialization(subObj) for subObj in obj] - elif type(obj) == datetime.datetime: - return obj.isoformat() - else: - if type(obj) == dict: - objDict = obj - else: - objDict = obj.__dict__ - return {key: self.sanitizeForSerialization(val) - for (key, val) in objDict.items() - if key != 'swaggerTypes'} - - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. - - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" - - # Have to accept objClass as string or actual type. Type could be a - # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] - - if (objClass in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) - else: # not a native type, must be model class - objClass = eval(objClass + '.' + objClass) - - if objClass in [int, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: - # Server will always return a time stamp in UTC, but with - # trailing +0000 indicating no offset from UTC. So don't process - # last 5 characters. - return datetime.datetime.strptime(obj[:-5], - "%Y-%m-%dT%H:%M:%S.%f") - - instance = objClass() - - for attr, attrType in instance.swaggerTypes.items(): - - if attr in obj: - value = obj[attr] - if attrType in ['str', 'int', 'float', 'bool']: - attrType = eval(attrType) - try: - value = attrType(value) - except UnicodeEncodeError: - value = unicode(value) - except TypeError: - value = value - setattr(instance, attr, value) - elif (attrType == 'datetime'): - setattr(instance, attr, datetime.datetime.strptime(value[:-5], - "%Y-%m-%dT%H:%M:%S.%f")) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] - if not value: - setattr(instance, attr, None) - else: - for subValue in value: - subValues.append(self.deserialize(subValue, - subClass)) - setattr(instance, attr, subValues) - else: - setattr(instance, attr, self.deserialize(value, - objClass)) - - return instance - - -class MethodRequest(urllib.request.Request): - - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" - - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib.request.Request.__init__(self, *args, **kwargs) - - def get_method(self): - return getattr(self, 'method', urllib.request.Request.get_method(self)) - diff --git a/samples/client/wordnik-api/scala/README.md b/samples/client/wordnik-api/scala/README.md deleted file mode 100644 index 65310cbd0866..000000000000 --- a/samples/client/wordnik-api/scala/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# Wordnik Scala client library - -## Overview -This is a full client library for the Wordnik API. It requires that you have a valid Wordnik API Key--you -can get one for free at http://developer.wordnik.com. - -This library is built using the Wordnik [Swagger](http://swagger.wordnik.com) client library generator. You -can re-generate this library by running ./bin/scala-wordnik-api.sh from the swagger-codegen project - -## Usage -Generate the client library with Maven: - -``` -mvn package -DskipTests=true -``` - -Run the tests if you like--note, these require you have an active Wordnik API key, username, and password: - -``` -mvn package -DAPI_KEY={YOUR_API_KEY} -DUSER_NAME={YOUR_USER_NAME} -DPASSWORD={YOUR_PASSWORD} -``` - -Add the library to your project and you're ready to go: - -```scala -import com.wordnik.client.api._ -import com.wordnik.client.model._ - -object Test { - def main(args: Array[String]) = { - if(args.length == 0) { - println("Please pass your API key") - sys.exit(0) - } - val key = args(0) - val api = new WordApi - api.addHeader("api_key", key) - api.getDefinitions("cat", null, null, 10).flatten.foreach(definition => { - println(definition) - }) - } -} -``` - -This project was built with the following minimum requirements: - -* Maven 3.0 -* Java JDK 6 \ No newline at end of file diff --git a/samples/client/wordnik-api/scala/ScalaWordnikApiCodegen.scala b/samples/client/wordnik-api/scala/ScalaWordnikApiCodegen.scala deleted file mode 100644 index 1acc4cc9e87e..000000000000 --- a/samples/client/wordnik-api/scala/ScalaWordnikApiCodegen.scala +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicScalaGenerator - -object ScalaWordnikApiCodegen extends BasicScalaGenerator { - def main(args: Array[String]) = generateClient(args) - - def destinationRoot = "samples/client/wordnik-api/scala" - - // where to write generated code - override def destinationDir = destinationRoot + "/src/main/scala" - - // package for api invoker - override def invokerPackage = Some("com.wordnik.client.common") - - // package for models - override def modelPackage = Some("com.wordnik.client.model") - - // package for api classes - override def apiPackage = Some("com.wordnik.client.api") - - // supporting classes - override def supportingFiles = List( - ("apiInvoker.mustache", destinationDir + "/" + invokerPackage.get.replace(".", java.io.File.separator), "ApiInvoker.scala"), - ("pom.mustache", destinationRoot, "pom.xml")) -} diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ContentProvider.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ContentProvider.scala deleted file mode 100644 index 9457347444e4..000000000000 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ContentProvider.scala +++ /dev/null @@ -1,6 +0,0 @@ -package com.wordnik.client.model - -case class ContentProvider ( - id: Int, - name: String) - diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/DefinitionSearchResults.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/DefinitionSearchResults.scala deleted file mode 100644 index 07be3a68b414..000000000000 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/DefinitionSearchResults.scala +++ /dev/null @@ -1,7 +0,0 @@ -package com.wordnik.client.model - -import com.wordnik.client.model.Definition -case class DefinitionSearchResults ( - results: List[Definition], - totalResults: Int) - diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ExampleSearchResults.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ExampleSearchResults.scala deleted file mode 100644 index a6e4e8f9e0f4..000000000000 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ExampleSearchResults.scala +++ /dev/null @@ -1,8 +0,0 @@ -package com.wordnik.client.model - -import com.wordnik.client.model.Facet -import com.wordnik.client.model.Example -case class ExampleSearchResults ( - facets: List[Facet], - examples: List[Example]) - diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Facet.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Facet.scala deleted file mode 100644 index e6c1fb012f36..000000000000 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Facet.scala +++ /dev/null @@ -1,7 +0,0 @@ -package com.wordnik.client.model - -import com.wordnik.client.model.FacetValue -case class Facet ( - facetValues: List[FacetValue], - name: String) - diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Frequency.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Frequency.scala deleted file mode 100644 index e84fd1edf1fc..000000000000 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Frequency.scala +++ /dev/null @@ -1,6 +0,0 @@ -package com.wordnik.client.model - -case class Frequency ( - count: Long, - year: Int) - diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Label.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Label.scala deleted file mode 100644 index e55183a7e402..000000000000 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Label.scala +++ /dev/null @@ -1,6 +0,0 @@ -package com.wordnik.client.model - -case class Label ( - text: String, - `type`: String) - diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ScrabbleScoreResult.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ScrabbleScoreResult.scala deleted file mode 100644 index 2e275f2fe7b5..000000000000 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ScrabbleScoreResult.scala +++ /dev/null @@ -1,5 +0,0 @@ -package com.wordnik.client.model - -case class ScrabbleScoreResult ( - value: Int) - diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Syllable.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Syllable.scala deleted file mode 100644 index 9175ecff9c37..000000000000 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Syllable.scala +++ /dev/null @@ -1,7 +0,0 @@ -package com.wordnik.client.model - -case class Syllable ( - text: String, - seq: Int, - `type`: String) - diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/WordSearchResults.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/WordSearchResults.scala deleted file mode 100644 index 885c35fd7a94..000000000000 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/WordSearchResults.scala +++ /dev/null @@ -1,7 +0,0 @@ -package com.wordnik.client.model - -import com.wordnik.client.model.WordSearchResult -case class WordSearchResults ( - searchResults: List[WordSearchResult], - totalResults: Int) - diff --git a/samples/client/wordnik-api/scala/src/test/scala/BaseApiTest.scala b/samples/client/wordnik-api/scala/src/test/scala/BaseApiTest.scala deleted file mode 100644 index 46316189c25e..000000000000 --- a/samples/client/wordnik-api/scala/src/test/scala/BaseApiTest.scala +++ /dev/null @@ -1,5 +0,0 @@ -trait BaseApiTest { - val API_KEY = System.getProperty("API_KEY") - val USER_NAME = System.getProperty("USER_NAME") - val PASSWORD = System.getProperty("PASSWORD") -} \ No newline at end of file diff --git a/samples/client/wordnik-api/spec-files/account.json b/samples/client/wordnik-api/spec-files/account.json deleted file mode 100644 index 5f3a89d4c9cb..000000000000 --- a/samples/client/wordnik-api/spec-files/account.json +++ /dev/null @@ -1,330 +0,0 @@ -{ - "resourcePath":"/account", - "apis":[ - { - "path":"/account.{format}/authenticate/{username}", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"username", - "description":"A confirmed Wordnik username", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"password", - "description":"The user's password", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Authenticates a User", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Account not available.", - "code":403 - }, - { - "reason":"User not found.", - "code":404 - } - ], - "nickname":"authenticate", - "responseClass":"AuthenticationToken" - }, - { - "parameters":[ - { - "name":"username", - "description":"A confirmed Wordnik username", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "description":"The user's password", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"body" - } - ], - "summary":"Authenticates a user", - "httpMethod":"POST", - "errorResponses":[ - { - "reason":"Account not available.", - "code":403 - }, - { - "reason":"User not found.", - "code":404 - } - ], - "nickname":"authenticatePost", - "responseClass":"AuthenticationToken" - } - ] - }, - { - "path":"/account.{format}/wordLists", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"auth_token", - "description":"auth_token of logged-in user", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"header" - }, - { - "name":"skip", - "defaultValue":"0", - "description":"Results to skip", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"limit", - "defaultValue":"50", - "description":"Maximum number of results to return", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Fetches WordList objects for the logged-in user.", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Not authenticated.", - "code":403 - }, - { - "reason":"User account not found.", - "code":404 - } - ], - "nickname":"getWordListsForLoggedInUser", - "responseClass":"List[WordList]" - } - ] - }, - { - "path":"/account.{format}/apiTokenStatus", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"api_key", - "description":"Wordnik authentication token", - "required":false, - "dataType":"string", - "allowMultiple":false, - "paramType":"header" - } - ], - "summary":"Returns usage statistics for the API account.", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"No token supplied.", - "code":400 - }, - { - "reason":"No API account with supplied token.", - "code":404 - } - ], - "nickname":"getApiTokenStatus", - "responseClass":"ApiTokenStatus" - } - ] - }, - { - "path":"/account.{format}/user", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"auth_token", - "description":"The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above)", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"header" - } - ], - "summary":"Returns the logged-in User", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Not logged in.", - "code":403 - }, - { - "reason":"User not found.", - "code":404 - } - ], - "nickname":"getLoggedInUser", - "responseClass":"User", - "notes":"Requires a valid auth_token to be set." - } - ] - } - ], - "apiVersion":"4.0", - "swaggerVersion":"1.0", - "basePath":"http://api.wordnik.com/v4", - "models":{ - "User":{ - "properties":{ - "id":{ - "type":"long" - }, - "username":{ - "type":"string" - }, - "email":{ - "type":"string" - }, - "status":{ - "type":"int" - }, - "faceBookId":{ - "type":"string" - }, - "userName":{ - "type":"string" - }, - "displayName":{ - "type":"string" - }, - "password":{ - "type":"string" - } - }, - "id":"User" - }, - "ApiTokenStatus":{ - "properties":{ - "valid":{ - "type":"boolean" - }, - "token":{ - "type":"string" - }, - "resetsInMillis":{ - "type":"long" - }, - "remainingCalls":{ - "type":"long" - }, - "expiresInMillis":{ - "type":"long" - }, - "totalRequests":{ - "type":"long" - } - }, - "id":"ApiTokenStatus" - }, - "AuthenticationToken":{ - "properties":{ - "token":{ - "type":"string" - }, - "userId":{ - "type":"long" - }, - "userSignature":{ - "type":"string" - } - }, - "id":"AuthenticationToken" - }, - "WordList":{ - "properties":{ - "id":{ - "type":"long", - "required":false - }, - "permalink":{ - "type":"string" - }, - "name":{ - "type":"string" - }, - "createdAt":{ - "type":"Date" - }, - "updatedAt":{ - "type":"Date" - }, - "lastActivityAt":{ - "type":"Date" - }, - "username":{ - "type":"string" - }, - "userId":{ - "type":"long" - }, - "description":{ - "type":"string" - }, - "numberWordsInList":{ - "type":"long" - }, - "type":{ - "type":"string" - } - }, - "id":"WordList" - }, - "WordListWord":{ - "properties":{ - "id":{ - "type":"long", - "required":true - }, - "word":{ - "type":"string" - }, - "username":{ - "type":"string" - }, - "userId":{ - "type":"long" - }, - "createdAt":{ - "type":"Date" - }, - "numberCommentsOnWord":{ - "type":"long" - }, - "numberLists":{ - "type":"long" - } - }, - "id":"WordListWord" - } - } -} \ No newline at end of file diff --git a/samples/client/wordnik-api/spec-files/resources.json b/samples/client/wordnik-api/spec-files/resources.json deleted file mode 100644 index 4a3f067f4efa..000000000000 --- a/samples/client/wordnik-api/spec-files/resources.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "apis":[ - { - "path":"/word.{format}", - "description":"" - }, - { - "path":"/words.{format}", - "description":"" - }, - { - "path":"/wordList.{format}", - "description":"" - }, - { - "path":"/wordLists.{format}", - "description":"" - }, - { - "path":"/account.{format}", - "description":"" - } - ], - "apiVersion":"4.0", - "swaggerVersion":"1.1", - "basePath":"http://api.wordnik.com/v4" -} \ No newline at end of file diff --git a/samples/client/wordnik-api/spec-files/word.json b/samples/client/wordnik-api/spec-files/word.json deleted file mode 100644 index cd1abf96aa10..000000000000 --- a/samples/client/wordnik-api/spec-files/word.json +++ /dev/null @@ -1,1356 +0,0 @@ -{ - "resourcePath":"/word", - "apis":[ - { - "path":"/word.{format}/{word}/examples", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"word", - "description":"Word to return examples for", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"includeDuplicates", - "defaultValue":"false", - "description":"Show duplicate examples from different sources", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"useCanonical", - "defaultValue":"false", - "description":"If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"skip", - "defaultValue":"0", - "description":"Results to skip", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"limit", - "defaultValue":"5", - "description":"Maximum number of results to return", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Returns examples for a word", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid word supplied.", - "code":400 - } - ], - "nickname":"getExamples", - "responseClass":"ExampleSearchResults" - } - ] - }, - { - "path":"/word.{format}/{word}", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"word", - "description":"String value of WordObject to return", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"useCanonical", - "defaultValue":"false", - "description":"If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"includeSuggestions", - "defaultValue":"true", - "description":"Return suggestions (for correct spelling, case variants, etc.)", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Given a word as a string, returns the WordObject that represents it", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid word supplied.", - "code":400 - } - ], - "nickname":"getWord", - "responseClass":"WordObject" - } - ] - }, - { - "path":"/word.{format}/{word}/definitions", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"word", - "description":"Word to return definitions for", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"limit", - "defaultValue":"200", - "description":"Maximum number of results to return", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"partOfSpeech", - "description":"CSV list of part-of-speech types", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "noun", - "adjective", - "verb", - "adverb", - "interjection", - "pronoun", - "preposition", - "abbreviation", - "affix", - "article", - "auxiliary-verb", - "conjunction", - "definite-article", - "family-name", - "given-name", - "idiom", - "imperative", - "noun-plural", - "noun-posessive", - "past-participle", - "phrasal-prefix", - "proper-noun", - "proper-noun-plural", - "proper-noun-posessive", - "suffix", - "verb-intransitive", - "verb-transitive" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"includeRelated", - "defaultValue":"false", - "description":"Return related words with definitions", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "true", - "false" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"sourceDictionaries", - "description":"Source dictionary to return definitions from. If 'all' is received, results are returned from all sources. If multiple values are received (e.g. 'century,wiktionary'), results are returned from the first specified dictionary that has definitions. If left blank, results are returned from the first dictionary that has definitions. By default, dictionaries are searched in this order: ahd, wiktionary, webster, century, wordnet", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "all", - "ahd", - "century", - "wiktionary", - "webster", - "wordnet" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":true, - "paramType":"query" - }, - { - "name":"useCanonical", - "defaultValue":"false", - "description":"If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"includeTags", - "defaultValue":"false", - "description":"Return a closed set of XML tags in response", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Return definitions for a word", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid word supplied.", - "code":400 - }, - { - "reason":"No definitions found.", - "code":404 - } - ], - "nickname":"getDefinitions", - "responseClass":"List[Definition]" - } - ] - }, - { - "path":"/word.{format}/{word}/topExample", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"word", - "description":"Word to fetch examples for", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"useCanonical", - "defaultValue":"false", - "description":"If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Returns a top example for a word", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid word supplied.", - "code":400 - } - ], - "nickname":"getTopExample", - "responseClass":"Example" - } - ] - }, - { - "path":"/word.{format}/{word}/relatedWords", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"word", - "description":"Word to fetch relationships for", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"useCanonical", - "defaultValue":"false", - "description":"If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"relationshipTypes", - "description":"Limits the total results per type of relationship type", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "synonym", - "antonym", - "variant", - "equivalent", - "cross-reference", - "related-word", - "rhyme", - "form", - "etymologically-related-term", - "hypernym", - "hyponym", - "inflected-form", - "primary", - "same-context", - "verb-form", - "verb-stem" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"limitPerRelationshipType", - "defaultValue":"10", - "description":"Restrict to the supplied relatinship types", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":"Infinity", - "min":1.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Given a word as a string, returns relationships from the Word Graph", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid word supplied.", - "code":400 - } - ], - "nickname":"getRelatedWords", - "responseClass":"List[Related]" - } - ] - }, - { - "path":"/word.{format}/{word}/pronunciations", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"word", - "description":"Word to get pronunciations for", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"useCanonical", - "defaultValue":"false", - "description":"If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"sourceDictionary", - "description":"Get from a single dictionary", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "ahd", - "century", - "cmu", - "macmillan", - "wiktionary", - "webster", - "wordnet" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"typeFormat", - "description":"Text pronunciation type", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "ahd", - "arpabet", - "gcide-diacritical", - "IPA" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"limit", - "defaultValue":"50", - "description":"Maximum number of results to return", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Returns text pronunciations for a given word", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid word supplied.", - "code":400 - } - ], - "nickname":"getTextPronunciations", - "responseClass":"List[TextPron]" - } - ] - }, - { - "path":"/word.{format}/{word}/hyphenation", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"word", - "description":"Word to get syllables for", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"useCanonical", - "defaultValue":"false", - "description":"If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", - "required":false, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"sourceDictionary", - "description":"Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet.", - "required":false, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"limit", - "defaultValue":"50", - "description":"Maximum number of results to return", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Returns syllable information for a word", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid word supplied.", - "code":400 - } - ], - "nickname":"getHyphenation", - "responseClass":"List[Syllable]" - } - ] - }, - { - "path":"/word.{format}/{word}/frequency", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"word", - "description":"Word to return", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"useCanonical", - "defaultValue":"false", - "description":"If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", - "required":false, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"startYear", - "defaultValue":"1800", - "description":"Starting Year", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"endYear", - "defaultValue":"2012", - "description":"Ending Year", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Returns word usage over time", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid word supplied.", - "code":400 - }, - { - "reason":"No results.", - "code":404 - } - ], - "nickname":"getWordFrequency", - "responseClass":"FrequencySummary" - } - ] - }, - { - "path":"/word.{format}/{word}/phrases", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"word", - "description":"Word to fetch phrases for", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"limit", - "defaultValue":"5", - "description":"Maximum number of results to return", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"wlmi", - "defaultValue":"0", - "description":"Minimum WLMI for the phrase", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"useCanonical", - "defaultValue":"false", - "description":"If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Fetches bi-gram phrases for a word", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid word supplied.", - "code":400 - } - ], - "nickname":"getPhrases", - "responseClass":"List[Bigram]" - } - ] - }, - { - "path":"/word.{format}/{word}/etymologies", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"word", - "description":"Word to return", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"useCanonical", - "description":"If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested.", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Fetches etymology data", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid word supplied.", - "code":400 - }, - { - "reason":"No definitions found.", - "code":404 - } - ], - "nickname":"getEtymologies", - "responseClass":"List[string]" - } - ] - }, - { - "path":"/word.{format}/{word}/audio", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"word", - "description":"Word to get audio for.", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"useCanonical", - "defaultValue":"false", - "description":"Use the canonical form of the word", - "required":false, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"limit", - "defaultValue":"50", - "description":"Maximum number of results to return", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Fetches audio metadata for a word.", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid word supplied.", - "code":400 - } - ], - "nickname":"getAudio", - "responseClass":"List[AudioFile]", - "notes":"The metadata includes a time-expiring fileUrl which allows reading the audio file directly from the API. Currently only audio pronunciations from the American Heritage Dictionary in mp3 format are supported." - } - ] - }, - { - "path": "/word.{format}/{word}/scrabbleScore", - "description": "", - "operations": [ - { - "parameters": [ - { - "name": "word", - "description": "Word to get scrabble score for.", - "required": true, - "dataType": "string", - "allowMultiple": false, - "paramType": "path" - } - ], - "summary": "Returns the Scrabble score for a word", - "httpMethod": "GET", - "responseTypeInternal": "com.wordnik.system.model.ScrabbleScoreResult", - "errorResponses": [ - { - "reason": "Invalid word supplied.", - "code": 400 - }, - { - "reason": "No scrabble score found.", - "code": 404 - } - ], - "nickname": "getScrabbleScore", - "responseClass": "ScrabbleScoreResult" - } - ] - } - ], - "apiVersion":"4.0", - "swaggerVersion":"1.0", - "basePath":"http://api.wordnik.com/v4", - "models":{ - "Syllable":{ - "properties":{ - "text":{ - "type":"string" - }, - "seq":{ - "type":"int" - }, - "type":{ - "type":"string" - } - }, - "id":"Syllable" - }, - "AudioType":{ - "properties":{ - "id":{ - "type":"int" - }, - "name":{ - "type":"string" - } - }, - "id":"AudioType" - }, - "Facet":{ - "properties":{ - "facetValues":{ - "type":"Array", - "items":{ - "$ref":"FacetValue" - } - }, - "name":{ - "type":"string" - } - }, - "id":"Facet" - }, - "FacetValue":{ - "properties":{ - "count":{ - "type":"long" - }, - "value":{ - "type":"string" - } - }, - "id":"FacetValue" - }, - "Note":{ - "properties":{ - "noteType":{ - "type":"string" - }, - "appliesTo":{ - "type":"Array", - "items":{ - "type":"string" - } - }, - "value":{ - "type":"string" - }, - "pos":{ - "type":"int" - } - }, - "id":"Note" - }, - "FacetValue":{ - "properties":{ - "count":{ - "type":"long" - }, - "value":{ - "type":"string" - } - }, - "id":"FacetValue" - }, - "Related":{ - "properties":{ - "label1":{ - "type":"string" - }, - "relationshipType":{ - "type":"string" - }, - "label2":{ - "type":"string" - }, - "label3":{ - "type":"string" - }, - "words":{ - "type":"Array", - "items":{ - "type":"string" - } - }, - "gram":{ - "type":"string" - }, - "label4":{ - "type":"string" - } - }, - "id":"Related" - }, - "WordObject":{ - "properties":{ - "id":{ - "type":"long", - "required":true - }, - "word":{ - "type":"string" - }, - "originalWord":{ - "type":"string" - }, - "suggestions":{ - "type":"Array", - "items":{ - "type":"string" - } - }, - "canonicalForm":{ - "type":"string" - }, - "vulgar":{ - "type":"string" - } - }, - "id":"WordObject" - }, - "ScoredWord":{ - "properties":{ - "position":{ - "type":"int" - }, - "id":{ - "type":"long" - }, - "docTermCount":{ - "type":"int" - }, - "lemma":{ - "type":"string" - }, - "wordType":{ - "type":"string" - }, - "score":{ - "type":"float" - }, - "sentenceId":{ - "type":"long" - }, - "word":{ - "type":"string" - }, - "stopword":{ - "type":"boolean" - }, - "baseWordScore":{ - "type":"double" - }, - "partOfSpeech":{ - "type":"string" - } - }, - "id":"ScoredWord" - }, - "Citation":{ - "properties":{ - "cite":{ - "type":"string" - }, - "source":{ - "type":"string" - } - }, - "id":"Citation" - }, - "ExampleSearchResults":{ - "properties":{ - "facets":{ - "type":"Array", - "items":{ - "$ref":"Facet" - } - }, - "examples":{ - "type":"Array", - "items":{ - "$ref":"Example" - } - } - }, - "id":"ExampleSearchResults" - }, - "Example":{ - "properties":{ - "id":{ - "type":"long" - }, - "exampleId":{ - "type":"long" - }, - "title":{ - "type":"string" - }, - "text":{ - "type":"string" - }, - "score":{ - "type":"ScoredWord" - }, - "sentence":{ - "type":"Sentence" - }, - "word":{ - "type":"string" - }, - "provider":{ - "type":"ContentProvider" - }, - "year":{ - "type":"int" - }, - "rating":{ - "type":"float" - }, - "documentId":{ - "type":"long" - }, - "url":{ - "type":"string" - } - }, - "id":"Example" - }, - "Sentence":{ - "properties":{ - "hasScoredWords":{ - "type":"boolean" - }, - "id":{ - "type":"long" - }, - "scoredWords":{ - "type":"Array", - "items":{ - "$ref":"ScoredWord" - } - }, - "display":{ - "type":"string" - }, - "rating":{ - "type":"int" - }, - "documentMetadataId":{ - "type":"long" - } - }, - "id":"Sentence" - }, - "ExampleUsage":{ - "properties":{ - "text":{ - "type":"string" - } - }, - "id":"ExampleUsage" - }, - "ContentProvider":{ - "properties":{ - "id":{ - "type":"int" - }, - "name":{ - "type":"string" - } - }, - "id":"ContentProvider" - }, - "AudioFile":{ - "properties":{ - "attributionUrl":{ - "type":"string" - }, - "commentCount":{ - "type":"int" - }, - "voteCount":{ - "type":"int" - }, - "fileUrl":{ - "type":"string" - }, - "audioType":{ - "type":"string" - }, - "id":{ - "type":"long", - "required":true - }, - "duration":{ - "type":"double" - }, - "attributionText":{ - "type":"string" - }, - "createdBy":{ - "type":"string" - }, - "description":{ - "type":"string" - }, - "createdAt":{ - "type":"Date" - }, - "voteWeightedAverage":{ - "type":"float" - }, - "voteAverage":{ - "type":"float" - }, - "word":{ - "type":"string" - } - }, - "id":"AudioFile" - }, - "Bigram":{ - "properties":{ - "count":{ - "type":"long" - }, - "gram2":{ - "type":"string" - }, - "gram1":{ - "type":"string" - }, - "wlmi":{ - "type":"double" - }, - "mi":{ - "type":"double" - } - }, - "id":"Bigram" - }, - "Label":{ - "properties":{ - "text":{ - "type":"string" - }, - "type":{ - "type":"string" - } - }, - "id":"Label" - }, - "Frequency":{ - "properties":{ - "count":{ - "type":"long" - }, - "year":{ - "type":"int" - } - }, - "id":"Frequency" - }, - "FrequencySummary":{ - "properties":{ - "unknownYearCount":{ - "type":"int" - }, - "totalCount":{ - "type":"long" - }, - "frequencyString":{ - "type":"string" - }, - "word":{ - "type":"string" - }, - "frequency":{ - "type":"Array", - "items":{ - "$ref":"Frequency" - } - } - }, - "id":"FrequencySummary" - }, - "Definition":{ - "properties":{ - "extendedText":{ - "type":"string" - }, - "text":{ - "type":"string" - }, - "sourceDictionary":{ - "type":"string" - }, - "citations":{ - "type":"Array", - "items":{ - "$ref":"Citation" - } - }, - "labels":{ - "type":"Array", - "items":{ - "$ref":"Label" - } - }, - "score":{ - "type":"float" - }, - "exampleUses":{ - "type":"Array", - "items":{ - "$ref":"ExampleUsage" - } - }, - "attributionUrl":{ - "type":"string" - }, - "seqString":{ - "type":"string" - }, - "attributionText":{ - "type":"string" - }, - "relatedWords":{ - "type":"Array", - "items":{ - "$ref":"Related" - } - }, - "sequence":{ - "type":"string" - }, - "word":{ - "type":"string" - }, - "notes":{ - "type":"Array", - "items":{ - "$ref":"Note" - } - }, - "textProns":{ - "type":"Array", - "items":{ - "$ref":"TextPron" - } - }, - "partOfSpeech":{ - "type":"string" - } - }, - "id":"Definition" - }, - "PartOfSpeech":{ - "properties":{ - "roots":{ - "type":"Array", - "items":{ - "$ref":"root" - } - }, - "storageAbbr":{ - "type":"Array", - "items":{ - "type":"string" - } - }, - "allCategories":{ - "type":"Array", - "items":{ - "$ref":"category" - } - } - }, - "id":"PartOfSpeech" - }, - "TextPron":{ - "properties":{ - "raw":{ - "type":"string" - }, - "seq":{ - "type":"int" - }, - "rawType":{ - "type":"string" - } - }, - "id":"TextPron" - }, - "ScrabbleScoreResult":{ - "properties":{ - "value":{ - "type":"int" - } - }, - "id":"ScrabbleScoreResult" - } - - } -} diff --git a/samples/client/wordnik-api/spec-files/wordList.json b/samples/client/wordnik-api/spec-files/wordList.json deleted file mode 100644 index d20202d85361..000000000000 --- a/samples/client/wordnik-api/spec-files/wordList.json +++ /dev/null @@ -1,406 +0,0 @@ -{ - "resourcePath":"/wordList", - "apis":[ - { - "path":"/wordList.{format}/{permalink}", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"permalink", - "description":"permalink of WordList to update", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "description":"Updated WordList", - "required":false, - "dataType":"WordList", - "valueTypeInternal":"com.wordnik.community.entity.WordList", - "allowMultiple":false, - "paramType":"body" - }, - { - "name":"auth_token", - "description":"The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above)", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"header" - } - ], - "summary":"Updates an existing WordList", - "httpMethod":"PUT", - "errorResponses":[ - { - "reason":"Invalid ID supplied", - "code":400 - }, - { - "reason":"Not Authorized to update WordList", - "code":403 - }, - { - "reason":"WordList not found", - "code":404 - } - ], - "nickname":"updateWordList", - "responseClass":"void" - }, - { - "parameters":[ - { - "name":"permalink", - "description":"ID of WordList to delete", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"auth_token", - "description":"The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above)", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"header" - } - ], - "summary":"Deletes an existing WordList", - "httpMethod":"DELETE", - "errorResponses":[ - { - "reason":"Invalid ID supplied", - "code":400 - }, - { - "reason":"Not Authorized to delete WordList", - "code":403 - }, - { - "reason":"WordList not found", - "code":404 - } - ], - "nickname":"deleteWordList", - "responseClass":"void" - }, - { - "parameters":[ - { - "name":"permalink", - "description":"permalink of WordList to fetch", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"auth_token", - "description":"The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above)", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"header" - } - ], - "summary":"Fetches a WordList by ID", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid ID supplied", - "code":400 - }, - { - "reason":"Not Authorized to access WordList", - "code":403 - }, - { - "reason":"WordList not found", - "code":404 - } - ], - "nickname":"getWordListByPermalink", - "responseClass":"WordList" - } - ] - }, - { - "path":"/wordList.{format}/{permalink}/words", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"permalink", - "description":"permalink of WordList to user", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "description":"Array of words to add to WordList", - "required":false, - "dataType":"Array[StringValue]", - "valueTypeInternal":"com.wordnik.resource.StringValue", - "allowMultiple":false, - "paramType":"body" - }, - { - "name":"auth_token", - "description":"The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above)", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"header" - } - ], - "summary":"Adds words to a WordList", - "httpMethod":"POST", - "errorResponses":[ - { - "reason":"Invalid permalink supplied", - "code":400 - }, - { - "reason":"Not Authorized to access WordList", - "code":403 - }, - { - "reason":"WordList not found", - "code":404 - } - ], - "nickname":"addWordsToWordList", - "responseClass":"void" - }, - { - "parameters":[ - { - "name":"permalink", - "description":"ID of WordList to use", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"sortBy", - "defaultValue":"createDate", - "description":"Field to sort by", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "createDate", - "alpha" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"sortOrder", - "defaultValue":"desc", - "description":"Direction to sort", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "asc", - "desc" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"skip", - "defaultValue":"0", - "description":"Results to skip", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"limit", - "defaultValue":"100", - "description":"Maximum number of results to return", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"auth_token", - "description":"The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above)", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"header" - } - ], - "summary":"Fetches words in a WordList", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid ID supplied", - "code":400 - }, - { - "reason":"Not Authorized to access WordList", - "code":403 - }, - { - "reason":"WordList not found", - "code":404 - } - ], - "nickname":"getWordListWords", - "responseClass":"List[WordListWord]" - } - ] - }, - { - "path":"/wordList.{format}/{permalink}/deleteWords", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"permalink", - "description":"permalink of WordList to use", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "description":"Words to remove from WordList", - "required":false, - "dataType":"Array[StringValue]", - "valueTypeInternal":"com.wordnik.resource.StringValue", - "allowMultiple":false, - "paramType":"body" - }, - { - "name":"auth_token", - "description":"The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above)", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"header" - } - ], - "summary":"Removes words from a WordList", - "httpMethod":"POST", - "errorResponses":[ - { - "reason":"Invalid permalink supplied", - "code":400 - }, - { - "reason":"Not Authorized to modify WordList", - "code":403 - }, - { - "reason":"WordList not found", - "code":404 - } - ], - "nickname":"deleteWordsFromWordList", - "responseClass":"void" - } - ] - } - ], - "apiVersion":"4.0", - "swaggerVersion":"1.0", - "basePath":"http://api.wordnik.com/v4", - "models":{ - "WordList":{ - "properties":{ - "id":{ - "type":"long", - "required":false - }, - "permalink":{ - "type":"string" - }, - "name":{ - "type":"string" - }, - "createdAt":{ - "type":"Date" - }, - "updatedAt":{ - "type":"Date" - }, - "lastActivityAt":{ - "type":"Date" - }, - "username":{ - "type":"string" - }, - "userId":{ - "type":"long" - }, - "description":{ - "type":"string" - }, - "numberWordsInList":{ - "type":"long" - }, - "type":{ - "type":"string" - } - }, - "id":"WordList" - }, - "WordListWord":{ - "properties":{ - "id":{ - "type":"long", - "required":true - }, - "word":{ - "type":"string" - }, - "username":{ - "type":"string" - }, - "userId":{ - "type":"long" - }, - "createdAt":{ - "type":"Date" - }, - "numberCommentsOnWord":{ - "type":"long" - }, - "numberLists":{ - "type":"long" - } - }, - "id":"WordListWord" - }, - "StringValue":{ - "properties":{ - "word":{ - "type":"string" - } - }, - "id":"StringValue" - } - } -} \ No newline at end of file diff --git a/samples/client/wordnik-api/spec-files/wordLists.json b/samples/client/wordnik-api/spec-files/wordLists.json deleted file mode 100644 index b1c61358d83e..000000000000 --- a/samples/client/wordnik-api/spec-files/wordLists.json +++ /dev/null @@ -1,120 +0,0 @@ -{ - "resourcePath":"/wordLists", - "apis":[ - { - "path":"/wordLists.{format}", - "description":"", - "operations":[ - { - "parameters":[ - { - "description":"WordList to create", - "required":false, - "dataType":"WordList", - "valueTypeInternal":"com.wordnik.community.entity.WordList", - "allowMultiple":false, - "paramType":"body" - }, - { - "name":"auth_token", - "description":"The auth token of the logged-in user, obtained by calling /account.{format}/authenticate/{username} (described above)", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"header" - } - ], - "summary":"Creates a WordList.", - "httpMethod":"POST", - "errorResponses":[ - { - "reason":"Invalid WordList supplied or mandatory fields are missing", - "code":400 - }, - { - "reason":"Not authenticated", - "code":403 - }, - { - "reason":"WordList owner not found", - "code":404 - } - ], - "nickname":"createWordList", - "responseClass":"WordList" - } - ] - } - ], - "apiVersion":"4.0", - "swaggerVersion":"1.0", - "basePath":"http://api.wordnik.com/v4", - "models":{ - "WordList":{ - "properties":{ - "id":{ - "type":"long", - "required":false - }, - "permalink":{ - "type":"string" - }, - "name":{ - "type":"string" - }, - "createdAt":{ - "type":"Date" - }, - "updatedAt":{ - "type":"Date" - }, - "lastActivityAt":{ - "type":"Date" - }, - "username":{ - "type":"string" - }, - "userId":{ - "type":"long" - }, - "description":{ - "type":"string" - }, - "numberWordsInList":{ - "type":"long" - }, - "type":{ - "type":"string" - } - }, - "id":"WordList" - }, - "WordListWord":{ - "properties":{ - "id":{ - "type":"long", - "required":true - }, - "word":{ - "type":"string" - }, - "username":{ - "type":"string" - }, - "userId":{ - "type":"long" - }, - "createdAt":{ - "type":"Date" - }, - "numberCommentsOnWord":{ - "type":"long" - }, - "numberLists":{ - "type":"long" - } - }, - "id":"WordListWord" - } - } -} \ No newline at end of file diff --git a/samples/client/wordnik-api/spec-files/words.json b/samples/client/wordnik-api/spec-files/words.json deleted file mode 100644 index 471e07cf4a45..000000000000 --- a/samples/client/wordnik-api/spec-files/words.json +++ /dev/null @@ -1,1262 +0,0 @@ -{ - "resourcePath":"/words", - "apis":[ - { - "path":"/words.{format}/search/{query}", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"query", - "description":"Search query", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"path" - }, - { - "name":"caseSensitive", - "defaultValue":"true", - "description":"Search case sensitive", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "true", - "false" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"includePartOfSpeech", - "description":"Only include these comma-delimited parts of speech", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "noun", - "adjective", - "verb", - "adverb", - "interjection", - "pronoun", - "preposition", - "abbreviation", - "affix", - "article", - "auxiliary-verb", - "conjunction", - "definite-article", - "family-name", - "given-name", - "idiom", - "imperative", - "noun-plural", - "noun-posessive", - "past-participle", - "phrasal-prefix", - "proper-noun", - "proper-noun-plural", - "proper-noun-posessive", - "suffix", - "verb-intransitive", - "verb-transitive" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"excludePartOfSpeech", - "description":"Exclude these comma-delimited parts of speech", - "required":false, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"minCorpusCount", - "defaultValue":"5", - "description":"Minimum corpus frequency for terms", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":"Infinity", - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"maxCorpusCount", - "defaultValue":"-1", - "description":"Maximum corpus frequency for terms", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":"Infinity", - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"minDictionaryCount", - "defaultValue":"1", - "description":"Minimum number of dictionary entries for words returned", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":"Infinity", - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"maxDictionaryCount", - "defaultValue":"-1", - "description":"Maximum dictionary definition count", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":"Infinity", - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"minLength", - "defaultValue":"1", - "description":"Minimum word length", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":1024.0, - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"maxLength", - "defaultValue":"-1", - "description":"Maximum word length", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":1024.0, - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"skip", - "defaultValue":"0", - "description":"Results to skip", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":1000.0, - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"limit", - "defaultValue":"10", - "description":"Maximum number of results to return", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":1000.0, - "min":1.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Searches words", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid query supplied.", - "code":400 - } - ], - "nickname":"searchWords", - "responseClass":"WordSearchResults" - } - ] - }, - { - "path":"/words.{format}/wordOfTheDay", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"date", - "description":"Fetches by date in yyyy-MM-dd", - "required":false, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Returns a specific WordOfTheDay", - "httpMethod":"GET", - "nickname":"getWordOfTheDay", - "responseClass":"WordOfTheDay" - } - ] - }, - { - "path":"/words.{format}/reverseDictionary", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"query", - "description":"Search term", - "required":true, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"findSenseForWord", - "description":"Restricts words and finds closest sense", - "required":false, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"includeSourceDictionaries", - "description":"Only include these comma-delimited source dictionaries", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "ahd", - " century", - " wiktionary", - " webster", - " wordnet" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"excludeSourceDictionaries", - "description":"Exclude these comma-delimited source dictionaries", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "ahd", - " century", - " wiktionary", - " webster", - " wordnet" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"includePartOfSpeech", - "description":"Only include these comma-delimited parts of speech", - "required":false, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"excludePartOfSpeech", - "description":"Exclude these comma-delimited parts of speech", - "required":false, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"minCorpusCount", - "defaultValue":"5", - "description":"Minimum corpus frequency for terms", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":"Infinity", - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"maxCorpusCount", - "defaultValue":"-1", - "description":"Maximum corpus frequency for terms", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":"Infinity", - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"minLength", - "defaultValue":"1", - "description":"Minimum word length", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":1024.0, - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"maxLength", - "defaultValue":"-1", - "description":"Maximum word length", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":1024.0, - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"expandTerms", - "description":"Expand terms", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "synonym", - "hypernym" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"includeTags", - "defaultValue":"false", - "description":"Return a closed set of XML tags in response", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"sortBy", - "description":"Attribute to sort by", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "alpha", - "count", - "length" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"sortOrder", - "description":"Sort direction", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "asc", - "desc" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"skip", - "defaultValue":"0", - "description":"Results to skip", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":1000.0, - "min":0.0, - "valueType":"RANGE" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"limit", - "defaultValue":"10", - "description":"Maximum number of results to return", - "required":false, - "allowableValues":{ - "valueType":"RANGE", - "max":1000.0, - "min":1.0, - "valueType":"RANGE" - }, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Reverse dictionary search", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid term supplied.", - "code":400 - } - ], - "nickname":"reverseDictionary", - "responseClass":"DefinitionSearchResults" - } - ] - }, - { - "path":"/words.{format}/randomWords", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"hasDictionaryDef", - "defaultValue":"true", - "description":"Only return words with dictionary definitions", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"includePartOfSpeech", - "description":"CSV part-of-speech values to include", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "noun", - "adjective", - "verb", - "adverb", - "interjection", - "pronoun", - "preposition", - "abbreviation", - "affix", - "article", - "auxiliary-verb", - "conjunction", - "definite-article", - "family-name", - "given-name", - "idiom", - "imperative", - "noun-plural", - "noun-posessive", - "past-participle", - "phrasal-prefix", - "proper-noun", - "proper-noun-plural", - "proper-noun-posessive", - "suffix", - "verb-intransitive", - "verb-transitive" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"excludePartOfSpeech", - "description":"CSV part-of-speech values to exclude", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "noun", - "adjective", - "verb", - "adverb", - "interjection", - "pronoun", - "preposition", - "abbreviation", - "affix", - "article", - "auxiliary-verb", - "conjunction", - "definite-article", - "family-name", - "given-name", - "idiom", - "imperative", - "noun-plural", - "noun-posessive", - "past-participle", - "phrasal-prefix", - "proper-noun", - "proper-noun-plural", - "proper-noun-posessive", - "suffix", - "verb-intransitive", - "verb-transitive" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"minCorpusCount", - "defaultValue":"0", - "description":"Minimum corpus frequency for terms", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"maxCorpusCount", - "defaultValue":"-1", - "description":"Maximum corpus frequency for terms", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"minDictionaryCount", - "defaultValue":"1", - "description":"Minimum dictionary count", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"maxDictionaryCount", - "defaultValue":"-1", - "description":"Maximum dictionary count", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"minLength", - "defaultValue":"5", - "description":"Minimum word length", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"maxLength", - "defaultValue":"-1", - "description":"Maximum word length", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"sortBy", - "description":"Attribute to sort by", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "alpha", - "count" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"sortOrder", - "description":"Sort direction", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "asc", - "desc" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"limit", - "defaultValue":"10", - "description":"Maximum number of results to return", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Returns an array of random WordObjects", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"Invalid term supplied.", - "code":400 - }, - { - "reason":"No results.", - "code":404 - } - ], - "nickname":"getRandomWords", - "responseClass":"List[WordObject]" - } - ] - }, - { - "path":"/words.{format}/randomWord", - "description":"", - "operations":[ - { - "parameters":[ - { - "name":"hasDictionaryDef", - "defaultValue":"true", - "description":"Only return words with dictionary definitions", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "false", - "true" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"includePartOfSpeech", - "description":"CSV part-of-speech values to include", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "noun", - "adjective", - "verb", - "adverb", - "interjection", - "pronoun", - "preposition", - "abbreviation", - "affix", - "article", - "auxiliary-verb", - "conjunction", - "definite-article", - "family-name", - "given-name", - "idiom", - "imperative", - "noun-plural", - "noun-posessive", - "past-participle", - "phrasal-prefix", - "proper-noun", - "proper-noun-plural", - "proper-noun-posessive", - "suffix", - "verb-intransitive", - "verb-transitive" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"excludePartOfSpeech", - "description":"CSV part-of-speech values to exclude", - "required":false, - "allowableValues":{ - "valueType":"LIST", - "values":[ - "noun", - "adjective", - "verb", - "adverb", - "interjection", - "pronoun", - "preposition", - "abbreviation", - "affix", - "article", - "auxiliary-verb", - "conjunction", - "definite-article", - "family-name", - "given-name", - "idiom", - "imperative", - "noun-plural", - "noun-posessive", - "past-participle", - "phrasal-prefix", - "proper-noun", - "proper-noun-plural", - "proper-noun-posessive", - "suffix", - "verb-intransitive", - "verb-transitive" - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"minCorpusCount", - "defaultValue":"0", - "description":"Minimum corpus frequency for terms", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"maxCorpusCount", - "defaultValue":"-1", - "description":"Maximum corpus frequency for terms", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"minDictionaryCount", - "defaultValue":"1", - "description":"Minimum dictionary count", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"maxDictionaryCount", - "defaultValue":"-1", - "description":"Maximum dictionary count", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"minLength", - "defaultValue":"5", - "description":"Minimum word length", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - }, - { - "name":"maxLength", - "defaultValue":"-1", - "description":"Maximum word length", - "required":false, - "dataType":"int", - "allowMultiple":false, - "paramType":"query" - } - ], - "summary":"Returns a single random WordObject", - "httpMethod":"GET", - "errorResponses":[ - { - "reason":"No word found.", - "code":404 - } - ], - "nickname":"getRandomWord", - "responseClass":"WordObject" - } - ] - } - ], - "apiVersion":"4.0", - "swaggerVersion":"1.0", - "basePath":"http://api.wordnik.com/v4", - "models":{ - "WordSearchResult":{ - "properties":{ - "count":{ - "type":"long" - }, - "lexicality":{ - "type":"double" - }, - "word":{ - "type":"string" - } - }, - "id":"WordSearchResult" - }, - "WordOfTheDay":{ - "properties":{ - "id":{ - "type":"long", - "required":true - }, - "parentId":{ - "type":"string" - }, - "category":{ - "type":"string" - }, - "createdBy":{ - "type":"string" - }, - "createdAt":{ - "type":"Date" - }, - "contentProvider":{ - "type":"ContentProvider" - }, - "htmlExtra":{ - "type":"string" - }, - "word":{ - "type":"string" - }, - "definitions":{ - "type":"Array", - "items":{ - "$ref":"SimpleDefinition" - } - }, - "examples":{ - "type":"Array", - "items":{ - "$ref":"SimpleExample" - } - }, - "note":{ - "type":"string" - }, - "publishDate":{ - "type":"Date" - } - }, - "id":"WordOfTheDay" - }, - "Note":{ - "properties":{ - "noteType":{ - "type":"string" - }, - "appliesTo":{ - "type":"Array", - "items":{ - "type":"string" - } - }, - "value":{ - "type":"string" - }, - "pos":{ - "type":"int" - } - }, - "id":"Note" - }, - "DefinitionSearchResults":{ - "properties":{ - "results":{ - "type":"Array", - "items":{ - "$ref":"Definition" - } - }, - "totalResults":{ - "type":"int" - } - }, - "id":"DefinitionSearchResults" - }, - "WordObject":{ - "properties":{ - "id":{ - "type":"long", - "required":true - }, - "word":{ - "type":"string" - }, - "originalWord":{ - "type":"string" - }, - "suggestions":{ - "type":"Array", - "items":{ - "type":"string" - } - }, - "canonicalForm":{ - "type":"string" - }, - "vulgar":{ - "type":"string" - } - }, - "id":"WordObject" - }, - "Related":{ - "properties":{ - "label1":{ - "type":"string" - }, - "relationshipType":{ - "type":"string" - }, - "label2":{ - "type":"string" - }, - "label3":{ - "type":"string" - }, - "words":{ - "type":"Array", - "items":{ - "type":"string" - } - }, - "gram":{ - "type":"string" - }, - "label4":{ - "type":"string" - } - }, - "id":"Related" - }, - "Citation":{ - "properties":{ - "cite":{ - "type":"string" - }, - "source":{ - "type":"string" - } - }, - "id":"Citation" - }, - "WordSearchResults":{ - "properties":{ - "searchResults":{ - "type":"Array", - "items":{ - "$ref":"WordSearchResult" - } - }, - "totalResults":{ - "type":"int" - } - }, - "id":"WordSearchResults" - }, - "Category":{ - "properties":{ - "id":{ - "type":"long", - "required":true - }, - "name":{ - "type":"string" - } - }, - "id":"Category" - }, - "SimpleDefinition":{ - "properties":{ - "text":{ - "type":"string" - }, - "source":{ - "type":"string" - }, - "note":{ - "type":"string" - }, - "partOfSpeech":{ - "type":"string" - } - }, - "id":"SimpleDefinition" - }, - "Root":{ - "properties":{ - "id":{ - "type":"long", - "required":true - }, - "name":{ - "type":"string" - }, - "categories":{ - "type":"Array", - "items":{ - "$ref":"Category" - } - } - }, - "id":"Root" - }, - "ExampleUsage":{ - "properties":{ - "text":{ - "type":"string" - } - }, - "id":"ExampleUsage" - }, - "ContentProvider":{ - "properties":{ - "id":{ - "type":"int" - }, - "name":{ - "type":"string" - } - }, - "id":"ContentProvider" - }, - "Label":{ - "properties":{ - "text":{ - "type":"string" - }, - "type":{ - "type":"string" - } - }, - "id":"Label" - }, - "SimpleExample":{ - "properties":{ - "id":{ - "type":"long" - }, - "title":{ - "type":"string" - }, - "text":{ - "type":"string" - }, - "url":{ - "type":"string" - } - }, - "id":"SimpleExample" - }, - "Definition":{ - "properties":{ - "extendedText":{ - "type":"string" - }, - "text":{ - "type":"string" - }, - "sourceDictionary":{ - "type":"string" - }, - "citations":{ - "type":"Array", - "items":{ - "$ref":"Citation" - } - }, - "labels":{ - "type":"Array", - "items":{ - "$ref":"Label" - } - }, - "score":{ - "type":"float" - }, - "exampleUses":{ - "type":"Array", - "items":{ - "$ref":"ExampleUsage" - } - }, - "attributionUrl":{ - "type":"string" - }, - "seqString":{ - "type":"string" - }, - "attributionText":{ - "type":"string" - }, - "relatedWords":{ - "type":"Array", - "items":{ - "$ref":"Related" - } - }, - "sequence":{ - "type":"string" - }, - "word":{ - "type":"string" - }, - "notes":{ - "type":"Array", - "items":{ - "$ref":"Note" - } - }, - "textProns":{ - "type":"Array", - "items":{ - "$ref":"TextPron" - } - }, - "partOfSpeech":{ - "type":"string" - } - }, - "id":"Definition" - }, - "PartOfSpeech":{ - "properties":{ - "roots":{ - "type":"Array", - "items":{ - "$ref":"Root" - } - }, - "storageAbbr":{ - "type":"Array", - "items":{ - "type":"string" - } - }, - "allCategories":{ - "type":"Array", - "items":{ - "$ref":"Category" - } - } - }, - "id":"PartOfSpeech" - }, - "TextPron":{ - "properties":{ - "raw":{ - "type":"string" - }, - "seq":{ - "type":"int" - }, - "rawType":{ - "type":"string" - } - }, - "id":"TextPron" - } - } -} \ No newline at end of file diff --git a/samples/client/wordnik-api/android/pom.xml b/samples/client/wordnik/android-java/pom.xml similarity index 69% rename from samples/client/wordnik-api/android/pom.xml rename to samples/client/wordnik/android-java/pom.xml index 03fdf69754e8..ef2be59b188b 100644 --- a/samples/client/wordnik-api/android/pom.xml +++ b/samples/client/wordnik/android-java/pom.xml @@ -1,11 +1,11 @@ 4.0.0 - com.wordnik - wordnik-android-client + io.swagger + swagger-client jar - wordnik-android-client - 4.0 + swagger-client + 1.0.0 scm:git:git@github.com:wordnik/swagger-mustache.git scm:git:git@github.com:wordnik/swagger-codegen.git @@ -104,56 +104,14 @@ 1.6 - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - - - - compile - testCompile - - - - - - incremental - - - -Xmx384m - - - -target:jvm-1.5 - -deprecation - - - - run-scalatest - org.scalatest.tools.Runner - - -p - ${project.build.testOutputDirectory} - - - -Xmx512m - - - - - - - - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - - - + + com.wordnik + swagger-annotations + ${swagger-annotations-version} + com.fasterxml.jackson.core jackson-core @@ -180,18 +138,6 @@ - - org.scala-lang - scala-library - ${scala-version} - test - - - org.scalatest - scalatest_2.9.1 - ${scala-test-version} - test - junit junit @@ -199,16 +145,18 @@ test - + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + + 1.5.1-M1 2.1.4 - 2.9.1-1 4.8.1 1.0.0 4.8.1 - 1.6.1 4.0 - 3.1.5 - diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/common/ApiException.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/ApiException.java similarity index 92% rename from samples/client/wordnik-api/java/src/main/java/com/wordnik/client/common/ApiException.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/ApiException.java index 8c96d599bb4f..31bc8a0978ad 100644 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/common/ApiException.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/ApiException.java @@ -1,4 +1,4 @@ -package com.wordnik.client.common; +package io.swagger.client; public class ApiException extends Exception { int code = 0; @@ -26,4 +26,4 @@ public class ApiException extends Exception { public void setMessage(String message) { this.message = message; } -} +} \ No newline at end of file diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiInvoker.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/ApiInvoker.java similarity index 84% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiInvoker.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/ApiInvoker.java index 2d167c3a663a..6306e0734a96 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiInvoker.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -1,4 +1,4 @@ -package com.wordnik.client; +package io.swagger.client; import com.fasterxml.jackson.core.JsonGenerator.Feature; @@ -12,9 +12,7 @@ import org.apache.http.client.methods.*; import org.apache.http.conn.*; import org.apache.http.conn.scheme.*; import org.apache.http.conn.ssl.*; -import org.apache.http.entity.mime.*; import org.apache.http.entity.StringEntity; -import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.impl.client.*; import org.apache.http.impl.conn.*; import org.apache.http.params.*; @@ -158,23 +156,10 @@ public class ApiInvoker { } else if ("POST".equals(method)) { HttpPost post = new HttpPost(url); - if (body != null) { - if("application/x-www-form-urlencoded".equals(contentType)) { - post.setHeader("Content-Type", contentType); - post.setEntity(new UrlEncodedFormEntity((List)body)); - } - else if("multipart/form-data".equals(contentType)) { - String boundary = "-------------" + System.currentTimeMillis(); - post.setHeader("Content-type", "multipart/form-data; boundary="+boundary); - MultipartEntityBuilder builder = (MultipartEntityBuilder)body; - builder.setBoundary(boundary); - post.setEntity(builder.build()); - } - else { - post.setHeader("Content-Type", contentType); - post.setEntity(new StringEntity(serialize(body), "UTF-8")); - } + if (body != null) { + post.setHeader("Content-Type", contentType); + post.setEntity(new StringEntity(serialize(body), "UTF-8")); } for(String key : headers.keySet()) { post.setHeader(key, headers.get(key)); @@ -184,21 +169,8 @@ public class ApiInvoker { else if ("PUT".equals(method)) { HttpPut put = new HttpPut(url); if(body != null) { - if("application/x-www-form-urlencoded".equals(contentType)) { - put.setHeader("Content-Type", contentType); - put.setEntity(new UrlEncodedFormEntity((List)body)); - } - else if("multipart/form-data".equals(contentType)) { - String boundary = "-------------" + System.currentTimeMillis(); - put.setHeader("Content-type", "multipart/form-data; boundary="+boundary); - MultipartEntityBuilder builder = (MultipartEntityBuilder)body; - builder.setBoundary(boundary); - put.setEntity(builder.build()); - } - else { - put.setHeader("Content-Type", contentType); - put.setEntity(new StringEntity(serialize(body), "UTF-8")); - } + put.setHeader("Content-Type", contentType); + put.setEntity(new StringEntity(serialize(body), "UTF-8")); } for(String key : headers.keySet()) { put.setHeader(key, headers.get(key)); @@ -309,4 +281,3 @@ public class ApiInvoker { } } } - diff --git a/samples/client/wordnik/android-java/src/main/java/io/swagger/client/HttpPatch.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/HttpPatch.java new file mode 100644 index 000000000000..cb97056dbc94 --- /dev/null +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/HttpPatch.java @@ -0,0 +1,16 @@ +package io.swagger.client; + +import org.apache.http.client.methods.*; + +public class HttpPatch extends HttpPost { + public static final String METHOD_PATCH = "PATCH"; + + public HttpPatch(final String url) { + super(url); + } + + @Override + public String getMethod() { + return METHOD_PATCH; + } +} \ No newline at end of file diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/JsonUtil.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/JsonUtil.java similarity index 93% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/JsonUtil.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/JsonUtil.java index 3a3ceb7b3266..90b99b48ec88 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/JsonUtil.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/JsonUtil.java @@ -1,4 +1,4 @@ -package com.wordnik.client.common; +package io.swagger.client; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; @@ -18,4 +18,3 @@ public class JsonUtil { return mapper; } } - diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/AccountApi.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/AccountApi.java similarity index 61% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/AccountApi.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/AccountApi.java index 5b334fa1e4fa..e50be9645a65 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/AccountApi.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/AccountApi.java @@ -1,15 +1,23 @@ -package com.wordnik.client.api; +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; + +import io.swagger.client.model.*; -import com.wordnik.client.common.ApiException; -import com.wordnik.client.common.ApiInvoker; -import com.wordnik.client.model.User; -import com.wordnik.client.model.WordList; -import com.wordnik.client.model.ApiTokenStatus; -import com.wordnik.client.model.AuthenticationToken; import java.util.*; +import io.swagger.client.model.ApiTokenStatus; +import io.swagger.client.model.AuthenticationToken; +import io.swagger.client.model.User; +import io.swagger.client.model.WordList; + +import java.util.Map; +import java.util.HashMap; +import java.io.File; + public class AccountApi { - String basePath = "http://api.wordnik.com/v4"; + String basePath = "https://api.wordnik.com/v4"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public void addHeader(String key, String value) { @@ -28,13 +36,53 @@ public class AccountApi { return basePath; } - public AuthenticationToken authenticate (String username, String password) throws ApiException { - // verify required params are set - if(username == null || password == null ) { - throw new ApiException(400, "missing required params"); - } + + + public ApiTokenStatus getApiTokenStatus (String api_key) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/account.{format}/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + String path = "/account.json/apiTokenStatus".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + headerParams.put("api_key", api_key); + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (ApiTokenStatus) ApiInvoker.deserialize(response, "", ApiTokenStatus.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public AuthenticationToken authenticate (String username, String password) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/account.json/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params Map queryParams = new HashMap(); @@ -42,10 +90,14 @@ public class AccountApi { if(!"null".equals(String.valueOf(password))) queryParams.put("password", String.valueOf(password)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ return (AuthenticationToken) ApiInvoker.deserialize(response, "", AuthenticationToken.class); } @@ -54,29 +106,35 @@ public class AccountApi { } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - public AuthenticationToken authenticatePost (String username, String body) throws ApiException { - // verify required params are set - if(username == null || body == null ) { - throw new ApiException(400, "missing required params"); - } + + + public AuthenticationToken authenticatePost (String username, String body) throws ApiException { + Object postBody = body; + + + // create path and map variables - String path = "/account.{format}/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + String path = "/account.json/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); if(response != null){ return (AuthenticationToken) ApiInvoker.deserialize(response, "", AuthenticationToken.class); } @@ -85,20 +143,60 @@ public class AccountApi { } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - public List getWordListsForLoggedInUser (String auth_token, Integer skip, Integer limit) throws ApiException { - // verify required params are set - if(auth_token == null ) { - throw new ApiException(400, "missing required params"); - } + + + public User getLoggedInUser (String auth_token) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/account.{format}/wordLists".replaceAll("\\{format\\}","json"); + String path = "/account.json/user".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + headerParams.put("auth_token", auth_token); + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (User) ApiInvoker.deserialize(response, "", User.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public List getWordListsForLoggedInUser (String auth_token, Integer skip, Integer limit) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/account.json/wordLists".replaceAll("\\{format\\}","json"); // query params Map queryParams = new HashMap(); @@ -108,85 +206,29 @@ public class AccountApi { queryParams.put("skip", String.valueOf(skip)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); - headerParams.put("auth_token", auth_token); - String contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); - if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", WordList.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - public ApiTokenStatus getApiTokenStatus (String api_key) throws ApiException { - // create path and map variables - String path = "/account.{format}/apiTokenStatus".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - headerParams.put("api_key", api_key); - String contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); - if(response != null){ - return (ApiTokenStatus) ApiInvoker.deserialize(response, "", ApiTokenStatus.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - public User getLoggedInUser (String auth_token) throws ApiException { - // verify required params are set - if(auth_token == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/account.{format}/user".replaceAll("\\{format\\}","json"); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); + headerParams.put("auth_token", auth_token); + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (User) ApiInvoker.deserialize(response, "", User.class); + return (List) ApiInvoker.deserialize(response, "array", WordList.class); } else { return null; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - } - + +} diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordApi.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordApi.java similarity index 59% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordApi.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordApi.java index 003a88caf0e5..91f296109777 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordApi.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordApi.java @@ -1,22 +1,25 @@ -package com.wordnik.client.api; +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; + +import io.swagger.client.model.*; -import com.wordnik.client.common.ApiException; -import com.wordnik.client.common.ApiInvoker; -import com.wordnik.client.model.FrequencySummary; -import com.wordnik.client.model.Bigram; -import com.wordnik.client.model.WordObject; -import com.wordnik.client.model.ExampleSearchResults; -import com.wordnik.client.model.Example; -import com.wordnik.client.model.ScrabbleScoreResult; -import com.wordnik.client.model.TextPron; -import com.wordnik.client.model.Syllable; -import com.wordnik.client.model.Related; -import com.wordnik.client.model.Definition; -import com.wordnik.client.model.AudioFile; import java.util.*; +import io.swagger.client.model.WordObject; +import io.swagger.client.model.AudioFile; +import io.swagger.client.model.Definition; +import io.swagger.client.model.FrequencySummary; +import io.swagger.client.model.Bigram; +import io.swagger.client.model.Example; + +import java.util.Map; +import java.util.HashMap; +import java.io.File; + public class WordApi { - String basePath = "http://api.wordnik.com/v4"; + String basePath = "https://api.wordnik.com/v4"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public void addHeader(String key, String value) { @@ -35,52 +38,15 @@ public class WordApi { return basePath; } - public ExampleSearchResults getExamples (String word, String includeDuplicates, String useCanonical, Integer skip, Integer limit) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } + + + public WordObject getWord (String word, String useCanonical, String includeSuggestions) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/word.{format}/{word}/examples".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - if(!"null".equals(String.valueOf(includeDuplicates))) - queryParams.put("includeDuplicates", String.valueOf(includeDuplicates)); - if(!"null".equals(String.valueOf(useCanonical))) - queryParams.put("useCanonical", String.valueOf(useCanonical)); - if(!"null".equals(String.valueOf(skip))) - queryParams.put("skip", String.valueOf(skip)); - if(!"null".equals(String.valueOf(limit))) - queryParams.put("limit", String.valueOf(limit)); - String contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); - if(response != null){ - return (ExampleSearchResults) ApiInvoker.deserialize(response, "", ExampleSearchResults.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - public WordObject getWord (String word, String useCanonical, String includeSuggestions) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/word.{format}/{word}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + String path = "/word.json/{word}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); // query params Map queryParams = new HashMap(); @@ -90,10 +56,14 @@ public class WordApi { queryParams.put("useCanonical", String.valueOf(useCanonical)); if(!"null".equals(String.valueOf(includeSuggestions))) queryParams.put("includeSuggestions", String.valueOf(includeSuggestions)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ return (WordObject) ApiInvoker.deserialize(response, "", WordObject.class); } @@ -102,20 +72,63 @@ public class WordApi { } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - public List getDefinitions (String word, String partOfSpeech, String sourceDictionaries, Integer limit, String includeRelated, String useCanonical, String includeTags) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } + + + public List getAudio (String word, String useCanonical, Integer limit) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/word.{format}/{word}/definitions".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + String path = "/word.json/{word}/audio".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "array", AudioFile.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public List getDefinitions (String word, Integer limit, String partOfSpeech, String includeRelated, List sourceDictionaries, String useCanonical, String includeTags) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/word.json/{word}/definitions".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); // query params Map queryParams = new HashMap(); @@ -133,32 +146,38 @@ public class WordApi { queryParams.put("useCanonical", String.valueOf(useCanonical)); if(!"null".equals(String.valueOf(includeTags))) queryParams.put("includeTags", String.valueOf(includeTags)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", Definition.class); + return (List) ApiInvoker.deserialize(response, "array", Definition.class); } else { return null; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - public Example getTopExample (String word, String useCanonical) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } + + + public List getEtymologies (String word, String useCanonical) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/word.{format}/{word}/topExample".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + String path = "/word.json/{word}/etymologies".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); // query params Map queryParams = new HashMap(); @@ -166,32 +185,83 @@ public class WordApi { if(!"null".equals(String.valueOf(useCanonical))) queryParams.put("useCanonical", String.valueOf(useCanonical)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (Example) ApiInvoker.deserialize(response, "", Example.class); + return (List) ApiInvoker.deserialize(response, "array", String.class); } else { return null; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - public List getRelatedWords (String word, String relationshipTypes, String useCanonical, Integer limitPerRelationshipType) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } + + + public void getExamples (String word, String includeDuplicates, String useCanonical, Integer skip, Integer limit) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/word.{format}/{word}/relatedWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + String path = "/word.json/{word}/examples".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(includeDuplicates))) + queryParams.put("includeDuplicates", String.valueOf(includeDuplicates)); + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + if(!"null".equals(String.valueOf(skip))) + queryParams.put("skip", String.valueOf(skip)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public FrequencySummary getWordFrequency (String word, String useCanonical, Integer startYear, Integer endYear) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/word.json/{word}/frequency".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); // query params Map queryParams = new HashMap(); @@ -199,36 +269,128 @@ public class WordApi { if(!"null".equals(String.valueOf(useCanonical))) queryParams.put("useCanonical", String.valueOf(useCanonical)); - if(!"null".equals(String.valueOf(relationshipTypes))) - queryParams.put("relationshipTypes", String.valueOf(relationshipTypes)); - if(!"null".equals(String.valueOf(limitPerRelationshipType))) - queryParams.put("limitPerRelationshipType", String.valueOf(limitPerRelationshipType)); + if(!"null".equals(String.valueOf(startYear))) + queryParams.put("startYear", String.valueOf(startYear)); + if(!"null".equals(String.valueOf(endYear))) + queryParams.put("endYear", String.valueOf(endYear)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", Related.class); + return (FrequencySummary) ApiInvoker.deserialize(response, "", FrequencySummary.class); } else { return null; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - public List getTextPronunciations (String word, String sourceDictionary, String typeFormat, String useCanonical, Integer limit) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } + + + public void getHyphenation (String word, String useCanonical, String sourceDictionary, Integer limit) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/word.{format}/{word}/pronunciations".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + String path = "/word.json/{word}/hyphenation".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + if(!"null".equals(String.valueOf(sourceDictionary))) + queryParams.put("sourceDictionary", String.valueOf(sourceDictionary)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public List getPhrases (String word, Integer limit, Integer wlmi, String useCanonical) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/word.json/{word}/phrases".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + if(!"null".equals(String.valueOf(wlmi))) + queryParams.put("wlmi", String.valueOf(wlmi)); + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + + + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "array", Bigram.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public void getTextPronunciations (String word, String useCanonical, String sourceDictionary, String typeFormat, Integer limit) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/word.json/{word}/pronunciations".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); // query params Map queryParams = new HashMap(); @@ -242,32 +404,38 @@ public class WordApi { queryParams.put("typeFormat", String.valueOf(typeFormat)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", TextPron.class); + return ; } else { - return null; + return ; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return ; } else { throw ex; } } } - public List getHyphenation (String word, String sourceDictionary, String useCanonical, Integer limit) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } + + + public void getRelatedWords (String word, String useCanonical, String relationshipTypes, Integer limitPerRelationshipType) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/word.{format}/{word}/hyphenation".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + String path = "/word.json/{word}/relatedWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); // query params Map queryParams = new HashMap(); @@ -275,36 +443,42 @@ public class WordApi { if(!"null".equals(String.valueOf(useCanonical))) queryParams.put("useCanonical", String.valueOf(useCanonical)); - if(!"null".equals(String.valueOf(sourceDictionary))) - queryParams.put("sourceDictionary", String.valueOf(sourceDictionary)); - if(!"null".equals(String.valueOf(limit))) - queryParams.put("limit", String.valueOf(limit)); + if(!"null".equals(String.valueOf(relationshipTypes))) + queryParams.put("relationshipTypes", String.valueOf(relationshipTypes)); + if(!"null".equals(String.valueOf(limitPerRelationshipType))) + queryParams.put("limitPerRelationshipType", String.valueOf(limitPerRelationshipType)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", Syllable.class); + return ; } else { - return null; + return ; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return ; } else { throw ex; } } } - public FrequencySummary getWordFrequency (String word, String useCanonical, Integer startYear, Integer endYear) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } + + + public Example getTopExample (String word, String useCanonical) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/word.{format}/{word}/frequency".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + String path = "/word.json/{word}/topExample".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); // query params Map queryParams = new HashMap(); @@ -312,164 +486,28 @@ public class WordApi { if(!"null".equals(String.valueOf(useCanonical))) queryParams.put("useCanonical", String.valueOf(useCanonical)); - if(!"null".equals(String.valueOf(startYear))) - queryParams.put("startYear", String.valueOf(startYear)); - if(!"null".equals(String.valueOf(endYear))) - queryParams.put("endYear", String.valueOf(endYear)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (FrequencySummary) ApiInvoker.deserialize(response, "", FrequencySummary.class); + return (Example) ApiInvoker.deserialize(response, "", Example.class); } else { return null; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - public List getPhrases (String word, Integer limit, Integer wlmi, String useCanonical) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/word.{format}/{word}/phrases".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - if(!"null".equals(String.valueOf(limit))) - queryParams.put("limit", String.valueOf(limit)); - if(!"null".equals(String.valueOf(wlmi))) - queryParams.put("wlmi", String.valueOf(wlmi)); - if(!"null".equals(String.valueOf(useCanonical))) - queryParams.put("useCanonical", String.valueOf(useCanonical)); - String contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); - if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", Bigram.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - public List getEtymologies (String word, String useCanonical) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/word.{format}/{word}/etymologies".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - if(!"null".equals(String.valueOf(useCanonical))) - queryParams.put("useCanonical", String.valueOf(useCanonical)); - String contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); - if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", String.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - public List getAudio (String word, String useCanonical, Integer limit) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/word.{format}/{word}/audio".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - if(!"null".equals(String.valueOf(useCanonical))) - queryParams.put("useCanonical", String.valueOf(useCanonical)); - if(!"null".equals(String.valueOf(limit))) - queryParams.put("limit", String.valueOf(limit)); - String contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); - if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", AudioFile.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - public ScrabbleScoreResult getScrabbleScore (String word) throws ApiException { - // verify required params are set - if(word == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/word.{format}/{word}/scrabbleScore".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - String contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); - if(response != null){ - return (ScrabbleScoreResult) ApiInvoker.deserialize(response, "", ScrabbleScoreResult.class); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return null; - } - else { - throw ex; - } - } - } - } - + +} diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListApi.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordListApi.java similarity index 55% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListApi.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordListApi.java index e017c4666367..27ad7f780c6f 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListApi.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordListApi.java @@ -1,14 +1,22 @@ -package com.wordnik.client.api; +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; + +import io.swagger.client.model.*; -import com.wordnik.client.common.ApiException; -import com.wordnik.client.common.ApiInvoker; -import com.wordnik.client.model.WordListWord; -import com.wordnik.client.model.WordList; -import com.wordnik.client.model.StringValue; import java.util.*; +import io.swagger.client.model.WordList; +import java.util.*; +import io.swagger.client.model.StringValue; + +import java.util.Map; +import java.util.HashMap; +import java.io.File; + public class WordListApi { - String basePath = "http://api.wordnik.com/v4"; + String basePath = "https://api.wordnik.com/v4"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public void addHeader(String key, String value) { @@ -27,87 +35,29 @@ public class WordListApi { return basePath; } - public void updateWordList (String permalink, WordList body, String auth_token) throws ApiException { - // verify required params are set - if(permalink == null || auth_token == null ) { - throw new ApiException(400, "missing required params"); - } + + + public WordList getWordListByPermalink (String permalink, String auth_token) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + String path = "/wordList.json/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); + + headerParams.put("auth_token", auth_token); + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - public void deleteWordList (String permalink, String auth_token) throws ApiException { - // verify required params are set - if(permalink == null || auth_token == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - headerParams.put("auth_token", auth_token); - String contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, contentType); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.getCode() == 404) { - return ; - } - else { - throw ex; - } - } - } - public WordList getWordListByPermalink (String permalink, String auth_token) throws ApiException { - // verify required params are set - if(permalink == null || auth_token == null ) { - throw new ApiException(400, "missing required params"); - } - // create path and map variables - String path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - - headerParams.put("auth_token", auth_token); - String contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ return (WordList) ApiInvoker.deserialize(response, "", WordList.class); } @@ -116,30 +66,36 @@ public class WordListApi { } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - public void addWordsToWordList (String permalink, List body, String auth_token) throws ApiException { - // verify required params are set - if(permalink == null || auth_token == null ) { - throw new ApiException(400, "missing required params"); - } + + + public void updateWordList (String permalink, WordList body, String auth_token) throws ApiException { + Object postBody = body; + + + // create path and map variables - String path = "/wordList.{format}/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + String path = "/wordList.json/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); + + headerParams.put("auth_token", auth_token); + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, contentType); if(response != null){ return ; } @@ -155,13 +111,91 @@ public class WordListApi { } } } - public List getWordListWords (String permalink, String auth_token, String sortBy, String sortOrder, Integer skip, Integer limit) throws ApiException { - // verify required params are set - if(permalink == null || auth_token == null ) { - throw new ApiException(400, "missing required params"); - } + + + public void deleteWordList (String permalink, String auth_token) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/wordList.{format}/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + String path = "/wordList.json/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + headerParams.put("auth_token", auth_token); + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void deleteWordsFromWordList (String permalink, List body, String auth_token) throws ApiException { + Object postBody = body; + + + + // create path and map variables + String path = "/wordList.json/{permalink}/deleteWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + + + headerParams.put("auth_token", auth_token); + + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + + + public void getWordListWords (String permalink, String sortBy, String sortOrder, Integer skip, Integer limit, String auth_token) throws ApiException { + Object postBody = null; + + + + // create path and map variables + String path = "/wordList.json/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); // query params Map queryParams = new HashMap(); @@ -175,43 +209,53 @@ public class WordListApi { queryParams.put("skip", String.valueOf(skip)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); + + headerParams.put("auth_token", auth_token); + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", WordListWord.class); + return ; } else { - return null; + return ; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return ; } else { throw ex; } } } - public void deleteWordsFromWordList (String permalink, List body, String auth_token) throws ApiException { - // verify required params are set - if(permalink == null || auth_token == null ) { - throw new ApiException(400, "missing required params"); - } + + + public void addWordsToWordList (String permalink, List body, String auth_token) throws ApiException { + Object postBody = body; + + + // create path and map variables - String path = "/wordList.{format}/{permalink}/deleteWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + String path = "/wordList.json/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); + + headerParams.put("auth_token", auth_token); + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); if(response != null){ return ; } @@ -227,5 +271,5 @@ public class WordListApi { } } } - } - + +} diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListsApi.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordListsApi.java similarity index 63% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListsApi.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordListsApi.java index c97ab75e5971..25eeb0cde896 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListsApi.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordListsApi.java @@ -1,12 +1,20 @@ -package com.wordnik.client.api; +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; + +import io.swagger.client.model.*; -import com.wordnik.client.common.ApiException; -import com.wordnik.client.common.ApiInvoker; -import com.wordnik.client.model.WordList; import java.util.*; +import io.swagger.client.model.WordList; + +import java.util.Map; +import java.util.HashMap; +import java.io.File; + public class WordListsApi { - String basePath = "http://api.wordnik.com/v4"; + String basePath = "https://api.wordnik.com/v4"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public void addHeader(String key, String value) { @@ -25,23 +33,29 @@ public class WordListsApi { return basePath; } - public WordList createWordList (WordList body, String auth_token) throws ApiException { - // verify required params are set - if(auth_token == null ) { - throw new ApiException(400, "missing required params"); - } + + + public WordList createWordList (WordList body, String auth_token) throws ApiException { + Object postBody = body; + + + // create path and map variables - String path = "/wordLists.{format}".replaceAll("\\{format\\}","json"); + String path = "/wordLists.json".replaceAll("\\{format\\}","json"); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); + + headerParams.put("auth_token", auth_token); + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, contentType); if(response != null){ return (WordList) ApiInvoker.deserialize(response, "", WordList.class); } @@ -50,12 +64,12 @@ public class WordListsApi { } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - } - + +} diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordsApi.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordsApi.java similarity index 75% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordsApi.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordsApi.java index c1c8a81efa0f..7cc9da2c1328 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordsApi.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/api/WordsApi.java @@ -1,15 +1,23 @@ -package com.wordnik.client.api; +package io.swagger.client.api; + +import io.swagger.client.ApiException; +import io.swagger.client.ApiInvoker; + +import io.swagger.client.model.*; -import com.wordnik.client.common.ApiException; -import com.wordnik.client.common.ApiInvoker; -import com.wordnik.client.model.DefinitionSearchResults; -import com.wordnik.client.model.WordObject; -import com.wordnik.client.model.WordOfTheDay; -import com.wordnik.client.model.WordSearchResults; import java.util.*; +import io.swagger.client.model.WordObject; +import io.swagger.client.model.DefinitionSearchResults; +import io.swagger.client.model.WordSearchResults; +import io.swagger.client.model.WordOfTheDay; + +import java.util.Map; +import java.util.HashMap; +import java.io.File; + public class WordsApi { - String basePath = "http://api.wordnik.com/v4"; + String basePath = "https://api.wordnik.com/v4"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public void addHeader(String key, String value) { @@ -28,20 +36,22 @@ public class WordsApi { return basePath; } - public WordSearchResults searchWords (String query, String includePartOfSpeech, String excludePartOfSpeech, String caseSensitive, Integer minCorpusCount, Integer maxCorpusCount, Integer minDictionaryCount, Integer maxDictionaryCount, Integer minLength, Integer maxLength, Integer skip, Integer limit) throws ApiException { - // verify required params are set - if(query == null ) { - throw new ApiException(400, "missing required params"); - } + + + public WordObject getRandomWord (String hasDictionaryDef, String includePartOfSpeech, String excludePartOfSpeech, Integer minCorpusCount, Integer maxCorpusCount, Integer minDictionaryCount, Integer maxDictionaryCount, Integer minLength, Integer maxLength) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/words.{format}/search/{query}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "query" + "\\}", apiInvoker.escapeString(query.toString())); + String path = "/words.json/randomWord".replaceAll("\\{format\\}","json"); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); - if(!"null".equals(String.valueOf(caseSensitive))) - queryParams.put("caseSensitive", String.valueOf(caseSensitive)); + if(!"null".equals(String.valueOf(hasDictionaryDef))) + queryParams.put("hasDictionaryDef", String.valueOf(hasDictionaryDef)); if(!"null".equals(String.valueOf(includePartOfSpeech))) queryParams.put("includePartOfSpeech", String.valueOf(includePartOfSpeech)); if(!"null".equals(String.valueOf(excludePartOfSpeech))) @@ -58,65 +68,99 @@ public class WordsApi { queryParams.put("minLength", String.valueOf(minLength)); if(!"null".equals(String.valueOf(maxLength))) queryParams.put("maxLength", String.valueOf(maxLength)); - if(!"null".equals(String.valueOf(skip))) - queryParams.put("skip", String.valueOf(skip)); - if(!"null".equals(String.valueOf(limit))) - queryParams.put("limit", String.valueOf(limit)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (WordSearchResults) ApiInvoker.deserialize(response, "", WordSearchResults.class); + return (WordObject) ApiInvoker.deserialize(response, "", WordObject.class); } else { return null; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - public WordOfTheDay getWordOfTheDay (String date) throws ApiException { + + + public void getRandomWords (String hasDictionaryDef, String includePartOfSpeech, String excludePartOfSpeech, Integer minCorpusCount, Integer maxCorpusCount, Integer minDictionaryCount, Integer maxDictionaryCount, Integer minLength, Integer maxLength, String sortBy, String sortOrder, Integer limit) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/words.{format}/wordOfTheDay".replaceAll("\\{format\\}","json"); + String path = "/words.json/randomWords".replaceAll("\\{format\\}","json"); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); - if(!"null".equals(String.valueOf(date))) - queryParams.put("date", String.valueOf(date)); + if(!"null".equals(String.valueOf(hasDictionaryDef))) + queryParams.put("hasDictionaryDef", String.valueOf(hasDictionaryDef)); + if(!"null".equals(String.valueOf(includePartOfSpeech))) + queryParams.put("includePartOfSpeech", String.valueOf(includePartOfSpeech)); + if(!"null".equals(String.valueOf(excludePartOfSpeech))) + queryParams.put("excludePartOfSpeech", String.valueOf(excludePartOfSpeech)); + if(!"null".equals(String.valueOf(minCorpusCount))) + queryParams.put("minCorpusCount", String.valueOf(minCorpusCount)); + if(!"null".equals(String.valueOf(maxCorpusCount))) + queryParams.put("maxCorpusCount", String.valueOf(maxCorpusCount)); + if(!"null".equals(String.valueOf(minDictionaryCount))) + queryParams.put("minDictionaryCount", String.valueOf(minDictionaryCount)); + if(!"null".equals(String.valueOf(maxDictionaryCount))) + queryParams.put("maxDictionaryCount", String.valueOf(maxDictionaryCount)); + if(!"null".equals(String.valueOf(minLength))) + queryParams.put("minLength", String.valueOf(minLength)); + if(!"null".equals(String.valueOf(maxLength))) + queryParams.put("maxLength", String.valueOf(maxLength)); + if(!"null".equals(String.valueOf(sortBy))) + queryParams.put("sortBy", String.valueOf(sortBy)); + if(!"null".equals(String.valueOf(sortOrder))) + queryParams.put("sortOrder", String.valueOf(sortOrder)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (WordOfTheDay) ApiInvoker.deserialize(response, "", WordOfTheDay.class); + return ; } else { - return null; + return ; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return ; } else { throw ex; } } } - public DefinitionSearchResults reverseDictionary (String query, String findSenseForWord, String includeSourceDictionaries, String excludeSourceDictionaries, String includePartOfSpeech, String excludePartOfSpeech, String expandTerms, String sortBy, String sortOrder, Integer minCorpusCount, Integer maxCorpusCount, Integer minLength, Integer maxLength, String includeTags, String skip, Integer limit) throws ApiException { - // verify required params are set - if(query == null ) { - throw new ApiException(400, "missing required params"); - } + + + public DefinitionSearchResults reverseDictionary (String query, String findSenseForWord, String includeSourceDictionaries, String excludeSourceDictionaries, String includePartOfSpeech, String excludePartOfSpeech, Integer minCorpusCount, Integer maxCorpusCount, Integer minLength, Integer maxLength, String expandTerms, String includeTags, String sortBy, String sortOrder, String skip, Integer limit) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/words.{format}/reverseDictionary".replaceAll("\\{format\\}","json"); + String path = "/words.json/reverseDictionary".replaceAll("\\{format\\}","json"); // query params Map queryParams = new HashMap(); @@ -154,10 +198,14 @@ public class WordsApi { queryParams.put("skip", String.valueOf(skip)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ return (DefinitionSearchResults) ApiInvoker.deserialize(response, "", DefinitionSearchResults.class); } @@ -166,23 +214,29 @@ public class WordsApi { } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - public List getRandomWords (String includePartOfSpeech, String excludePartOfSpeech, String sortBy, String sortOrder, String hasDictionaryDef, Integer minCorpusCount, Integer maxCorpusCount, Integer minDictionaryCount, Integer maxDictionaryCount, Integer minLength, Integer maxLength, Integer limit) throws ApiException { + + + public WordSearchResults searchWords (String query, String caseSensitive, String includePartOfSpeech, String excludePartOfSpeech, Integer minCorpusCount, Integer maxCorpusCount, Integer minDictionaryCount, Integer maxDictionaryCount, Integer minLength, Integer maxLength, Integer skip, Integer limit) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/words.{format}/randomWords".replaceAll("\\{format\\}","json"); + String path = "/words.json/search/{query}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "query" + "\\}", apiInvoker.escapeString(query.toString())); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); - if(!"null".equals(String.valueOf(hasDictionaryDef))) - queryParams.put("hasDictionaryDef", String.valueOf(hasDictionaryDef)); + if(!"null".equals(String.valueOf(caseSensitive))) + queryParams.put("caseSensitive", String.valueOf(caseSensitive)); if(!"null".equals(String.valueOf(includePartOfSpeech))) queryParams.put("includePartOfSpeech", String.valueOf(includePartOfSpeech)); if(!"null".equals(String.valueOf(excludePartOfSpeech))) @@ -199,75 +253,71 @@ public class WordsApi { queryParams.put("minLength", String.valueOf(minLength)); if(!"null".equals(String.valueOf(maxLength))) queryParams.put("maxLength", String.valueOf(maxLength)); - if(!"null".equals(String.valueOf(sortBy))) - queryParams.put("sortBy", String.valueOf(sortBy)); - if(!"null".equals(String.valueOf(sortOrder))) - queryParams.put("sortOrder", String.valueOf(sortOrder)); + if(!"null".equals(String.valueOf(skip))) + queryParams.put("skip", String.valueOf(skip)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (List) ApiInvoker.deserialize(response, "List", WordObject.class); + return (WordSearchResults) ApiInvoker.deserialize(response, "", WordSearchResults.class); } else { return null; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - public WordObject getRandomWord (String includePartOfSpeech, String excludePartOfSpeech, String hasDictionaryDef, Integer minCorpusCount, Integer maxCorpusCount, Integer minDictionaryCount, Integer maxDictionaryCount, Integer minLength, Integer maxLength) throws ApiException { + + + public WordOfTheDay getWordOfTheDay (String date) throws ApiException { + Object postBody = null; + + + // create path and map variables - String path = "/words.{format}/randomWord".replaceAll("\\{format\\}","json"); + String path = "/words.json/wordOfTheDay".replaceAll("\\{format\\}","json"); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); - if(!"null".equals(String.valueOf(hasDictionaryDef))) - queryParams.put("hasDictionaryDef", String.valueOf(hasDictionaryDef)); - if(!"null".equals(String.valueOf(includePartOfSpeech))) - queryParams.put("includePartOfSpeech", String.valueOf(includePartOfSpeech)); - if(!"null".equals(String.valueOf(excludePartOfSpeech))) - queryParams.put("excludePartOfSpeech", String.valueOf(excludePartOfSpeech)); - if(!"null".equals(String.valueOf(minCorpusCount))) - queryParams.put("minCorpusCount", String.valueOf(minCorpusCount)); - if(!"null".equals(String.valueOf(maxCorpusCount))) - queryParams.put("maxCorpusCount", String.valueOf(maxCorpusCount)); - if(!"null".equals(String.valueOf(minDictionaryCount))) - queryParams.put("minDictionaryCount", String.valueOf(minDictionaryCount)); - if(!"null".equals(String.valueOf(maxDictionaryCount))) - queryParams.put("maxDictionaryCount", String.valueOf(maxDictionaryCount)); - if(!"null".equals(String.valueOf(minLength))) - queryParams.put("minLength", String.valueOf(minLength)); - if(!"null".equals(String.valueOf(maxLength))) - queryParams.put("maxLength", String.valueOf(maxLength)); + if(!"null".equals(String.valueOf(date))) + queryParams.put("date", String.valueOf(date)); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, contentType); if(response != null){ - return (WordObject) ApiInvoker.deserialize(response, "", WordObject.class); + return (WordOfTheDay) ApiInvoker.deserialize(response, "", WordOfTheDay.class); } else { return null; } } catch (ApiException ex) { if(ex.getCode() == 404) { - return null; + return null; } else { throw ex; } } } - } - + +} diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ApiTokenStatus.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/ApiTokenStatus.java similarity index 78% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ApiTokenStatus.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/ApiTokenStatus.java index 4f65a3505373..5345aaeb0ccf 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ApiTokenStatus.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/ApiTokenStatus.java @@ -1,20 +1,25 @@ -package com.wordnik.client.model; +package io.swagger.client.model; + +import com.wordnik.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; -public class ApiTokenStatus { - @JsonProperty("valid") + +@ApiModel(description = "") +public class ApiTokenStatus { + private Boolean valid = null; - @JsonProperty("token") private String token = null; - @JsonProperty("resetsInMillis") private Long resetsInMillis = null; - @JsonProperty("remainingCalls") private Long remainingCalls = null; - @JsonProperty("expiresInMillis") private Long expiresInMillis = null; - @JsonProperty("totalRequests") private Long totalRequests = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("valid") public Boolean getValid() { return valid; } @@ -22,6 +27,11 @@ public class ApiTokenStatus { this.valid = valid; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("token") public String getToken() { return token; } @@ -29,6 +39,11 @@ public class ApiTokenStatus { this.token = token; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("resetsInMillis") public Long getResetsInMillis() { return resetsInMillis; } @@ -36,6 +51,11 @@ public class ApiTokenStatus { this.resetsInMillis = resetsInMillis; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("remainingCalls") public Long getRemainingCalls() { return remainingCalls; } @@ -43,6 +63,11 @@ public class ApiTokenStatus { this.remainingCalls = remainingCalls; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("expiresInMillis") public Long getExpiresInMillis() { return expiresInMillis; } @@ -50,6 +75,11 @@ public class ApiTokenStatus { this.expiresInMillis = expiresInMillis; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("totalRequests") public Long getTotalRequests() { return totalRequests; } @@ -57,10 +87,13 @@ public class ApiTokenStatus { this.totalRequests = totalRequests; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ApiTokenStatus {\n"); + sb.append(" valid: ").append(valid).append("\n"); sb.append(" token: ").append(token).append("\n"); sb.append(" resetsInMillis: ").append(resetsInMillis).append("\n"); @@ -71,4 +104,3 @@ public class ApiTokenStatus { return sb.toString(); } } - diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AudioFile.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/AudioFile.java similarity index 79% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AudioFile.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/AudioFile.java index d6d46ad2f8e4..372ccfed7ed3 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AudioFile.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/AudioFile.java @@ -1,37 +1,34 @@ -package com.wordnik.client.model; - -import com.fasterxml.jackson.annotation.JsonProperty; +package io.swagger.client.model; import java.util.Date; -public class AudioFile { - @JsonProperty("attributionUrl") + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class AudioFile { + private String attributionUrl = null; - @JsonProperty("commentCount") private Integer commentCount = null; - @JsonProperty("voteCount") private Integer voteCount = null; - @JsonProperty("fileUrl") private String fileUrl = null; - @JsonProperty("audioType") private String audioType = null; - @JsonProperty("id") private Long id = null; - @JsonProperty("duration") private Double duration = null; - @JsonProperty("attributionText") private String attributionText = null; - @JsonProperty("createdBy") private String createdBy = null; - @JsonProperty("description") private String description = null; - @JsonProperty("createdAt") private Date createdAt = null; - @JsonProperty("voteWeightedAverage") private Float voteWeightedAverage = null; - @JsonProperty("voteAverage") private Float voteAverage = null; - @JsonProperty("word") private String word = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("attributionUrl") public String getAttributionUrl() { return attributionUrl; } @@ -39,6 +36,11 @@ public class AudioFile { this.attributionUrl = attributionUrl; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("commentCount") public Integer getCommentCount() { return commentCount; } @@ -46,6 +48,11 @@ public class AudioFile { this.commentCount = commentCount; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("voteCount") public Integer getVoteCount() { return voteCount; } @@ -53,6 +60,11 @@ public class AudioFile { this.voteCount = voteCount; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("fileUrl") public String getFileUrl() { return fileUrl; } @@ -60,6 +72,11 @@ public class AudioFile { this.fileUrl = fileUrl; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("audioType") public String getAudioType() { return audioType; } @@ -67,6 +84,11 @@ public class AudioFile { this.audioType = audioType; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -74,6 +96,11 @@ public class AudioFile { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("duration") public Double getDuration() { return duration; } @@ -81,6 +108,11 @@ public class AudioFile { this.duration = duration; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("attributionText") public String getAttributionText() { return attributionText; } @@ -88,6 +120,11 @@ public class AudioFile { this.attributionText = attributionText; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("createdBy") public String getCreatedBy() { return createdBy; } @@ -95,6 +132,11 @@ public class AudioFile { this.createdBy = createdBy; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("description") public String getDescription() { return description; } @@ -102,6 +144,11 @@ public class AudioFile { this.description = description; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("createdAt") public Date getCreatedAt() { return createdAt; } @@ -109,6 +156,11 @@ public class AudioFile { this.createdAt = createdAt; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("voteWeightedAverage") public Float getVoteWeightedAverage() { return voteWeightedAverage; } @@ -116,6 +168,11 @@ public class AudioFile { this.voteWeightedAverage = voteWeightedAverage; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("voteAverage") public Float getVoteAverage() { return voteAverage; } @@ -123,6 +180,11 @@ public class AudioFile { this.voteAverage = voteAverage; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("word") public String getWord() { return word; } @@ -130,10 +192,13 @@ public class AudioFile { this.word = word; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AudioFile {\n"); + sb.append(" attributionUrl: ").append(attributionUrl).append("\n"); sb.append(" commentCount: ").append(commentCount).append("\n"); sb.append(" voteCount: ").append(voteCount).append("\n"); @@ -152,4 +217,3 @@ public class AudioFile { return sb.toString(); } } - diff --git a/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/AudioType.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/AudioType.java new file mode 100644 index 000000000000..c8ce06c0efd7 --- /dev/null +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/AudioType.java @@ -0,0 +1,50 @@ +package io.swagger.client.model; + + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class AudioType { + + private Integer id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AudioType {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AuthenticationToken.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/AuthenticationToken.java similarity index 74% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AuthenticationToken.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/AuthenticationToken.java index 03c6cc00dbae..d047965b23fb 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AuthenticationToken.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/AuthenticationToken.java @@ -1,14 +1,22 @@ -package com.wordnik.client.model; +package io.swagger.client.model; + +import com.wordnik.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; -public class AuthenticationToken { - @JsonProperty("token") + +@ApiModel(description = "") +public class AuthenticationToken { + private String token = null; - @JsonProperty("userId") private Long userId = null; - @JsonProperty("userSignature") private String userSignature = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("token") public String getToken() { return token; } @@ -16,6 +24,11 @@ public class AuthenticationToken { this.token = token; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("userId") public Long getUserId() { return userId; } @@ -23,6 +36,11 @@ public class AuthenticationToken { this.userId = userId; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("userSignature") public String getUserSignature() { return userSignature; } @@ -30,10 +48,13 @@ public class AuthenticationToken { this.userSignature = userSignature; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AuthenticationToken {\n"); + sb.append(" token: ").append(token).append("\n"); sb.append(" userId: ").append(userId).append("\n"); sb.append(" userSignature: ").append(userSignature).append("\n"); @@ -41,4 +62,3 @@ public class AuthenticationToken { return sb.toString(); } } - diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Bigram.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Bigram.java similarity index 73% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Bigram.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Bigram.java index 4be9f36cf561..d864b73c02e6 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Bigram.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Bigram.java @@ -1,18 +1,24 @@ -package com.wordnik.client.model; +package io.swagger.client.model; + +import com.wordnik.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; -public class Bigram { - @JsonProperty("count") + +@ApiModel(description = "") +public class Bigram { + private Long count = null; - @JsonProperty("gram2") private String gram2 = null; - @JsonProperty("gram1") private String gram1 = null; - @JsonProperty("wlmi") private Double wlmi = null; - @JsonProperty("mi") private Double mi = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("count") public Long getCount() { return count; } @@ -20,6 +26,11 @@ public class Bigram { this.count = count; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("gram2") public String getGram2() { return gram2; } @@ -27,6 +38,11 @@ public class Bigram { this.gram2 = gram2; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("gram1") public String getGram1() { return gram1; } @@ -34,6 +50,11 @@ public class Bigram { this.gram1 = gram1; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("wlmi") public Double getWlmi() { return wlmi; } @@ -41,6 +62,11 @@ public class Bigram { this.wlmi = wlmi; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("mi") public Double getMi() { return mi; } @@ -48,10 +74,13 @@ public class Bigram { this.mi = mi; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Bigram {\n"); + sb.append(" count: ").append(count).append("\n"); sb.append(" gram2: ").append(gram2).append("\n"); sb.append(" gram1: ").append(gram1).append("\n"); @@ -61,4 +90,3 @@ public class Bigram { return sb.toString(); } } - diff --git a/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Category.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 000000000000..3a7a84f89bb0 --- /dev/null +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,50 @@ +package io.swagger.client.model; + + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Category { + + private Long id = null; + private String name = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("name") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Citation.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Citation.java similarity index 71% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Citation.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Citation.java index 5b2f45bc6505..f696895e6b50 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Citation.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Citation.java @@ -1,12 +1,21 @@ -package com.wordnik.client.model; +package io.swagger.client.model; + +import com.wordnik.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; -public class Citation { - @JsonProperty("cite") + +@ApiModel(description = "") +public class Citation { + private String cite = null; - @JsonProperty("source") private String source = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("cite") public String getCite() { return cite; } @@ -14,6 +23,11 @@ public class Citation { this.cite = cite; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("source") public String getSource() { return source; } @@ -21,14 +35,16 @@ public class Citation { this.source = source; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Citation {\n"); + sb.append(" cite: ").append(cite).append("\n"); sb.append(" source: ").append(source).append("\n"); sb.append("}\n"); return sb.toString(); } } - diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ContentProvider.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/ContentProvider.java similarity index 70% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ContentProvider.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/ContentProvider.java index b0d994d3b0b1..a069dad1a9f6 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ContentProvider.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/ContentProvider.java @@ -1,12 +1,21 @@ -package com.wordnik.client.model; +package io.swagger.client.model; + +import com.wordnik.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; -public class ContentProvider { - @JsonProperty("id") + +@ApiModel(description = "") +public class ContentProvider { + private Integer id = null; - @JsonProperty("name") private String name = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Integer getId() { return id; } @@ -14,6 +23,11 @@ public class ContentProvider { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("name") public String getName() { return name; } @@ -21,14 +35,16 @@ public class ContentProvider { this.name = name; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ContentProvider {\n"); + sb.append(" id: ").append(id).append("\n"); sb.append(" name: ").append(name).append("\n"); sb.append("}\n"); return sb.toString(); } } - diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Definition.java b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Definition.java similarity index 72% rename from samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Definition.java rename to samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Definition.java index f16273a415ab..e2e799d8b568 100644 --- a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Definition.java +++ b/samples/client/wordnik/android-java/src/main/java/io/swagger/client/model/Definition.java @@ -1,47 +1,42 @@ -package com.wordnik.client.model; +package io.swagger.client.model; +import io.swagger.client.model.Related; +import io.swagger.client.model.Note; +import io.swagger.client.model.Label; +import io.swagger.client.model.TextPron; +import io.swagger.client.model.ExampleUsage; +import java.util.*; +import io.swagger.client.model.Citation; + +import com.wordnik.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.*; -import com.wordnik.client.model.Label; -import com.wordnik.client.model.ExampleUsage; -import com.wordnik.client.model.TextPron; -import com.wordnik.client.model.Citation; -import com.wordnik.client.model.Related; -import com.wordnik.client.model.Note; -public class Definition { - @JsonProperty("extendedText") + +@ApiModel(description = "") +public class Definition { + private String extendedText = null; - @JsonProperty("text") private String text = null; - @JsonProperty("sourceDictionary") private String sourceDictionary = null; - @JsonProperty("citations") - private List citations = new ArrayList(); - @JsonProperty("labels") - private List
+ + + + + +
  • getOrderById
  • + +
  • deleteOrder
  • + + + + + +

    Getting Started

    @@ -80,4 +115,4 @@
    - + \ No newline at end of file diff --git a/samples/dynamic-html/docs/models/Category.html b/samples/dynamic-html/docs/models/Category.html new file mode 100644 index 000000000000..52e04b2072a3 --- /dev/null +++ b/samples/dynamic-html/docs/models/Category.html @@ -0,0 +1,15 @@ + +

    Category

    + +
      +
    • id : Long +
      +
    • +
    + +
      +
    • name : String +
      +
    • +
    + diff --git a/samples/dynamic-html/docs/models/Order.html b/samples/dynamic-html/docs/models/Order.html new file mode 100644 index 000000000000..cea3cef3fd62 --- /dev/null +++ b/samples/dynamic-html/docs/models/Order.html @@ -0,0 +1,39 @@ + +

    Order

    + +
      +
    • id : Long +
      +
    • +
    + +
      +
    • petId : Long +
      +
    • +
    + +
      +
    • quantity : Integer +
      +
    • +
    + +
      +
    • shipDate : Date +
      +
    • +
    + +
      +
    • status : String +
      Order Status +
    • +
    + +
      +
    • complete : Boolean +
      +
    • +
    + diff --git a/samples/dynamic-html/docs/models/Pet.html b/samples/dynamic-html/docs/models/Pet.html new file mode 100644 index 000000000000..ea50d7f02998 --- /dev/null +++ b/samples/dynamic-html/docs/models/Pet.html @@ -0,0 +1,39 @@ + +

    Pet

    + +
      +
    • id : Long +
      +
    • +
    + +
      +
    • category : Category +
      +
    • +
    + +
      +
    • name : String +
      +
    • +
    + +
      +
    • photoUrls : List +
      +
    • +
    + +
      +
    • tags : List +
      +
    • +
    + +
      +
    • status : String +
      pet status in the store +
    • +
    + diff --git a/samples/dynamic-html/docs/models/Tag.html b/samples/dynamic-html/docs/models/Tag.html new file mode 100644 index 000000000000..ba0314f1c41f --- /dev/null +++ b/samples/dynamic-html/docs/models/Tag.html @@ -0,0 +1,15 @@ + +

    Tag

    + +
      +
    • id : Long +
      +
    • +
    + +
      +
    • name : String +
      +
    • +
    + diff --git a/samples/dynamic-html/docs/models/User.html b/samples/dynamic-html/docs/models/User.html new file mode 100644 index 000000000000..41f7e2376f17 --- /dev/null +++ b/samples/dynamic-html/docs/models/User.html @@ -0,0 +1,51 @@ + +

    User

    + +
      +
    • id : Long +
      +
    • +
    + +
      +
    • username : String +
      +
    • +
    + +
      +
    • firstName : String +
      +
    • +
    + +
      +
    • lastName : String +
      +
    • +
    + +
      +
    • email : String +
      +
    • +
    + +
      +
    • password : String +
      +
    • +
    + +
      +
    • phone : String +
      +
    • +
    + +
      +
    • userStatus : Integer +
      User Status +
    • +
    + diff --git a/samples/dynamic-html/docs/operations/PetApi.html b/samples/dynamic-html/docs/operations/PetApi.html new file mode 100644 index 000000000000..11ca041d8d8b --- /dev/null +++ b/samples/dynamic-html/docs/operations/PetApi.html @@ -0,0 +1,232 @@ +
    +

    +

    This is the API

    + + + +

    updatePet

    +
    +

    +

    +

    URL

    + http://petstore.swagger.io/v2/pet +

    HTTP Method

    + PUT +

    Response Type

    +
    +

    Parameters

    +
      + +
      + + + + +

      Pet object that needs to be added to the store

      +
      + +
    + +

    addPet

    +
    +

    +

    +

    URL

    + http://petstore.swagger.io/v2/pet +

    HTTP Method

    + POST +

    Response Type

    +
    +

    Parameters

    +
      + +
      + + + + +

      Pet object that needs to be added to the store

      +
      + +
    + +

    findPetsByStatus

    +
    +

    +

    Multiple status values can be provided with comma seperated strings

    +

    URL

    + http://petstore.swagger.io/v2/pet/findByStatus +

    HTTP Method

    + GET +

    Response Type

    + +

    Parameters

    +
      + +
      + + + + +

      Status values that need to be considered for filter

      +
      + +
    + +

    findPetsByTags

    +
    +

    +

    Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.

    +

    URL

    + http://petstore.swagger.io/v2/pet/findByTags +

    HTTP Method

    + GET +

    Response Type

    + +

    Parameters

    +
      + +
      + + + + +

      Tags to filter by

      +
      + +
    + +

    getPetById

    +
    +

    +

    Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions

    +

    URL

    + http://petstore.swagger.io/v2/pet/{petId} +

    HTTP Method

    + GET +

    Response Type

    + +

    Parameters

    +
      + +
      + + + + +

      ID of pet that needs to be fetched

      +
      + +
    + +

    updatePetWithForm

    +
    +

    +

    +

    URL

    + http://petstore.swagger.io/v2/pet/{petId} +

    HTTP Method

    + POST +

    Response Type

    +
    +

    Parameters

    +
      + +
      + + + + +

      ID of pet that needs to be updated

      +
      + +
      + + + + +

      Updated name of the pet

      +
      + +
      + + + + +

      Updated status of the pet

      +
      + +
    + +

    deletePet

    +
    +

    +

    +

    URL

    + http://petstore.swagger.io/v2/pet/{petId} +

    HTTP Method

    + DELETE +

    Response Type

    +
    +

    Parameters

    +
      + +
      + + + + +

      +
      + +
      + + + + +

      Pet id to delete

      +
      + +
    + +

    uploadFile

    +
    +

    +

    +

    URL

    + http://petstore.swagger.io/v2/pet/{petId}/uploadImage +

    HTTP Method

    + POST +

    Response Type

    +
    +

    Parameters

    +
      + +
      + + + + +

      ID of pet to update

      +
      + +
      + + + + +

      Additional data to pass to server

      +
      + +
      + + + + +

      file to upload

      +
      + +
    + + +
    \ No newline at end of file diff --git a/samples/dynamic-html/docs/operations/StoreApi.html b/samples/dynamic-html/docs/operations/StoreApi.html new file mode 100644 index 000000000000..798372217f04 --- /dev/null +++ b/samples/dynamic-html/docs/operations/StoreApi.html @@ -0,0 +1,92 @@ +
    +

    +

    This is the API

    + + + +

    getInventory

    +
    +

    +

    Returns a map of status codes to quantities

    +

    URL

    + http://petstore.swagger.io/v2/store/inventory +

    HTTP Method

    + GET +

    Response Type

    + +

    Parameters

    +
      + +
    + +

    placeOrder

    +
    +

    +

    +

    URL

    + http://petstore.swagger.io/v2/store/order +

    HTTP Method

    + POST +

    Response Type

    + +

    Parameters

    +
      + +
      + + + + +

      order placed for purchasing the pet

      +
      + +
    + +

    getOrderById

    +
    +

    +

    For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions

    +

    URL

    + http://petstore.swagger.io/v2/store/order/{orderId} +

    HTTP Method

    + GET +

    Response Type

    + +

    Parameters

    +
      + +
      + + + + +

      ID of pet that needs to be fetched

      +
      + +
    + +

    deleteOrder

    +
    +

    +

    For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors

    +

    URL

    + http://petstore.swagger.io/v2/store/order/{orderId} +

    HTTP Method

    + DELETE +

    Response Type

    +
    +

    Parameters

    +
      + +
      + + + + +

      ID of the order that needs to be deleted

      +
      + +
    + + +
    \ No newline at end of file diff --git a/samples/dynamic-html/docs/operations/UserApi.html b/samples/dynamic-html/docs/operations/UserApi.html new file mode 100644 index 000000000000..cc573089bceb --- /dev/null +++ b/samples/dynamic-html/docs/operations/UserApi.html @@ -0,0 +1,206 @@ +
    +

    +

    This is the API

    + + + +

    createUser

    +
    +

    +

    This can only be done by the logged in user.

    +

    URL

    + http://petstore.swagger.io/v2/user +

    HTTP Method

    + POST +

    Response Type

    +
    +

    Parameters

    +
      + +
      + + + + +

      Created user object

      +
      + +
    + +

    createUsersWithArrayInput

    +
    +

    +

    +

    URL

    + http://petstore.swagger.io/v2/user/createWithArray +

    HTTP Method

    + POST +

    Response Type

    +
    +

    Parameters

    +
      + +
      + + + + + + + +

      List of user object

      +
      + +
    + +

    createUsersWithListInput

    +
    +

    +

    +

    URL

    + http://petstore.swagger.io/v2/user/createWithList +

    HTTP Method

    + POST +

    Response Type

    +
    +

    Parameters

    +
      + +
      + + + + + + + +

      List of user object

      +
      + +
    + +

    loginUser

    +
    +

    +

    +

    URL

    + http://petstore.swagger.io/v2/user/login +

    HTTP Method

    + GET +

    Response Type

    + +

    Parameters

    +
      + +
      + + + + +

      The user name for login

      +
      + +
      + + + + +

      The password for login in clear text

      +
      + +
    + +

    logoutUser

    +
    +

    +

    +

    URL

    + http://petstore.swagger.io/v2/user/logout +

    HTTP Method

    + GET +

    Response Type

    +
    +

    Parameters

    +
      + +
    + +

    getUserByName

    +
    +

    +

    +

    URL

    + http://petstore.swagger.io/v2/user/{username} +

    HTTP Method

    + GET +

    Response Type

    + +

    Parameters

    +
      + +
      + + + + +

      The name that needs to be fetched. Use user1 for testing.

      +
      + +
    + +

    updateUser

    +
    +

    +

    This can only be done by the logged in user.

    +

    URL

    + http://petstore.swagger.io/v2/user/{username} +

    HTTP Method

    + PUT +

    Response Type

    +
    +

    Parameters

    +
      + +
      + + + + +

      name that need to be deleted

      +
      + +
      + + + + +

      Updated user object

      +
      + +
    + +

    deleteUser

    +
    +

    +

    This can only be done by the logged in user.

    +

    URL

    + http://petstore.swagger.io/v2/user/{username} +

    HTTP Method

    + DELETE +

    Response Type

    +
    +

    Parameters

    +
      + +
      + + + + +

      The name that needs to be deleted

      +
      + +
    + + +
    \ No newline at end of file diff --git a/samples/swagger-static-docs/main.js b/samples/dynamic-html/main.js similarity index 99% rename from samples/swagger-static-docs/main.js rename to samples/dynamic-html/main.js index 06c3995110ed..45a7221546fb 100644 --- a/samples/swagger-static-docs/main.js +++ b/samples/dynamic-html/main.js @@ -5,4 +5,3 @@ var docs_handler = express.static(__dirname + '/docs/'); app.use(docs_handler); // start the server app.listen(8002); - diff --git a/samples/swagger-static-docs/package.json b/samples/dynamic-html/package.json similarity index 99% rename from samples/swagger-static-docs/package.json rename to samples/dynamic-html/package.json index a24f93457a8c..d728e9f00639 100644 --- a/samples/swagger-static-docs/package.json +++ b/samples/dynamic-html/package.json @@ -10,4 +10,3 @@ }, "license": "apache 2.0" } - diff --git a/samples/html/index.html b/samples/html/index.html new file mode 100644 index 000000000000..0efac5d4bee9 --- /dev/null +++ b/samples/html/index.html @@ -0,0 +1,655 @@ + + + + API Reference + + + +

    Swagger Petstore

    +
    This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters for our Partner
    + +
    Contact Info: apiteam@wordnik.com
    +
    Apache 2.0
    +
    http://www.apache.org/licenses/LICENSE-2.0.html
    +

    Access

    +
    Access to the API requires an api key to be provided by our Partner for all requests. The api key is passed as a header with the name `api_key` and the value provided by Reverb Technologies, Inc. Unless otherwise agreed upon, access to the Reverb API is intended solely for usage by our Partner and not third parties.
    +

    Methods

    + + + +
    +
    post: /user
    +
    createUser Create user
    +
    This can only be done by the logged in user.
    + +

    Parameters

    +
    +
    body (optional)
    + +
    Body Parameter — Created user object
    + +
    +

    Return type

    + +
    + + +
    +
    + +
    +
    post: /user/createWithArray
    +
    createUsersWithArrayInput Creates list of users with given input array
    +
    + +

    Parameters

    +
    +
    body (optional)
    + +
    Body Parameter — List of user object
    + +
    +

    Return type

    + +
    + + +
    +
    + +
    +
    post: /user/createWithList
    +
    createUsersWithListInput Creates list of users with given input array
    +
    + +

    Parameters

    +
    +
    body (optional)
    + +
    Body Parameter — List of user object
    + +
    +

    Return type

    + +
    + + +
    +
    + +
    +
    get: /user/login
    +
    loginUser Logs user into the system
    +
    + +

    Parameters

    +
    +
    username (optional)
    + +
    Query Parameter — The user name for login
    +
    password (optional)
    + +
    Query Parameter — The password for login in clear text
    + +
    +

    Return type

    + + + + +
    +
    + +
    +
    get: /user/logout
    +
    logoutUser Logs out current logged in user session
    +
    + +

    Parameters

    +
    + +
    +

    Return type

    + +
    + + +
    +
    + +
    +
    get: /user/{username}
    +
    getUserByName Get user by user name
    +
    + +

    Parameters

    +
    +
    username (required)
    + +
    Path Parameter — The name that needs to be fetched. Use user1 for testing.
    + +
    +

    Return type

    + + + + +
    +
    + +
    +
    put: /user/{username}
    +
    updateUser Updated user
    +
    This can only be done by the logged in user.
    + +

    Parameters

    +
    +
    username (required)
    + +
    Path Parameter — name that need to be deleted
    +
    body (optional)
    + +
    Body Parameter — Updated user object
    + +
    +

    Return type

    + +
    + + +
    +
    + +
    +
    delete: /user/{username}
    +
    deleteUser Delete user
    +
    This can only be done by the logged in user.
    + +

    Parameters

    +
    +
    username (required)
    + +
    Path Parameter — The name that needs to be deleted
    + +
    +

    Return type

    + +
    + + +
    +
    + + + +
    +
    get: /store/inventory
    +
    getInventory Returns pet inventories by status
    +
    Returns a map of status codes to quantities
    + +

    Parameters

    +
    + +
    +

    Return type

    + + + + +
    +
    + +
    +
    post: /store/order
    +
    placeOrder Place an order for a pet
    +
    + +

    Parameters

    +
    +
    body (optional)
    + +
    Body Parameter — order placed for purchasing the pet
    + +
    +

    Return type

    + + + + +
    +
    + +
    +
    get: /store/order/{orderId}
    +
    getOrderById Find purchase order by ID
    +
    For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
    + +

    Parameters

    +
    +
    orderId (required)
    + +
    Path Parameter — ID of pet that needs to be fetched
    + +
    +

    Return type

    + + + + +
    +
    + +
    +
    delete: /store/order/{orderId}
    +
    deleteOrder Delete purchase order by ID
    +
    For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
    + +

    Parameters

    +
    +
    orderId (required)
    + +
    Path Parameter — ID of the order that needs to be deleted
    + +
    +

    Return type

    + +
    + + +
    +
    + + + +
    +
    put: /pet
    +
    updatePet Update an existing pet
    +
    + +

    Parameters

    +
    +
    body (optional)
    + +
    Body Parameter — Pet object that needs to be added to the store
    + +
    +

    Return type

    + +
    + + +
    +
    + +
    +
    post: /pet
    +
    addPet Add a new pet to the store
    +
    + +

    Parameters

    +
    +
    body (optional)
    + +
    Body Parameter — Pet object that needs to be added to the store
    + +
    +

    Return type

    + +
    + + +
    +
    + +
    +
    get: /pet/findByStatus
    +
    findPetsByStatus Finds Pets by status
    +
    Multiple status values can be provided with comma seperated strings
    + +

    Parameters

    +
    +
    status (optional)
    + +
    Query Parameter — Status values that need to be considered for filter
    + +
    +

    Return type

    + + + + +
    +
    + +
    +
    get: /pet/findByTags
    +
    findPetsByTags Finds Pets by tags
    +
    Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
    + +

    Parameters

    +
    +
    tags (optional)
    + +
    Query Parameter — Tags to filter by
    + +
    +

    Return type

    + + + + +
    +
    + +
    +
    get: /pet/{petId}
    +
    getPetById Find pet by ID
    +
    Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions
    + +

    Parameters

    +
    +
    petId (required)
    + +
    Path Parameter — ID of pet that needs to be fetched
    + +
    +

    Return type

    + + + + +
    +
    + +
    +
    post: /pet/{petId}
    +
    updatePetWithForm Updates a pet in the store with form data
    +
    + +

    Parameters

    +
    +
    petId (required)
    + +
    Path Parameter — ID of pet that needs to be updated
    +
    name (optional)
    + +
    Form Parameter — Updated name of the pet
    +
    status (optional)
    + +
    Form Parameter — Updated status of the pet
    + +
    +

    Return type

    + +
    + + +
    +
    + +
    +
    delete: /pet/{petId}
    +
    deletePet Deletes a pet
    +
    + +

    Parameters

    +
    +
    api_key (optional)
    + +
    Header Parameter
    +
    petId (required)
    + +
    Path Parameter — Pet id to delete
    + +
    +

    Return type

    + +
    + + +
    +
    + +
    +
    post: /pet/{petId}/uploadImage
    +
    uploadFile uploads an image
    +
    + +

    Parameters

    +
    +<<<<<<< HEAD +======= +
    petId (required)
    + +
    Path Parameter — ID of pet to update
    +>>>>>>> master +
    additionalMetadata (optional)
    + +
    Form Parameter — Additional data to pass to server
    +
    file (optional)
    + +
    Form Parameter — file to upload
    + +
    +

    Return type

    + +
    + + +
    +
    + + + +

    Models

    + + +
    +

    User

    +
    +
    id
    Long
    +
    username
    String
    +
    firstName
    String
    +
    lastName
    String
    +
    email
    String
    +
    password
    String
    +
    phone
    String
    +
    userStatus
    Integer User Status
    + +
    +
    + + + +
    +

    Category

    +
    +
    id
    Long
    +
    name
    String
    + +
    +
    + + + +
    +

    Pet

    +
    +
    id
    Long
    +
    category
    Category
    +
    name
    String
    +
    photoUrls
    array[String]
    +
    tags
    array[Tag]
    +
    status
    String pet status in the store
    + +
    +
    + + + +
    +

    Tag

    +
    +
    id
    Long
    +
    name
    String
    + +
    +
    + + + +
    +

    Order

    +
    +
    id
    Long
    +
    petId
    Long
    +
    quantity
    Integer
    +
    shipDate
    Date
    +
    status
    String Order Status
    +
    complete
    Boolean
    + +
    +
    + + + + + \ No newline at end of file diff --git a/samples/server-generator/java-jaxrs/JavaJaxRSServerGenerator.scala b/samples/server-generator/java-jaxrs/JavaJaxRSServerGenerator.scala deleted file mode 100644 index 8c68a77dd899..000000000000 --- a/samples/server-generator/java-jaxrs/JavaJaxRSServerGenerator.scala +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicJavaGenerator - -import scala.collection.mutable.{ HashMap, ListBuffer } - -object JavaJaxRSServerGenerator extends BasicJavaGenerator { - def main(args: Array[String]) = generateClient(args) - - override def templateDir = "samples/server-generator/java-jaxrs/templates" - - val outputFolder = "samples/server-generator/java-jaxrs/output" - - // where to write generated code - override def destinationDir = outputFolder + "/src/main/java" - - override def modelPackage = Some("com.wordnik.client.model") - - // template used for apis - apiTemplateFiles ++= Map("api.mustache" -> ".java") - - modelTemplateFiles ++= Map("model.mustache" -> ".java") - - override def apiPackage = Some("com.wordnik.api") - - // supporting classes - override def supportingFiles = List( - ("README.mustache", outputFolder, "README.md"), - ("ApiException.mustache", destinationDir + "/" + apiPackage.get.replaceAll("\\.", "/"), "ApiException.java"), - ("ApiOriginFilter.mustache", destinationDir + "/" + apiPackage.get.replaceAll("\\.", "/"), "ApiOriginFilter.java"), - ("ApiResponse.mustache", destinationDir + "/" + apiPackage.get.replaceAll("\\.", "/"), "ApiResponse.java"), - ("JacksonJsonProvider.mustache", destinationDir + "/" + apiPackage.get.replaceAll("\\.", "/"), "JacksonJsonProvider.java"), - ("NotFoundException.mustache", destinationDir + "/" + apiPackage.get.replaceAll("\\.", "/"), "NotFoundException.java"), - ("pom.xml", outputFolder, "pom.xml"), - ("web.mustache", outputFolder + "/src/main/webapp/WEB-INF", "web.xml") - ) - - override def processApiMap(m: Map[String, AnyRef]): Map[String, AnyRef] = { - val mutable = scala.collection.mutable.Map() ++ m - - mutable.map(k => { - k._1 match { - case "allParams" => { - val paramList = k._2.asInstanceOf[List[_]] - paramList.foreach(param => { - val map = param.asInstanceOf[scala.collection.mutable.HashMap[String, AnyRef]] - if(map.contains("dataType")){ - val dataType = map("dataType") - map += "dataType" -> dataType.toString.replaceAll("Array\\[","List[") - } - if(map.contains("required")) { - if(map("required") == "false") map += "notRequired" -> "true" - } - if(map.contains("defaultValue")) { - // unquote default value - val defaultValue = { - map("defaultValue") match { - case Some(d) => { - val str = d.toString - if(str.startsWith("\"") && str.endsWith("\"")) - Some(str.substring(1, str.length-1)) - else Some(d) - } - case None => None - } - } - map += "defaultValue" -> defaultValue - } - if(map.contains("allowableValues")) { - val allowableValues = map("allowableValues") - val quote = map("swaggerDataType") match { - case "string" => "\"" - case _ => "" - } - val pattern = "([A-Z]*)\\[(.*)\\]".r - val str = allowableValues match { - case pattern(valueType, values) => { - valueType match { - case "LIST" => { - val l = values.split(",").toList - Some("AllowableValues(" + l.mkString(quote, quote + "," + quote, quote + ")")) - } - case "RANGE" => { - val r = values.split(",") - Some("AllowableValues(Range(" + r(0) + "," + r(1) + ", 1))") - } - } - } - case _ => None - } - str match { - case Some(s) => map += "allowableValues" -> s - case _ => - } - } - }) - } - case "path" => { - val path = { - val arr = k._2.toString.split("/") - if (arr.length >= 2) { - mutable += "basePart" -> (arr.slice(2, arr.length).mkString("", "/", "")) - "/" + arr.slice(2, arr.length).mkString("", "/", "") - } else - k._2.toString - } - // rip out the root path - mutable += "path" -> path - } - case "returnType" => { - k._2 match { - case Some(returnType) => - case None => mutable += "returnType" -> "void" - } - } - case _ => - } - }) - mutable.toMap - } -} diff --git a/samples/server-generator/java-jaxrs/README.md b/samples/server-generator/java-jaxrs/README.md deleted file mode 100644 index f35d2b55614d..000000000000 --- a/samples/server-generator/java-jaxrs/README.md +++ /dev/null @@ -1,80 +0,0 @@ -# Swagger generated server - -## Overview -Using the swagger-codegen, you can not only generate clients but servers as well! The same spec can be used to drive your -development both ways. This is an example of generating a server for `JAX-RS`. - -### Prerequisites -You need the following installed and available in your $PATH: - -
  • Maven 3
  • - -### Generating a server -You first need to build the `swagger-codegen` project--this is done by running this command at the root of the swagger-codegen project: - -``` -sbt assembly -``` - -You can now generate a server from any valid[**](https://github.com/wordnik/swagger-codegen/blob/master/README.md#validating-your-swagger-spec) swagger spec: - -``` -./bin/runscala.sh samples/server-generator/java-jaxrs/JavaJaxRSServerGenerator.scala http://petstore.swagger.wordnik.com/api/api-docs special-key -``` - -After executing this script, you will have an output directory with the server-generated files: - -``` -$ cd samples/server-generator/java-jaxrs/output -$ find . -./pom.xml -./README.md -./src -./src/main -./src/main/java -./src/main/java/com -./src/main/java/com/wordnik -./src/main/java/com/wordnik/api -./src/main/java/com/wordnik/api/ApiException.java -./src/main/java/com/wordnik/api/ApiResponse.java -./src/main/java/com/wordnik/api/JacksonJsonProvider.java -./src/main/java/com/wordnik/api/NotFoundException.java -./src/main/java/com/wordnik/api/PetApi.java -./src/main/java/com/wordnik/api/StoreApi.java -./src/main/java/com/wordnik/api/UserApi.java -./src/main/java/com/wordnik/client -./src/main/java/com/wordnik/client/model -./src/main/java/com/wordnik/client/model/Category.java -./src/main/java/com/wordnik/client/model/Order.java -./src/main/java/com/wordnik/client/model/Pet.java -./src/main/java/com/wordnik/client/model/Tag.java -./src/main/java/com/wordnik/client/model/User.java -./src/main/webapp -./src/main/webapp/WEB-INF -./src/main/webapp/WEB-INF/web.xml - -``` - -To run the server, cd to the `samples/server-generator/java-jaxrs/output` folder and run: - -``` -mvn jetty:run -``` - -You can now load the swagger-ui against `http://localhost:8002/api/api-docs.json`. Of course this isn't a fully -runnable server! You have to add the logic in the **/api/*.java files. But that's the easy part. - -### Making it your own -Running the sample is easy, but how about making your own server? Easy! Just modify the `samples/server-generator/java-jaxrs/JavaJaxRSServerGenerator.scala` file. - -Don't like the templates? Don't worry, we're not offended! They're [mustache](http://mustache.github.com/) templates and are easy to modify. -Take a look at the sample templates here: - -
  • - Generator for your api classes: [api.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/java-jaxrs/templates/api.mustache) - -
  • - Generator for your models: [model.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/java-jaxrs/templates/model.mustache) - -
  • - Your web.xml: [web.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/java-jaxrs/templates/web.mustache) - - -Sound easy? It is! \ No newline at end of file diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/JacksonJsonProvider.java b/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/JacksonJsonProvider.java deleted file mode 100644 index aa43fb8bd29b..000000000000 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/JacksonJsonProvider.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.wordnik.api; - -import com.wordnik.swagger.core.util.JsonUtil; - -import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; -import com.fasterxml.jackson.databind.*; - -import com.fasterxml.jackson.core.JsonGenerator.Feature; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import javax.ws.rs.Produces; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.ext.Provider; - -@Provider -@Produces(MediaType.APPLICATION_JSON) -public class JacksonJsonProvider extends JacksonJaxbJsonProvider { - private static ObjectMapper commonMapper = null; - - public JacksonJsonProvider() { - if(commonMapper == null){ - ObjectMapper mapper = new ObjectMapper(); - - 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); - - commonMapper = mapper; - } - super.setMapper(commonMapper); - } - - -} diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/PetApi.java b/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/PetApi.java deleted file mode 100644 index b026f2f4c2a9..000000000000 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/PetApi.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.wordnik.api; - -import com.wordnik.swagger.annotations.*; - -import com.wordnik.client.model.Pet; -import java.util.List; -import com.wordnik.api.NotFoundException; - -import javax.ws.rs.core.Response; -import javax.ws.rs.*; - -@Path("/pet.json") -@Api(value = "/pet", description = "the pet API") -@Produces({"application/json"}) -public class PetApi { - @GET - @Path("/{petId}") - @ApiOperation(value = "Find pet by ID", notes = "Returns a pet based on ID", responseClass = "Pet") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response getPetById( - @ApiParam(value = "ID of pet that needs to be fetched" - ,required=true)@PathParam("petId") String petId - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @POST - @Path("/") - @ApiOperation(value = "Add a new pet to the store", notes = "", responseClass = "void") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response addPet( - @ApiParam(value = "Pet object that needs to be added to the store" - ,required=true) Pet body - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @PUT - @Path("/") - @ApiOperation(value = "Update an existing pet", notes = "", responseClass = "void") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response updatePet( - @ApiParam(value = "Pet object that needs to be updated in the store" - ,required=true) Pet body - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @GET - @Path("/findByStatus") - @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", responseClass = "List") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response findPetsByStatus( - @ApiParam(value = "Status values that need to be considered for filter" - ,required=true, defaultValue="available")@QueryParam("status") String status - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @GET - @Path("/findByTags") - @ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", responseClass = "List") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response findPetsByTags( - @ApiParam(value = "Tags to filter by" - ,required=true)@QueryParam("tags") String tags - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - } - diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/StoreApi.java b/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/StoreApi.java deleted file mode 100644 index fd50ae87417c..000000000000 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/StoreApi.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.wordnik.api; - -import com.wordnik.swagger.annotations.*; - -import com.wordnik.client.model.Order; -import java.util.List; -import com.wordnik.api.NotFoundException; - -import javax.ws.rs.core.Response; -import javax.ws.rs.*; - -@Path("/store.json") -@Api(value = "/store", description = "the store API") -@Produces({"application/json"}) -public class StoreApi { - @GET - @Path("/order/{orderId}") - @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors", responseClass = "Order") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response getOrderById( - @ApiParam(value = "ID of pet that needs to be fetched" - ,required=true)@PathParam("orderId") String orderId - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @DELETE - @Path("/order/{orderId}") - @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", responseClass = "void") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response deleteOrder( - @ApiParam(value = "ID of the order that needs to be deleted" - ,required=true)@PathParam("orderId") String orderId - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @POST - @Path("/order") - @ApiOperation(value = "Place an order for a pet", notes = "", responseClass = "void") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response placeOrder( - @ApiParam(value = "order placed for purchasing the pet" - ,required=true) Order body - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - } - diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/UserApi.java b/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/UserApi.java deleted file mode 100644 index fbceb95282f6..000000000000 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/UserApi.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.wordnik.api; - -import com.wordnik.swagger.annotations.*; - -import com.wordnik.client.model.User; -import java.util.List; -import com.wordnik.api.NotFoundException; - -import javax.ws.rs.core.Response; -import javax.ws.rs.*; - -@Path("/user.json") -@Api(value = "/user", description = "the user API") -@Produces({"application/json"}) -public class UserApi { - @POST - @Path("/createWithArray") - @ApiOperation(value = "Creates list of users with given input array", notes = "", responseClass = "void") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response createUsersWithArrayInput( - @ApiParam(value = "List of user object" - ,required=true) List body - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @POST - @Path("/") - @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", responseClass = "void") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response createUser( - @ApiParam(value = "Created user object" - ,required=true) User body - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @POST - @Path("/createWithList") - @ApiOperation(value = "Creates list of users with given list input", notes = "", responseClass = "void") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response createUsersWithListInput( - @ApiParam(value = "List of user object" - ,required=true) List body - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @PUT - @Path("/{username}") - @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", responseClass = "void") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response updateUser( - @ApiParam(value = "name that need to be deleted" - ,required=true)@PathParam("username") String username - ,@ApiParam(value = "Updated user object" - ,required=true) User body - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @DELETE - @Path("/{username}") - @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", responseClass = "void") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response deleteUser( - @ApiParam(value = "The name that needs to be deleted" - ,required=true)@PathParam("username") String username - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @GET - @Path("/{username}") - @ApiOperation(value = "Get user by user name", notes = "", responseClass = "User") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response getUserByName( - @ApiParam(value = "The name that needs to be fetched. Use user1 for testing." - ,required=true)@PathParam("username") String username - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @GET - @Path("/login") - @ApiOperation(value = "Logs user into the system", notes = "", responseClass = "String") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response loginUser( - @ApiParam(value = "The user name for login" - ,required=true)@QueryParam("username") String username - ,@ApiParam(value = "The password for login in clear text" - ,required=true)@QueryParam("password") String password - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - @GET - @Path("/logout") - @ApiOperation(value = "Logs out current logged in user session", notes = "", responseClass = "void") - @ApiErrors(value = { @ApiError(code = 400, reason = "Invalid ID supplied"), - @ApiError(code = 404, reason = "Pet not found") }) - public Response logoutUser( - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - } - diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Order.java b/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Order.java deleted file mode 100644 index ae6d507f297a..000000000000 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/client/model/Order.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.wordnik.client.model; - -import java.util.Date; -public class Order { - private Long id = null; - private Long petId = null; - /* Order Status */ - private String status = null; - private Integer quantity = null; - private Date shipDate = null; - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - public Long getPetId() { - return petId; - } - public void setPetId(Long petId) { - this.petId = petId; - } - - public String getStatus() { - return status; - } - public void setStatus(String status) { - this.status = status; - } - - public Integer getQuantity() { - return quantity; - } - public void setQuantity(Integer quantity) { - this.quantity = quantity; - } - - public Date getShipDate() { - return shipDate; - } - public void setShipDate(Date shipDate) { - this.shipDate = shipDate; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Order {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" petId: ").append(petId).append("\n"); - sb.append(" status: ").append(status).append("\n"); - sb.append(" quantity: ").append(quantity).append("\n"); - sb.append(" shipDate: ").append(shipDate).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} - diff --git a/samples/server-generator/java-jaxrs/templates/JacksonJsonProvider.mustache b/samples/server-generator/java-jaxrs/templates/JacksonJsonProvider.mustache deleted file mode 100644 index 32276096eabb..000000000000 --- a/samples/server-generator/java-jaxrs/templates/JacksonJsonProvider.mustache +++ /dev/null @@ -1,38 +0,0 @@ -package {{apiPackage}}; - -import com.wordnik.swagger.core.util.JsonUtil; - -import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider; -import com.fasterxml.jackson.databind.*; - -import com.fasterxml.jackson.core.JsonGenerator.Feature; -import com.fasterxml.jackson.databind.*; -import com.fasterxml.jackson.annotation.*; -import com.fasterxml.jackson.databind.annotation.JsonSerialize; - -import javax.ws.rs.Produces; - -import javax.ws.rs.core.MediaType; -import javax.ws.rs.ext.Provider; - -@Provider -@Produces(MediaType.APPLICATION_JSON) -public class JacksonJsonProvider extends JacksonJaxbJsonProvider { - private static ObjectMapper commonMapper = null; - - public JacksonJsonProvider() { - if(commonMapper == null){ - ObjectMapper mapper = new ObjectMapper(); - - 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); - - commonMapper = mapper; - } - super.setMapper(commonMapper); - } - - -} \ No newline at end of file diff --git a/samples/server-generator/java-jaxrs/templates/api.mustache b/samples/server-generator/java-jaxrs/templates/api.mustache deleted file mode 100644 index f704af8c38bb..000000000000 --- a/samples/server-generator/java-jaxrs/templates/api.mustache +++ /dev/null @@ -1,77 +0,0 @@ -package {{package}}; - -import com.wordnik.swagger.annotations.*; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.util.List; -import {{package}}.NotFoundException; - -import javax.ws.rs.core.Response; -import javax.ws.rs.*; - -@Path("/{{baseName}}.json") -@Api(value = "/{{baseName}}", description = "the {{baseName}} API") -@Produces({"application/json"}) -public class {{className}} { - {{#operations}} - {{#operation}} - @{{httpMethod}} - @Path("{{path}}") - @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", responseClass = "{{{returnType}}}") - @ApiErrors(value = { {{#errorList}} @ApiError(code = {{{code}}}, reason = "{{{reason}}}"){{#hasMore}},{{/hasMore}} - {{/errorList}} - }) - - public Response {{nickname}}( - {{#allParams}} - {{#queryParameter}} - @ApiParam(value = "{{{description}}}" - {{#required}},required=true{{newline}}{{/required}} - {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}} - {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}} - - )@QueryParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}} - {{/queryParameter}} - - {{#pathParameter}} - @ApiParam(value = "{{{description}}}" - {{#required}},required=true{{newline}}{{/required}} - {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}} - {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}} - - )@PathParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}} - {{/pathParameter}} - - {{#headerParameter}} - @ApiParam(value = "{{{description}}}" - {{#required}},required=true{{newline}}{{/required}} - {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}} - {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}} - - )@HeaderParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}} - {{/headerParameter}} - - {{#bodyParameter}} - @ApiParam(value = "{{{description}}}" - {{#required}},required=true{{newline}}{{/required}} - {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}} - {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}} - - ) {{{dataType}}} {{paramName}} - {{/bodyParameter}} - - - {{#hasMore}},{{/hasMore}} - {{/allParams}} - - ) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponse(ApiResponse.OK, "magic!")).build(); - } - - {{/operation}} - {{/operations}} -} diff --git a/samples/server-generator/java-jaxrs/templates/model.mustache b/samples/server-generator/java-jaxrs/templates/model.mustache deleted file mode 100644 index f4472d468974..000000000000 --- a/samples/server-generator/java-jaxrs/templates/model.mustache +++ /dev/null @@ -1,38 +0,0 @@ -package {{package}}; - -{{#imports}}import {{import}}; -{{/imports}} -{{#models}} -{{#model}} -public class {{classname}} { - {{#vars}} - - {{#description}}/* {{{description}}} */ - {{/description}} - private {{{datatype}}} {{name}} = {{{defaultValue}}}; - {{/vars}} - - {{#vars}} - - public {{{datatype}}} {{getter}}() { - return {{name}}; - } - public void {{setter}}({{{datatype}}} {{name}}) { - this.{{name}} = {{name}}; - } - - {{/vars}} - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class {{classname}} {\n"); - {{#vars}} - sb.append(" {{name}}: ").append({{name}}).append("\n"); - {{/vars}} - sb.append("}\n"); - return sb.toString(); - } -} -{{/model}} -{{/models}} \ No newline at end of file diff --git a/samples/server-generator/node/NodeServerFromSpec.scala b/samples/server-generator/node/NodeServerFromSpec.scala deleted file mode 100644 index 4661c35816cb..000000000000 --- a/samples/server-generator/node/NodeServerFromSpec.scala +++ /dev/null @@ -1,54 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicScalaGenerator - -import scala.collection.mutable.{ HashMap, ListBuffer } - -object NodeServerGenerator extends BasicScalaGenerator { - def main(args: Array[String]) = generateClient(args) - val codeDir = "app" - val apiDir = "apis" - - override def templateDir = "samples/server-generator/node/templates" - - val outputFolder = "samples/server-generator/node/output" - - // where to write generated code - override def destinationDir = outputFolder + java.io.File.separator + codeDir - - override def apiPackage = Option(apiDir) - - // template used for apis - apiTemplateFiles ++= Map("api.mustache" -> ".js") - - modelTemplateFiles.clear - - additionalParams ++= Map( - "artifactId" -> "swagger-sample-app", - "artifactVersion" -> "1.0.0", - "homepage" -> "http://swagger.wordnik.com", - "codeDir" -> codeDir, - "apiFolder" -> apiDir - ) - - // supporting classes - override def supportingFiles = List( - ("package.mustache", outputFolder, "package.json"), - ("README.mustache", outputFolder, "README.md"), - ("main.mustache", destinationDir, "main.js"), - ("models.mustache", destinationDir, "models.js")) -} diff --git a/samples/server-generator/node/output/App/main.js b/samples/server-generator/node/output/App/main.js deleted file mode 100644 index 77c098aa12de..000000000000 --- a/samples/server-generator/node/output/App/main.js +++ /dev/null @@ -1,58 +0,0 @@ -var express = require("express") - , url = require("url") - , cors = require("cors") - , swagger = require("swagger-node-express") - , db = false - -var app = express(); -app.use(express.bodyParser()); - -var corsOptions = { - credentials: true, - origin: function(origin,callback) { - if(origin===undefined) { - callback(null,false); - } else { - callback(null,true); - } - } -}; - -app.use(cors(corsOptions)); - -swagger.setAppHandler(app); -swagger.configureSwaggerPaths("", "api-docs", "") - -var models = require("./models.js"); - -var UserApi = require("./apis/UserApi.js"); -var PetApi = require("./apis/PetApi.js"); -var StoreApi = require("./apis/StoreApi.js"); -swagger.addModels(models) - .addPUT(UserApi.updateUser) -.addDELETE(UserApi.deleteUser) -.addGET(UserApi.getUserByName) -.addGET(UserApi.loginUser) -.addGET(UserApi.logoutUser) -.addPOST(UserApi.createUser) -.addPOST(UserApi.createUsersWithArrayInput) -.addPOST(UserApi.createUsersWithListInput) -.addGET(PetApi.getPetById) -.addDELETE(PetApi.deletePet) -.addPATCH(PetApi.partialUpdate) -.addPOST(PetApi.updatePetWithForm) -.addPOST(PetApi.uploadFile) -.addPOST(PetApi.addPet) -.addPUT(PetApi.updatePet) -.addGET(PetApi.findPetsByStatus) -.addGET(PetApi.findPetsByTags) -.addGET(StoreApi.getOrderById) -.addDELETE(StoreApi.deleteOrder) -.addPOST(StoreApi.placeOrder) -; - // configures the app -swagger.configure("http://localhost:8002", "0.1"); - -// start the server -app.listen(8002); - diff --git a/samples/server-generator/node/output/README.md b/samples/server-generator/node/output/README.md deleted file mode 100644 index e53b82dfcc5d..000000000000 --- a/samples/server-generator/node/output/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# Swagger generated server - -## Overview -This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the -[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a node.js server. - -This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: - -[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/node) diff --git a/samples/server-generator/node/templates/README.mustache b/samples/server-generator/node/templates/README.mustache deleted file mode 100644 index 881e7dd92c57..000000000000 --- a/samples/server-generator/node/templates/README.mustache +++ /dev/null @@ -1,10 +0,0 @@ -# Swagger generated server - -## Overview -This server was generated by the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. By using the -[swagger-spec](https://github.com/wordnik/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a node.js server. - -This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: - -[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/node) \ No newline at end of file diff --git a/samples/server-generator/node/templates/main.mustache b/samples/server-generator/node/templates/main.mustache deleted file mode 100644 index 2763d779a9ce..000000000000 --- a/samples/server-generator/node/templates/main.mustache +++ /dev/null @@ -1,47 +0,0 @@ -var express = require("express") - , url = require("url") - , cors = require("cors") - , swagger = require("swagger-node-express") - , db = false - -var app = express(); -app.use(express.bodyParser()); - -var corsOptions = { - credentials: true, - origin: function(origin,callback) { - if(origin===undefined) { - callback(null,false); - } else { - callback(null,true); - } - } -}; - -app.use(cors(corsOptions)); - -swagger.setAppHandler(app); -swagger.configureSwaggerPaths("", "api-docs", "") - -var models = require("./models.js"); - -{{#apiInfo}} -{{#apis}} -var {{name}} = require("./{{apiFolder}}/{{classname}}.js"); -{{/apis}} -{{/apiInfo}} - -swagger.addModels(models) - {{#apiInfo}} - {{#apis}} - {{#operations}} - {{#operation}}.add{{httpMethod}}({{name}}.{{nickname}}){{newline}}{{/operation}} - {{/operations}} - {{/apis}}; - {{/apiInfo}} - -// configures the app -swagger.configure("http://localhost:8002", "0.1"); - -// start the server -app.listen(8002); diff --git a/samples/server-generator/node/templates/models.mustache b/samples/server-generator/node/templates/models.mustache deleted file mode 100644 index de84fc3f6d7d..000000000000 --- a/samples/server-generator/node/templates/models.mustache +++ /dev/null @@ -1,7 +0,0 @@ -exports.models = { - {{#models}} - {{#model}} - "{{classVarName}}": {{{modelJson}}}{{#hasMoreModels}},{{/hasMoreModels}}{{newline}} - {{/model}} - {{/models}} -} \ No newline at end of file diff --git a/samples/server-generator/scalatra/README.md b/samples/server-generator/scalatra/README.md deleted file mode 100644 index 74622f30805f..000000000000 --- a/samples/server-generator/scalatra/README.md +++ /dev/null @@ -1,76 +0,0 @@ -# Swagger generated server - -## Overview -Using the swagger-codegen, you can not only generate clients but servers as well! The same spec can be used to drive your -development both ways. This is an example of generating a server for `scalatra`. - -### Prerequisites -You need the following installed and available in your $PATH: - -
  • - sbt 0.12 (http://www.scala-sbt.org/) - -
  • - Scala 2.10.0 [available here](http://www.scala-lang.org) - -You also need to add the scala binary to your PATH. - -### Generating a server -You first need to build the `swagger-codegen` project--this is done by running this command at the root of the swagger-codegen project: - -``` -./sbt assembly -``` - -You can now generate a server from any valid[**](https://github.com/wordnik/swagger-codegen/blob/master/README.md#validating-your-swagger-spec) swagger spec: - -``` -./bin/runscala.sh samples/server-generator/scalatra/ScalatraServerGenerator.scala http://petstore.swagger.wordnik.com/api/api-docs special-key -``` - -After executing this script, you will have an output directory with the server-generated files: - -``` -$ cd samples/server-generator/scalatra/output -$ find -type f -./project/build.properties -./project/plugins.sbt -./README.md -./src/main/scala/apis/PetApi.scala -./src/main/scala/apis/StoreApi.scala -./src/main/scala/apis/UserApi.scala -./src/main/scala/com/wordnik/client/model/Category.scala -./src/main/scala/com/wordnik/client/model/Order.scala -./src/main/scala/com/wordnik/client/model/Pet.scala -./src/main/scala/com/wordnik/client/model/Tag.scala -./src/main/scala/com/wordnik/client/model/User.scala -./src/main/scala/JsonUtil.scala -./src/main/scala/ServletApp.scala - -``` - -To run the server, cd to the `samples/server-generator/scalatra/output` folder and run: - -``` -chmod a+x ./sbt - -./sbt - -> container:start -``` - -You can now load the swagger-ui against `http://localhost:8080/api-docs`. Of course this isn't a fully -runnable server! You have to add the logic in the apis/*.scala files. But that's the easy part. - -### Making it your own -Running the sample is easy, but how about making your own server? Easy! Just modify the `samples/server-generator/scalatra/ScalatraServerGenerator.scala` file. - -Don't like the templates? Don't worry, we're not offended! They're [mustache](http://mustache.github.com/) templates and are easy to modify. -Take a look at the sample templates here: - -
  • - Generator for your api classes: [api.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/scalatra/templates/api.mustache) - -
  • - Generator for your models: [model.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/scalatra/templates/model.mustache) - -
  • - The main class to run your server: [ServletApp.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/scalatra/templates/ServletApp.mustache) - - -Sound easy? It is! \ No newline at end of file diff --git a/samples/server-generator/scalatra/ScalatraServerGenerator.scala b/samples/server-generator/scalatra/ScalatraServerGenerator.scala deleted file mode 100644 index aa2375088597..000000000000 --- a/samples/server-generator/scalatra/ScalatraServerGenerator.scala +++ /dev/null @@ -1,127 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicScalaGenerator - -import scala.collection.mutable.{ HashMap, ListBuffer } - -object ScalatraServerGenerator extends BasicScalaGenerator { - def main(args: Array[String]) = generateClient(args) - - override def templateDir = "samples/server-generator/scalatra/templates" - - val outputFolder = "samples/server-generator/scalatra/output" - - // where to write generated code - override def destinationDir = outputFolder + "/src/main/scala" - - override def modelPackage = Some("com.wordnik.client.model") - - // template used for apis - apiTemplateFiles ++= Map("api.mustache" -> ".scala") - - modelTemplateFiles ++= Map("model.mustache" -> ".scala") - - override def apiPackage = Some("apis") - - additionalParams ++= Map( - "appName" -> "Swagger Sample", - "appDescription" -> "A sample swagger server", - "infoUrl" -> "http://developers.helloreverb.com", - "infoEmail" -> "hello@helloreverb.com", - "licenseInfo" -> "All rights reserved", - "licenseUrl" -> "http://apache.org/licenses/LICENSE-2.0.html") - - // supporting classes - override def supportingFiles = List( - ("README.mustache", outputFolder, "README.md"), - ("build.sbt", outputFolder, "build.sbt"), - ("web.xml", outputFolder + "/src/main/webapp/WEB-INF", "web.xml"), - ("JettyMain.scala", outputFolder + "/src/main/scala", "JettyMain.scala"), - ("Bootstrap.mustache", destinationDir, "ScalatraBootstrap.scala"), - ("ServletApp.mustache", destinationDir, "ServletApp.scala"), - ("project/build.properties", outputFolder, "project/build.properties"), - ("project/plugins.sbt", outputFolder, "project/plugins.sbt"), - ("sbt", outputFolder, "sbt")) - - override def processApiMap(m: Map[String, AnyRef]): Map[String, AnyRef] = { - val mutable = scala.collection.mutable.Map() ++ m - - mutable.map(k => { - k._1 match { - case "allParams" => { - val paramList = k._2.asInstanceOf[List[_]] - paramList.foreach(param => { - val map = param.asInstanceOf[scala.collection.mutable.HashMap[String, AnyRef]] - if(map.contains("dataType")){ - val dataType = map("dataType") - map += "dataType" -> dataType.toString.replaceAll("Array\\[","List[") - } - if(map.contains("required")) { - if(map("required") == "false") map += "notRequired" -> "true" - } - if(map.contains("allowableValues")) { - val allowableValues = map("allowableValues") - val quote = map("swaggerDataType") match { - case "string" => "\"" - case _ => "" - } - val pattern = "([A-Z]*)\\[(.*)\\]".r - val str = allowableValues match { - case pattern(valueType, values) => { - valueType match { - case "LIST" => { - val l = values.split(",").toList - Some("AllowableValues(" + l.mkString(quote, quote + "," + quote, quote + ")")) - } - case "RANGE" => { - val r = values.split(",") - Some("AllowableValues(Range(" + r(0) + "," + r(1) + ", 1))") - } - } - } - case _ => None - } - str match { - case Some(s) => map += "allowableValues" -> s - case _ => - } - } - }) - } - - // the scalatra templates like lower-case httpMethods - case "httpMethod" => mutable += "httpMethod" -> k._2.toString.toLowerCase - - // convert path into ruby-ish syntax without basePart (i.e. /pet.{format}/{petId} => /:petId - case "path" => { - val path = { - val arr = k._2.toString.split("/") - if (arr.length >= 2) { - mutable += "basePart" -> (arr.slice(2, arr.length).mkString("", "/", "")) - "/" + arr.slice(2, arr.length).mkString("", "/", "") - } else - k._2.toString - } - // rip out the root path - mutable += "path" -> path.replaceAll("\\{", ":").replaceAll("\\}", "") - } - case _ => - } - }) - mutable.toMap - } -} diff --git a/samples/server-generator/scalatra/output/project/build.properties b/samples/server-generator/scalatra/output/project/build.properties deleted file mode 100644 index 8cbb5226c451..000000000000 --- a/samples/server-generator/scalatra/output/project/build.properties +++ /dev/null @@ -1 +0,0 @@ -sbt.version=0.13.0 \ No newline at end of file diff --git a/samples/server-generator/scalatra/output/project/plugins.sbt b/samples/server-generator/scalatra/output/project/plugins.sbt deleted file mode 100644 index 94de8e5414fa..000000000000 --- a/samples/server-generator/scalatra/output/project/plugins.sbt +++ /dev/null @@ -1,7 +0,0 @@ -addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.1") - -addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "0.6.4") - -addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.6.0") - -addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.2.1") diff --git a/samples/server-generator/scalatra/output/src/main/scala/ServletApp.scala b/samples/server-generator/scalatra/output/src/main/scala/ServletApp.scala deleted file mode 100644 index acb57c31e3e7..000000000000 --- a/samples/server-generator/scalatra/output/src/main/scala/ServletApp.scala +++ /dev/null @@ -1,39 +0,0 @@ -package com.wordnik.swagger.app - -import _root_.akka.actor.ActorSystem - -import org.scalatra.swagger.{ ApiInfo, SwaggerWithAuth, Swagger } -import org.scalatra.swagger.{ JacksonSwaggerBase, Swagger } -import org.scalatra.ScalatraServlet -import org.json4s.{ DefaultFormats, Formats } - -class ResourcesApp(implicit protected val system: ActorSystem, val swagger: SwaggerApp) - extends ScalatraServlet with JacksonSwaggerBase { - before() { - response.headers += ("Access-Control-Allow-Origin" -> "*") - } - - protected def buildFullUrl(path: String) = if (path.startsWith("http")) path else { - val port = request.getServerPort - val h = request.getServerName - val prot = if (port == 443) "https" else "http" - val (proto, host) = if (port != 80 && port != 443) ("http", h + ":" + port.toString) else (prot, h) - "%s://%s%s%s".format( - proto, - host, - request.getContextPath, - path) - } -} - -class SwaggerApp extends Swagger(apiInfo = ApiSwagger.apiInfo, apiVersion = "1.0", swaggerVersion = "1.2") - -object ApiSwagger { - val apiInfo = ApiInfo( - "Swagger Sample", - "A sample swagger server", - "http://developers.helloreverb.com", - "hello@helloreverb.com", - "All rights reserved", - "http://apache.org/licenses/LICENSE-2.0.html") -} diff --git a/samples/server-generator/scalatra/output/src/main/scala/apis/PetApi.scala b/samples/server-generator/scalatra/output/src/main/scala/apis/PetApi.scala deleted file mode 100644 index bdc0222d3fd8..000000000000 --- a/samples/server-generator/scalatra/output/src/main/scala/apis/PetApi.scala +++ /dev/null @@ -1,137 +0,0 @@ -package apis - -import com.wordnik.client.model.Pet -import java.io.File - -import org.scalatra.{ TypedParamSupport, ScalatraServlet } -import org.scalatra.swagger._ -import org.json4s._ -import org.json4s.JsonDSL._ -import org.scalatra.json.{ JValueResult, JacksonJsonSupport } -import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException } - -import scala.collection.JavaConverters._ - -class PetApi(implicit val swagger: Swagger) extends ScalatraServlet - with FileUploadSupport - with JacksonJsonSupport - with SwaggerSupport { - protected implicit val jsonFormats: Formats = DefaultFormats - - protected val applicationDescription: String = "PetApi" - override protected val applicationName: Option[String] = Some("pet") - - before() { - contentType = formats("json") - response.headers += ("Access-Control-Allow-Origin" -> "*") - } - - val getPetByIdOperation = (apiOperation[Pet]("getPetById") - summary "Find pet by ID" - parameters ( - pathParam[Long]("petId").description("")) - ) - - get("/:petId", operation(getPetByIdOperation)) { - val petId = params.getOrElse("petId", halt(400)) - println("petId: " + petId) - } - - val deletePetOperation = (apiOperation[Unit]("deletePet") - summary "Deletes a pet" - parameters ( - pathParam[String]("petId").description("")) - ) - - delete("/:petId", operation(deletePetOperation)) { - val petId = params.getOrElse("petId", halt(400)) - println("petId: " + petId) - } - - val partialUpdateOperation = (apiOperation[List[Pet]]("partialUpdate") - summary "partial updates to a pet" - parameters ( - pathParam[String]("petId").description(""), bodyParam[Pet]("body").description("")) - ) - - patch("/:petId", operation(partialUpdateOperation)) { - val petId = params.getOrElse("petId", halt(400)) - println("petId: " + petId) - val body = parsedBody.extract[Pet] - println("body: " + body) - } - - val updatePetWithFormOperation = (apiOperation[Unit]("updatePetWithForm") - summary "Updates a pet in the store with form data" - parameters ( - pathParam[String]("petId").description(""), formParam[String]("name").description(""), formParam[String]("status").description("")) - ) - - post("/:petId", operation(updatePetWithFormOperation)) { - val petId = params.getOrElse("petId", halt(400)) - println("petId: " + petId) - val name = params.getAs[String]("name") - println("name: " + name) - val status = params.getAs[String]("status") - println("status: " + status) - } - - val uploadFileOperation = (apiOperation[Unit]("uploadFile") - summary "uploads an image" - parameters ( - formParam[String]("additionalMetadata").description(""), - bodyParam[File]("body").description("").optional) - ) - - post("/uploadImage", operation(uploadFileOperation)) { - val additionalMetadata = params.getAs[String]("additionalMetadata") - println("additionalMetadata: " + additionalMetadata) - val body = fileParams("body") - println("body: " + body) - } - - val addPetOperation = (apiOperation[Unit]("addPet") - summary "Add a new pet to the store" - parameters ( - bodyParam[Pet]("body").description("")) - ) - - post("/", operation(addPetOperation)) { - val body = parsedBody.extract[Pet] - println("body: " + body) - } - - val updatePetOperation = (apiOperation[Unit]("updatePet") - summary "Update an existing pet" - parameters ( - bodyParam[Pet]("body").description("")) - ) - - put("/", operation(updatePetOperation)) { - val body = parsedBody.extract[Pet] - println("body: " + body) - } - - val findPetsByStatusOperation = (apiOperation[List[Pet]]("findPetsByStatus") - summary "Finds Pets by status" - parameters ( - queryParam[String]("status").description("").defaultValue("available")) - ) - - get("/findByStatus", operation(findPetsByStatusOperation)) { - val status = params.getAs[String]("status") - println("status: " + status) - } - - val findPetsByTagsOperation = (apiOperation[List[Pet]]("findPetsByTags") - summary "Finds Pets by tags" - parameters ( - queryParam[String]("tags").description("")) - ) - - get("/findByTags", operation(findPetsByTagsOperation)) { - val tags = params.getAs[String]("tags") - println("tags: " + tags) - } - -} diff --git a/samples/server-generator/scalatra/output/src/main/scala/apis/StoreApi.scala b/samples/server-generator/scalatra/output/src/main/scala/apis/StoreApi.scala deleted file mode 100644 index 92b4629ff4f1..000000000000 --- a/samples/server-generator/scalatra/output/src/main/scala/apis/StoreApi.scala +++ /dev/null @@ -1,62 +0,0 @@ -package apis - -import com.wordnik.client.model.Order -import java.io.File - -import org.scalatra.{ TypedParamSupport, ScalatraServlet } -import org.scalatra.swagger._ -import org.json4s._ -import org.json4s.JsonDSL._ -import org.scalatra.json.{ JValueResult, JacksonJsonSupport } -import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException } - -import scala.collection.JavaConverters._ - -class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet - with FileUploadSupport - with JacksonJsonSupport - with SwaggerSupport { - protected implicit val jsonFormats: Formats = DefaultFormats - - protected val applicationDescription: String = "StoreApi" - override protected val applicationName: Option[String] = Some("store") - - before() { - contentType = formats("json") - response.headers += ("Access-Control-Allow-Origin" -> "*") - } - - val getOrderByIdOperation = (apiOperation[Order]("getOrderById") - summary "Find purchase order by ID" - parameters ( - pathParam[String]("orderId").description("")) - ) - - get("/order/:orderId", operation(getOrderByIdOperation)) { - val orderId = params.getOrElse("orderId", halt(400)) - println("orderId: " + orderId) - } - - val deleteOrderOperation = (apiOperation[Unit]("deleteOrder") - summary "Delete purchase order by ID" - parameters ( - pathParam[String]("orderId").description("")) - ) - - delete("/order/:orderId", operation(deleteOrderOperation)) { - val orderId = params.getOrElse("orderId", halt(400)) - println("orderId: " + orderId) - } - - val placeOrderOperation = (apiOperation[Unit]("placeOrder") - summary "Place an order for a pet" - parameters ( - bodyParam[Order]("body").description("")) - ) - - post("/order", operation(placeOrderOperation)) { - val body = parsedBody.extract[Order] - println("body: " + body) - } - -} diff --git a/samples/server-generator/scalatra/output/src/main/scala/apis/UserApi.scala b/samples/server-generator/scalatra/output/src/main/scala/apis/UserApi.scala deleted file mode 100644 index 8324fd0f9b83..000000000000 --- a/samples/server-generator/scalatra/output/src/main/scala/apis/UserApi.scala +++ /dev/null @@ -1,118 +0,0 @@ -package apis - -import com.wordnik.client.model.User -import java.io.File - -import org.scalatra.{ TypedParamSupport, ScalatraServlet } -import org.scalatra.swagger._ -import org.json4s._ -import org.json4s.JsonDSL._ -import org.scalatra.json.{ JValueResult, JacksonJsonSupport } -import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException } - -import scala.collection.JavaConverters._ - -class UserApi(implicit val swagger: Swagger) extends ScalatraServlet - with FileUploadSupport - with JacksonJsonSupport - with SwaggerSupport { - protected implicit val jsonFormats: Formats = DefaultFormats - - protected val applicationDescription: String = "UserApi" - override protected val applicationName: Option[String] = Some("user") - - before() { - contentType = formats("json") - response.headers += ("Access-Control-Allow-Origin" -> "*") - } - - val updateUserOperation = (apiOperation[Unit]("updateUser") - summary "Updated user" - parameters ( - pathParam[String]("username").description(""), bodyParam[User]("body").description("")) - ) - - put("/:username", operation(updateUserOperation)) { - val username = params.getOrElse("username", halt(400)) - println("username: " + username) - val body = parsedBody.extract[User] - println("body: " + body) - } - - val deleteUserOperation = (apiOperation[Unit]("deleteUser") - summary "Delete user" - parameters ( - pathParam[String]("username").description("")) - ) - - delete("/:username", operation(deleteUserOperation)) { - val username = params.getOrElse("username", halt(400)) - println("username: " + username) - } - - val getUserByNameOperation = (apiOperation[User]("getUserByName") - summary "Get user by user name" - parameters ( - pathParam[String]("username").description("")) - ) - - get("/:username", operation(getUserByNameOperation)) { - val username = params.getOrElse("username", halt(400)) - println("username: " + username) - } - - val loginUserOperation = (apiOperation[String]("loginUser") - summary "Logs user into the system" - parameters ( - queryParam[String]("username").description(""), queryParam[String]("password").description("")) - ) - - get("/login", operation(loginUserOperation)) { - val username = params.getAs[String]("username") - println("username: " + username) - val password = params.getAs[String]("password") - println("password: " + password) - } - - val logoutUserOperation = (apiOperation[Unit]("logoutUser") - summary "Logs out current logged in user session" - parameters () - ) - - get("/logout", operation(logoutUserOperation)) { - } - - val createUserOperation = (apiOperation[Unit]("createUser") - summary "Create user" - parameters ( - bodyParam[User]("body").description("")) - ) - - post("/", operation(createUserOperation)) { - val body = parsedBody.extract[User] - println("body: " + body) - } - - val createUsersWithArrayInputOperation = (apiOperation[Unit]("createUsersWithArrayInput") - summary "Creates list of users with given input array" - parameters ( - bodyParam[List[User]]("body").description("")) - ) - - post("/createWithArray", operation(createUsersWithArrayInputOperation)) { - val body = parsedBody.extract[List[User]] - println("body: " + body) - } - - val createUsersWithListInputOperation = (apiOperation[Unit]("createUsersWithListInput") - summary "Creates list of users with given list input" - parameters ( - bodyParam[List[User]]("body").description("")) - ) - - post("/createWithList", operation(createUsersWithListInputOperation)) { - val body = parsedBody.extract[List[User]] - println("body: " + body) - } - -} diff --git a/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Category.scala b/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Category.scala deleted file mode 100644 index 4bcd2a5c9ed1..000000000000 --- a/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Category.scala +++ /dev/null @@ -1,7 +0,0 @@ -package com.wordnik.client.model - -case class Category( - id: Option[Long], - - name: Option[String]) - diff --git a/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Order.scala b/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Order.scala deleted file mode 100644 index 75d2dc73bed2..000000000000 --- a/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Order.scala +++ /dev/null @@ -1,14 +0,0 @@ -package com.wordnik.client.model - -import java.util.Date -case class Order( - id: Option[Long], - - petId: Option[Long], - - quantity: Option[Int], - - status: Option[String], // Order Status - - shipDate: Option[Date]) - diff --git a/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Pet.scala b/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Pet.scala deleted file mode 100644 index 088cbb5472cc..000000000000 --- a/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Pet.scala +++ /dev/null @@ -1,18 +0,0 @@ -package com.wordnik.client.model - -import com.wordnik.client.model.Category -import com.wordnik.client.model.Tag -case class Pet( - id: Long, // unique identifier for the pet - - category: Option[Category], - - name: String, - - photoUrls: Option[List[String]], - - tags: Option[List[Tag]], - - status: Option[String] // pet status in the store - ) - diff --git a/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Tag.scala b/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Tag.scala deleted file mode 100644 index 6f4a024b4475..000000000000 --- a/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/Tag.scala +++ /dev/null @@ -1,7 +0,0 @@ -package com.wordnik.client.model - -case class Tag( - id: Option[Long], - - name: Option[String]) - diff --git a/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/User.scala b/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/User.scala deleted file mode 100644 index 228980a1a88d..000000000000 --- a/samples/server-generator/scalatra/output/src/main/scala/com/wordnik/client/model/User.scala +++ /dev/null @@ -1,20 +0,0 @@ -package com.wordnik.client.model - -case class User( - id: Option[Long], - - firstName: Option[String], - - username: Option[String], - - lastName: Option[String], - - email: Option[String], - - password: Option[String], - - phone: Option[String], - - userStatus: Option[Int] // User Status - ) - diff --git a/samples/server-generator/scalatra/templates/JettyMain.scala b/samples/server-generator/scalatra/templates/JettyMain.scala deleted file mode 100644 index ec73dd228164..000000000000 --- a/samples/server-generator/scalatra/templates/JettyMain.scala +++ /dev/null @@ -1,32 +0,0 @@ -import org.eclipse.jetty.server.nio.SelectChannelConnector -import org.eclipse.jetty.server.{ Server } -import org.eclipse.jetty.server.handler.ContextHandlerCollection -import org.eclipse.jetty.webapp.WebAppContext -import org.eclipse.jetty.servlet.{ DefaultServlet, ServletContextHandler, ServletHolder } - -object JettyMain { - def main(args: Array[String]) = { - val server: Server = new Server - println("starting jetty") - - server setGracefulShutdown 5000 - server setSendServerVersion false - server setSendDateHeader true - server setStopAtShutdown true - - val connector = new SelectChannelConnector - connector setPort sys.env.get("PORT").map(_.toInt).getOrElse(8080) - connector setMaxIdleTime 90000 - server addConnector connector - - val webapp = sys.env.get("PUBLIC") getOrElse "webapp" - val webApp = new WebAppContext - webApp setContextPath "/" - webApp setResourceBase webapp - webApp setDescriptor (webapp+"/WEB-INF/web.xml"); - - server setHandler webApp - - server.start() - } -} \ No newline at end of file diff --git a/samples/server-generator/scalatra/templates/api.mustache b/samples/server-generator/scalatra/templates/api.mustache deleted file mode 100644 index fdd842c710ce..000000000000 --- a/samples/server-generator/scalatra/templates/api.mustache +++ /dev/null @@ -1,89 +0,0 @@ -package {{package}} - -{{#imports}}import {{import}} -{{/imports}} - -import java.io.File - -import org.scalatra.{ TypedParamSupport, ScalatraServlet } -import org.scalatra.swagger._ -import org.json4s._ -import org.json4s.JsonDSL._ -import org.scalatra.json.{ JValueResult, JacksonJsonSupport } -import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException} - -import scala.collection.JavaConverters._ - -class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet - with FileUploadSupport - with JacksonJsonSupport - with SwaggerSupport { - protected implicit val jsonFormats: Formats = DefaultFormats - - protected val applicationDescription: String = "{{classname}}" - override protected val applicationName: Option[String] = Some("{{baseName}}") - - before() { - contentType = formats("json") - response.headers += ("Access-Control-Allow-Origin" -> "*") - } -{{#operations}} -{{#operation}} - {{newline}} - - val {{nickname}}Operation = (apiOperation[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]("{{nickname}}") - summary "{{{summary}}}" - parameters( - {{#allParams}} - {{#queryParameter}} - queryParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} - {{/queryParameter}} - {{#pathParameter}} - pathParam[{{dataType}}]("{{paramName}}").description(""){{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} - {{/pathParameter}} - {{#headerParameter}} - headerParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} - {{/headerParameter}} - {{#bodyParameter}} - bodyParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} - {{/bodyParameter}} - {{#formParameter}} - formParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}} - {{/formParameter}} - {{#hasMore}},{{/hasMore}} - {{/allParams}}) - ) - - {{httpMethod}}("{{path}}",operation({{nickname}}Operation)) { - {{#allParams}} - {{#isFile}} - val {{paramName}} = fileParams("{{paramName}}") - {{/isFile}} - {{#notFile}} - {{#pathParameter}} - val {{paramName}} = params.getOrElse("{{paramName}}", halt(400)) - {{/pathParameter}} - - {{#queryParameter}} - val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}") - {{/queryParameter}} - - {{#headerParameter}} - val {{paramName}} = request.getHeader("{{paramName}}") - {{/headerParameter}} - - {{#formParameter}} - val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}") - {{/formParameter}} - - {{#bodyParameter}} - val {{paramName}} = parsedBody.extract[{{dataType}}] - {{/bodyParameter}} - {{/notFile}} - println("{{paramName}}: " + {{paramName}}) - {{/allParams}} - } - -{{/operation}} -{{/operations}} -} \ No newline at end of file diff --git a/samples/server-generator/scalatra/templates/model.mustache b/samples/server-generator/scalatra/templates/model.mustache deleted file mode 100644 index 198f4c5a61af..000000000000 --- a/samples/server-generator/scalatra/templates/model.mustache +++ /dev/null @@ -1,16 +0,0 @@ -package {{package}} - -{{#imports}}import {{import}} -{{/imports}} - -{{#models}} - -{{#model}} -case class {{classname}} ( - {{#vars}} - - {{name}}: {{#isNotRequired}}Option[{{/isNotRequired}}{{datatype}}{{#isNotRequired}}]{{/isNotRequired}} {{#hasMore}},{{/hasMore}}{{#description}} // {{description}}{{/description}}{{newline}} - {{/vars}} -) -{{/model}} -{{/models}} \ No newline at end of file diff --git a/samples/server-generator/scalatra/templates/project/build.properties b/samples/server-generator/scalatra/templates/project/build.properties deleted file mode 100644 index 8cbb5226c451..000000000000 --- a/samples/server-generator/scalatra/templates/project/build.properties +++ /dev/null @@ -1 +0,0 @@ -sbt.version=0.13.0 \ No newline at end of file diff --git a/samples/server-generator/scalatra/templates/project/plugins.sbt b/samples/server-generator/scalatra/templates/project/plugins.sbt deleted file mode 100644 index 94de8e5414fa..000000000000 --- a/samples/server-generator/scalatra/templates/project/plugins.sbt +++ /dev/null @@ -1,7 +0,0 @@ -addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.1") - -addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "0.6.4") - -addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.6.0") - -addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.2.1") diff --git a/samples/server-generator/scalatra/templates/sbt b/samples/server-generator/scalatra/templates/sbt deleted file mode 100755 index 491debf4fb3f..000000000000 --- a/samples/server-generator/scalatra/templates/sbt +++ /dev/null @@ -1,518 +0,0 @@ -#!/usr/bin/env bash -# -# A more capable sbt runner, coincidentally also called sbt. -# Author: Paul Phillips - -# todo - make this dynamic -declare -r sbt_release_version=0.12.4 -declare -r sbt_beta_version=0.13.0-RC4 -declare -r sbt_snapshot_version=0.13.0-SNAPSHOT - -declare sbt_jar sbt_dir sbt_create sbt_snapshot sbt_launch_dir -declare scala_version java_home sbt_explicit_version -declare verbose debug quiet noshare batch trace_level log_level -declare sbt_saved_stty - -echoerr () { [[ -z $quiet ]] && echo "$@" >&2; } -vlog () { [[ -n "$verbose$debug" ]] && echoerr "$@"; } -dlog () { [[ -n $debug ]] && echoerr "$@"; } - -# we'd like these set before we get around to properly processing arguments -for arg in "$@"; do - case $arg in - -q|-quiet) quiet=true ;; - -d|-debug) debug=true ;; - -v|-verbose) verbose=true ;; - *) ;; - esac -done - -build_props_sbt () { - if [[ -r project/build.properties ]]; then - versionLine=$(grep ^sbt.version project/build.properties | tr -d '\r') - versionString=${versionLine##sbt.version=} - echo "$versionString" - fi -} - -update_build_props_sbt () { - local ver="$1" - local old=$(build_props_sbt) - - if [[ $ver == $old ]]; then - return - elif [[ -r project/build.properties ]]; then - perl -pi -e "s/^sbt\.version=.*\$/sbt.version=${ver}/" project/build.properties - grep -q '^sbt.version=' project/build.properties || echo "sbt.version=${ver}" >> project/build.properties - - echoerr !!! - echoerr !!! Updated file project/build.properties setting sbt.version to: $ver - echoerr !!! Previous value was: $old - echoerr !!! - fi -} - -sbt_version () { - if [[ -n $sbt_explicit_version ]]; then - echo $sbt_explicit_version - else - local v=$(build_props_sbt) - if [[ -n $v ]]; then - echo $v - else - echo $sbt_release_version - fi - fi -} - -# restore stty settings (echo in particular) -onSbtRunnerExit() { - [[ -n $sbt_saved_stty ]] || return - dlog "" - dlog "restoring stty: $sbt_saved_stty" - stty $sbt_saved_stty - unset sbt_saved_stty -} - -# save stty and trap exit, to ensure echo is reenabled if we are interrupted. -trap onSbtRunnerExit EXIT -sbt_saved_stty=$(stty -g 2>/dev/null) -dlog "Saved stty: $sbt_saved_stty" - -# this seems to cover the bases on OSX, and someone will -# have to tell me about the others. -get_script_path () { - local path="$1" - [[ -L "$path" ]] || { echo "$path" ; return; } - - local target=$(readlink "$path") - if [[ "${target:0:1}" == "/" ]]; then - echo "$target" - else - echo "$(dirname $path)/$target" - fi -} - -die() { - echo "Aborting: $@" - exit 1 -} - -make_url () { - groupid="$1" - category="$2" - version="$3" - - echo "http://typesafe.artifactoryonline.com/typesafe/ivy-$category/$groupid/sbt-launch/$version/sbt-launch.jar" -} - -readarr () { - while read ; do - eval "$1+=(\"$REPLY\")" - done -} - -init_default_option_file () { - local overriding_var=${!1} - local default_file=$2 - if [[ ! -r "$default_file" && $overriding_var =~ ^@(.*)$ ]]; then - local envvar_file=${BASH_REMATCH[1]} - if [[ -r $envvar_file ]]; then - default_file=$envvar_file - fi - fi - echo $default_file -} - -declare -r default_jvm_opts="-Dfile.encoding=UTF8 -XX:MaxPermSize=256m -Xms512m -Xmx1g -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC" -declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" -declare -r latest_28="2.8.2" -declare -r latest_29="2.9.3" -declare -r latest_210="2.10.0" - -declare -r script_path=$(get_script_path "$BASH_SOURCE") -declare -r script_dir="$(dirname $script_path)" -declare -r script_name="$(basename $script_path)" - -# some non-read-onlies set with defaults -declare java_cmd=java -declare sbt_opts_file=$(init_default_option_file SBT_OPTS .sbtopts) -declare jvm_opts_file=$(init_default_option_file JVM_OPTS .jvmopts) - -# pull -J and -D options to give to java. -declare -a residual_args -declare -a java_args -declare -a scalac_args -declare -a sbt_commands - -# args to jvm/sbt via files or environment variables -declare -a extra_jvm_opts extra_sbt_opts - -# if set, use JAVA_HOME over java found in path -[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java" - -# directory to store sbt launchers -declare sbt_launch_dir="$HOME/.sbt/launchers" -[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir" -[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers)" - -build_props_scala () { - if [[ -r project/build.properties ]]; then - versionLine=$(grep ^build.scala.versions project/build.properties) - versionString=${versionLine##build.scala.versions=} - echo ${versionString%% .*} - fi -} - -execRunner () { - # print the arguments one to a line, quoting any containing spaces - [[ $verbose || $debug ]] && echo "# Executing command line:" && { - for arg; do - if [[ -n "$arg" ]]; then - if printf "%s\n" "$arg" | grep -q ' '; then - printf "\"%s\"\n" "$arg" - else - printf "%s\n" "$arg" - fi - fi - done - echo "" - } - - if [[ -n $batch ]]; then - # the only effective way I've found to avoid sbt hanging when backgrounded. - exec 0<&- - ( "$@" & ) - # I'm sure there's some way to get our hands on the pid and wait for it - # but it exceeds my present level of ambition. - else - { "$@"; } - fi -} - -sbt_groupid () { - case $(sbt_version) in - 0.7.*) echo org.scala-tools.sbt ;; - 0.10.*) echo org.scala-tools.sbt ;; - 0.11.[12]) echo org.scala-tools.sbt ;; - *) echo org.scala-sbt ;; - esac -} - -sbt_artifactory_list () { - local version0=$(sbt_version) - local version=${version0%-SNAPSHOT} - local url="http://typesafe.artifactoryonline.com/typesafe/ivy-snapshots/$(sbt_groupid)/sbt-launch/" - dlog "Looking for snapshot list at: $url " - - curl -s --list-only "$url" | \ - grep -F $version | \ - perl -e 'print reverse <>' | \ - perl -pe 's#^/dev/null - dlog "curl returned: $?" - echo "$url" - return - done -} - -jar_url () { - case $(sbt_version) in - 0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;; - *-SNAPSHOT) make_snapshot_url ;; - *) make_release_url ;; - esac -} - -jar_file () { - case $1 in - 0.13.*) echo "$sbt_launch_dir/$1/sbt-launch.jar" ;; - *) echo "$sbt_launch_dir/$sbt_release_version/sbt-launch.jar" ;; - esac -} - -download_url () { - local url="$1" - local jar="$2" - - echo "Downloading sbt launcher $(sbt_version):" - echo " From $url" - echo " To $jar" - - mkdir -p $(dirname "$jar") && { - if which curl >/dev/null; then - curl --fail --silent "$url" --output "$jar" - elif which wget >/dev/null; then - wget --quiet -O "$jar" "$url" - fi - } && [[ -r "$jar" ]] -} - -acquire_sbt_jar () { - sbt_url="$(jar_url)" - sbt_jar="$(jar_file $(sbt_version))" - - [[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar" -} - -usage () { - cat < display stack traces with a max of frames (default: -1, traces suppressed) - -no-colors disable ANSI color codes - -sbt-create start sbt even if current directory contains no sbt project - -sbt-dir path to global settings/plugins directory (default: ~/.sbt/) - -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11+) - -ivy path to local Ivy repository (default: ~/.ivy2) - -no-share use all local caches; no sharing - -offline put sbt in offline mode - -jvm-debug Turn on JVM debugging, open at the given port. - -batch Disable interactive mode - -prompt Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted - - # sbt version (default: from project/build.properties if present, else latest release) - !!! The only way to accomplish this pre-0.12.0 if there is a build.properties file which - !!! contains an sbt.version property is to update the file on disk. That's what this does. - -sbt-version use the specified version of sbt (default: $sbt_release_version) - -sbt-jar use the specified jar as the sbt launcher - -sbt-beta use a beta version of sbt (currently: $sbt_beta_version) - -sbt-snapshot use a snapshot version of sbt (currently: $sbt_snapshot_version) - -sbt-launch-dir directory to hold sbt launchers (default: $sbt_launch_dir) - - # scala version (default: as chosen by sbt) - -28 use $latest_28 - -29 use $latest_29 - -210 use $latest_210 - -scala-home use the scala build at the specified directory - -scala-version use the specified version of scala - -binary-version use the specified scala version when searching for dependencies - - # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) - -java-home alternate JAVA_HOME - - # passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution - # The default set is used if JVM_OPTS is unset and no -jvm-opts file is found - $default_jvm_opts - JVM_OPTS environment variable holding either the jvm args directly, or - the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts') - Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument. - -jvm-opts file containing jvm args (if not given, .jvmopts in project root is used if present) - -Dkey=val pass -Dkey=val directly to the jvm - -J-X pass option -X directly to the jvm (-J is stripped) - - # passing options to sbt, OR to this runner - SBT_OPTS environment variable holding either the sbt args directly, or - the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts') - Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument. - -sbt-opts file containing sbt args (if not given, .sbtopts in project root is used if present) - -S-X add -X to sbt's scalacOptions (-S is stripped) -EOM -} - -addJava () { - dlog "[addJava] arg = '$1'" - java_args=( "${java_args[@]}" "$1" ) -} -addSbt () { - dlog "[addSbt] arg = '$1'" - sbt_commands=( "${sbt_commands[@]}" "$1" ) -} -addScalac () { - dlog "[addScalac] arg = '$1'" - scalac_args=( "${scalac_args[@]}" "$1" ) -} -addResidual () { - dlog "[residual] arg = '$1'" - residual_args=( "${residual_args[@]}" "$1" ) -} -addResolver () { - addSbt "set resolvers in ThisBuild += $1" -} -addDebugger () { - addJava "-Xdebug" - addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1" -} -setScalaVersion () { - addSbt "set scalaVersion in ThisBuild := \"$1\"" - if [[ "$1" == *SNAPSHOT* ]]; then - addResolver Opts.resolver.sonatypeSnapshots - fi -} - -process_args () -{ - require_arg () { - local type="$1" - local opt="$2" - local arg="$3" - - if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then - die "$opt requires <$type> argument" - fi - } - while [[ $# -gt 0 ]]; do - case "$1" in - -h|-help) usage; exit 1 ;; - -v|-verbose) verbose=true && log_level=Info && shift ;; - -d|-debug) debug=true && log_level=Debug && shift ;; - -q|-quiet) quiet=true && log_level=Error && shift ;; - - -trace) require_arg integer "$1" "$2" && trace_level=$2 && shift 2 ;; - -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; - -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; - -no-share) noshare=true && shift ;; - -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; - -sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;; - -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; - -offline) addSbt "set offline := true" && shift ;; - -jvm-debug) require_arg port "$1" "$2" && addDebugger $2 && shift 2 ;; - -batch) batch=true && shift ;; - -prompt) require_arg "expr" "$1" "$2" && addSbt "set shellPrompt in ThisBuild := (s => { val e = Project.extract(s) ; $2 })" && shift 2 ;; - - -sbt-create) sbt_create=true && shift ;; - -sbt-snapshot) sbt_explicit_version=$sbt_snapshot_version && shift ;; - -sbt-beta) sbt_explicit_version=$sbt_beta_version && shift ;; - -sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;; - -sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;; --sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;; - -scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;; --binary-version) require_arg version "$1" "$2" && addSbt "set scalaBinaryVersion in ThisBuild := \"$2\"" && shift 2 ;; - -scala-home) require_arg path "$1" "$2" && addSbt "set every scalaHome := Some(file(\"$2\"))" && shift 2 ;; - -java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;; - -sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;; - -jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;; - - -D*) addJava "$1" && shift ;; - -J*) addJava "${1:2}" && shift ;; - -S*) addScalac "${1:2}" && shift ;; - -28) addSbt "++ $latest_28" && shift ;; - -29) addSbt "++ $latest_29" && shift ;; - -210) addSbt "++ $latest_210" && shift ;; - - *) addResidual "$1" && shift ;; - esac - done -} - - -# process the direct command line arguments -process_args "$@" - -# skip #-styled comments -readConfigFile() { - while read line; do echo ${line/\#*/} | grep -vE '^\s*$'; done < $1 -} - -# if there are file/environment sbt_opts, process again so we -# can supply args to this runner -if [[ -r "$sbt_opts_file" ]]; then - vlog "Using sbt options defined in file $sbt_opts_file" - readarr extra_sbt_opts < <(readConfigFile "$sbt_opts_file") -elif [[ -n "$SBT_OPTS" && !($SBT_OPTS =~ ^@.*) ]]; then - vlog "Using sbt options defined in variable \$SBT_OPTS" - extra_sbt_opts=( $SBT_OPTS ) -else - vlog "No extra sbt options have been defined" -fi - -[[ -n $extra_sbt_opts ]] && process_args "${extra_sbt_opts[@]}" - -# reset "$@" to the residual args -set -- "${residual_args[@]}" -argumentCount=$# - -# only exists in 0.12+ -setTraceLevel() { - case $(sbt_version) in - 0.{7,10,11}.*) echoerr "Cannot set trace level in sbt version $(sbt_version)" ;; - *) addSbt "set every traceLevel := $trace_level" ;; - esac -} - -# set scalacOptions if we were given any -S opts -[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\"" - -# Update build.properties no disk to set explicit version - sbt gives us no choice -[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version" -vlog "Detected sbt version $(sbt_version)" - -[[ -n "$scala_version" ]] && echoerr "Overriding scala version to $scala_version" - -# no args - alert them there's stuff in here -(( $argumentCount > 0 )) || vlog "Starting $script_name: invoke with -help for other options" - -# verify this is an sbt dir or -create was given -[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || { - cat <- Scala 2.9.1 [available here](http://www.scala-lang.org) - -You also need to add scala binary to your PATH. - -### Generating a server -You first need to build the `swagger-codegen` project--this is done by running this command at the root of the swagger-codegen project: - -``` -mvn package -``` - -You can now generate a server from any valid[**](https://github.com/wordnik/swagger-codegen/blob/master/README.md#validating-your-swagger-spec) swagger spec: - -``` -./bin/runscala.sh samples/server-generator/sinatra/SinatraServerGenerator.scala http://petstore.swagger.wordnik.com/api/api-docs special-key -``` - -After executing this script, you will have an output directory with the server-generated files: - -``` -$ cd samples/server-generator/sinatra/output -$ find . -type f -./config.ru -./Gemfile -./Gemfile.lock -./lib/pet_api.rb -./lib/store_api.rb -./lib/swaggering.rb -./lib/user_api.rb -./my_app.rb -./README.md -``` - -To run the server, cd to the `samples/server-generator/sinatra/output` folder and run: - -``` -rackup -p 4567 -``` - -You can now load the swagger-ui against `http://localhost:4567/resources.json`. Of course this isn't a fully -runnable server! You have to add the logic in the lib/*.rb files. But that's the easy part. - - -### Making it your own -Running the sample is easy, but how about making your own server? Easy! Just modify the `samples/server-generator/sinatra/SinatraServerGenerator.scala` file. - -Don't like the templates? Don't worry, we're not offended! They're [mustache](http://mustache.github.com/) templates and are easy to modify. -Take a look at the sample templates here: - -
  • - Generator for your api classes: [api.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/sinatra/templates/api.mustache) - -
  • - The main class to run your server: [my_app.mustache](https://github.com/wordnik/swagger-codegen/blob/master/samples/server-generator/sinatra/templates/my_app.mustache) - - -Sound easy? It is! diff --git a/samples/server-generator/sinatra/SinatraServerGenerator.scala b/samples/server-generator/sinatra/SinatraServerGenerator.scala deleted file mode 100644 index 7cb351d34427..000000000000 --- a/samples/server-generator/sinatra/SinatraServerGenerator.scala +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicRubyGenerator - -import java.io.File - -import scala.collection.mutable.{ HashMap, ListBuffer } - -object SinatraServerGenerator extends BasicRubyGenerator { - def main(args: Array[String]) = generateClient(args) - - override def toApiName(name: String): String = name + "_api" - - // undo the ruby-ish conversions in the BasicRubyGenerator - override def toVarName(name: String): String = name - override def toMethodName(name: String): String = name - - override def templateDir = "samples/server-generator/sinatra/templates" - - val outputFolder = "samples/server-generator/sinatra/output" - - // where to write generated code - override def destinationDir = outputFolder + "" - - override def modelPackage = Some("com.wordnik.client.model") - - // template used for apis - apiTemplateFiles ++= Map("api.mustache" -> ".rb") - - modelTemplateFiles.clear - - override def apiPackage = Some("lib") - - // supporting classes - override def supportingFiles = List( - ("README.md", outputFolder, "README.md"), - ("config.ru", outputFolder, "config.ru"), - ("Gemfile", outputFolder, "Gemfile"), - ("my_app.mustache", outputFolder, "my_app.rb"), - ("lib/swaggering.rb", outputFolder + File.separator + "lib", "swaggering.rb")) - - override def processApiMap(m: Map[String, AnyRef]): Map[String, AnyRef] = { - val mutable = scala.collection.mutable.Map() ++ m - - mutable.map(k => { - k._1 match { - // the sinatra templates like lower-case httpMethods - case e: String if (e == "httpMethod") => mutable += "httpMethod" -> k._2.toString.toLowerCase - - // convert path into ruby-ish syntax without basePart (i.e. /pet.{format}/{petId} => /:petId - case e: String if (e == "path") => { - val path = { - val arr = k._2.toString.split("/") - if (arr.length >= 2) { - mutable += "basePart" -> (arr.slice(2, arr.length).mkString("", "/", "")) - "/" + arr.slice(2, arr.length).mkString("", "/", "") - } else - k._2.toString - } - mutable += "path" -> path.replaceAll("\\{", ":").replaceAll("\\}", "") - } - case _ => - } - }) - mutable.toMap - } -} diff --git a/samples/server-generator/sinatra/output/Gemfile b/samples/server-generator/sinatra/output/Gemfile deleted file mode 100644 index be9c3168ea6f..000000000000 --- a/samples/server-generator/sinatra/output/Gemfile +++ /dev/null @@ -1,4 +0,0 @@ -source 'https://rubygems.org' - -gem "sinatra" -gem "sinatra-cross_origin" \ No newline at end of file diff --git a/samples/server-generator/sinatra/output/README.md b/samples/server-generator/sinatra/output/README.md deleted file mode 100644 index 23c501353da5..000000000000 --- a/samples/server-generator/sinatra/output/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Swagger for Sinatra - -## Overview -This is a project to provide Swagger support inside the [Sinatra](http://www.sinatrarb.com/) framework. You can find -out more about both the spec and the framework at http://swagger.wordnik.com. For more information about -Wordnik's APIs, please visit http://developer.wordnik.com. - -## Prerequisites -You need to install ruby 1.9.3 and the following gems: - -``` -sinatra -sinatra-cross_origin -``` - -## Getting started -This sample was generated with the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. - -``` -rackup -p 4567 config.ru -``` - -In your [swagger ui](https://github.com/wordnik/swagger-ui), put in the following URL: - -``` -http://localhost:4567/resources.json -``` - -Voila! diff --git a/samples/server-generator/sinatra/output/config.ru b/samples/server-generator/sinatra/output/config.ru deleted file mode 100644 index 395d05871239..000000000000 --- a/samples/server-generator/sinatra/output/config.ru +++ /dev/null @@ -1,2 +0,0 @@ -require './my_app' -run MyApp diff --git a/samples/server-generator/sinatra/output/lib/Swaggering.rb b/samples/server-generator/sinatra/output/lib/Swaggering.rb deleted file mode 100644 index 79aca1da2c92..000000000000 --- a/samples/server-generator/sinatra/output/lib/Swaggering.rb +++ /dev/null @@ -1,154 +0,0 @@ -require 'json' -require 'sinatra/base' -require 'sinatra/cross_origin' - -class Configuration - attr_accessor :base_path, :api_version, :swagger_version, :format_specifier - - def initialize - @api_version = '1.0' - @base_path = 'http://localhost:4567' - @swagger_version = '1.1' - @format_specifier = ".json" - end -end - -class Swaggering < Sinatra::Base - register Sinatra::CrossOrigin - - @@routes = {} - @@configuration = Configuration.new - - attr_accessor :configuration - - def self.configure - get("/resources" + @@configuration.format_specifier) { - cross_origin - Swaggering.to_resource_listing - } - @@configuration ||= Configuration.new - yield(@@configuration) if block_given? - end - - def self.add_route(method, path, swag={}, opts={}, &block) - fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path - - accepted = case method - when 'get' - get(fullPath, opts, &block) - true - when 'post' - post(fullPath, opts, &block) - true - when 'delete' - delete(fullPath, opts, &block) - true - when 'put' - put(fullPath, opts, &block) - true - else - false - end - - if accepted then - resourcePath = swag["resourcePath"].to_s - ops = @@routes[resourcePath] - if ops.nil? - ops = Array.new - @@routes.merge!(resourcePath => ops) - - get(resourcePath + @@configuration.format_specifier) do - cross_origin - Swaggering.to_api(resourcePath) - end - end - - swag.merge!("httpMethod" => method.to_s.upcase) - ops.push(swag) - end - end - - def self.to_resource_listing - apis = Array.new - (@@routes.keys).each do |key| - api = { - "path" => (key + ".{format}"), - "description" => "no description" - } - apis.push api - end - - resource = { - "apiVersion" => @@configuration.api_version, - "swaggerVersion" => @@configuration.swagger_version, - "apis" => apis - } - - resource.to_json - end - - def self.to_api(resourcePath) - apis = {} - models = [] - - @@routes[resourcePath].each do |route| - endpoint = route["endpoint"].gsub(/:(\w+)(\/?)/,'{\1}\2') - path = (resourcePath + ".{format}" + endpoint) - api = apis[path] - if api.nil? - api = {"path" => path, "description" => "description", "operations" => []} - apis.merge!(path => api) - end - - parameters = route["parameters"] - - unless parameters.nil? then - parameters.each do |param| - av_string = param["allowableValues"] - unless av_string.nil? - if av_string.count('[') > 0 - pattern = /^([A-Z]*)\[(.*)\]/ - match = pattern.match av_string - case match.to_a[1] - when "LIST" - allowables = match.to_a[2].split(',') - param["allowableValues"] = { - "valueType" => "LIST", - "values" => allowables - } - when "RANGE" - allowables = match.to_a[2].split(',') - param["allowableValues"] = { - "valueType" => "RANGE", - "min" => allowables[0], - "max" => allowables[1] - } - end - end - end - end - end - - op = { - "httpMethod" => route["httpMethod"], - "description" => route["summary"], - "responseClass" => route["responseClass"], - "notes" => route["notes"], - "nickname" => route["nickname"], - "summary" => route["summary"], - "parameters" => route["parameters"] - } - api["operations"].push(op) - end - - api_listing = { - "apiVersion" => @@configuration.api_version, - "swaggerVersion" => @@configuration.swagger_version, - "basePath" => @@configuration.base_path, - "resourcePath" => resourcePath, - "apis" => apis.values, - "models" => models - } - api_listing.to_json - end -end diff --git a/samples/server-generator/sinatra/output/lib/pet_api.rb b/samples/server-generator/sinatra/output/lib/pet_api.rb deleted file mode 100644 index 774349d2e9c1..000000000000 --- a/samples/server-generator/sinatra/output/lib/pet_api.rb +++ /dev/null @@ -1,112 +0,0 @@ -require 'json' - -MyApp.add_route('get', '/:petId', { - "resourcePath" => "/pet", - "summary" => "Find pet by ID", - "nickname" => "getPetById", - "responseClass" => "Pet", - "endpoint" => "/:petId", - "notes" => "Returns a pet based on ID", - "parameters" => [ - { - "name" => "petId", - "description" => "ID of pet that needs to be fetched", - "dataType" => "string", - "paramType" => "path", - }, - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('post', '/', { - "resourcePath" => "/pet", - "summary" => "Add a new pet to the store", - "nickname" => "addPet", - "responseClass" => "void", - "endpoint" => "/", - "notes" => "", - "parameters" => [ - { - "name" => "body", - "description" => "Pet object that needs to be added to the store", - "dataType" => "Pet", - "paramType" => "body", - } - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('put', '/', { - "resourcePath" => "/pet", - "summary" => "Update an existing pet", - "nickname" => "updatePet", - "responseClass" => "void", - "endpoint" => "/", - "notes" => "", - "parameters" => [ - { - "name" => "body", - "description" => "Pet object that needs to be updated in the store", - "dataType" => "Pet", - "paramType" => "body", - } - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('get', '/findByStatus', { - "resourcePath" => "/pet", - "summary" => "Finds Pets by status", - "nickname" => "findPetsByStatus", - "responseClass" => "List[Pet]", - "endpoint" => "/findByStatus", - "notes" => "Multiple status values can be provided with comma seperated strings", - "parameters" => [ - { - "name" => "status", - "description" => "Status values that need to be considered for filter", - "dataType" => "string", - "paramType" => "query", - "allowMultiple" => true, - "allowableValues" => "LIST[available,pending,sold]", - "defaultValue" => "available"}, - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('get', '/findByTags', { - "resourcePath" => "/pet", - "summary" => "Finds Pets by tags", - "nickname" => "findPetsByTags", - "responseClass" => "List[Pet]", - "endpoint" => "/findByTags", - "notes" => "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", - "parameters" => [ - { - "name" => "tags", - "description" => "Tags to filter by", - "dataType" => "string", - "paramType" => "query", - "allowMultiple" => true, - "allowableValues" => "", - }, - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - - diff --git a/samples/server-generator/sinatra/output/lib/store_api.rb b/samples/server-generator/sinatra/output/lib/store_api.rb deleted file mode 100644 index 8a5e2315c499..000000000000 --- a/samples/server-generator/sinatra/output/lib/store_api.rb +++ /dev/null @@ -1,66 +0,0 @@ -require 'json' - -MyApp.add_route('get', '/order/:orderId', { - "resourcePath" => "/store", - "summary" => "Find purchase order by ID", - "nickname" => "getOrderById", - "responseClass" => "Order", - "endpoint" => "/order/:orderId", - "notes" => "For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors", - "parameters" => [ - { - "name" => "orderId", - "description" => "ID of pet that needs to be fetched", - "dataType" => "string", - "paramType" => "path", - }, - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('delete', '/order/:orderId', { - "resourcePath" => "/store", - "summary" => "Delete purchase order by ID", - "nickname" => "deleteOrder", - "responseClass" => "void", - "endpoint" => "/order/:orderId", - "notes" => "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "parameters" => [ - { - "name" => "orderId", - "description" => "ID of the order that needs to be deleted", - "dataType" => "string", - "paramType" => "path", - }, - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('post', '/order', { - "resourcePath" => "/store", - "summary" => "Place an order for a pet", - "nickname" => "placeOrder", - "responseClass" => "void", - "endpoint" => "/order", - "notes" => "", - "parameters" => [ - { - "name" => "body", - "description" => "order placed for purchasing the pet", - "dataType" => "Order", - "paramType" => "body", - } - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - - diff --git a/samples/server-generator/sinatra/output/lib/user_api.rb b/samples/server-generator/sinatra/output/lib/user_api.rb deleted file mode 100644 index 8e1d5715151b..000000000000 --- a/samples/server-generator/sinatra/output/lib/user_api.rb +++ /dev/null @@ -1,181 +0,0 @@ -require 'json' - -MyApp.add_route('post', '/createWithArray', { - "resourcePath" => "/user", - "summary" => "Creates list of users with given input array", - "nickname" => "createUsersWithArrayInput", - "responseClass" => "void", - "endpoint" => "/createWithArray", - "notes" => "", - "parameters" => [ - { - "name" => "body", - "description" => "List of user object", - "dataType" => "Array[User]", - "paramType" => "body", - } - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('post', '/', { - "resourcePath" => "/user", - "summary" => "Create user", - "nickname" => "createUser", - "responseClass" => "void", - "endpoint" => "/", - "notes" => "This can only be done by the logged in user.", - "parameters" => [ - { - "name" => "body", - "description" => "Created user object", - "dataType" => "User", - "paramType" => "body", - } - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('post', '/createWithList', { - "resourcePath" => "/user", - "summary" => "Creates list of users with given list input", - "nickname" => "createUsersWithListInput", - "responseClass" => "void", - "endpoint" => "/createWithList", - "notes" => "", - "parameters" => [ - { - "name" => "body", - "description" => "List of user object", - "dataType" => "List[User]", - "paramType" => "body", - } - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('put', '/:username', { - "resourcePath" => "/user", - "summary" => "Updated user", - "nickname" => "updateUser", - "responseClass" => "void", - "endpoint" => "/:username", - "notes" => "This can only be done by the logged in user.", - "parameters" => [ - { - "name" => "username", - "description" => "name that need to be deleted", - "dataType" => "string", - "paramType" => "path", - }, - { - "name" => "body", - "description" => "Updated user object", - "dataType" => "User", - "paramType" => "body", - } - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('delete', '/:username', { - "resourcePath" => "/user", - "summary" => "Delete user", - "nickname" => "deleteUser", - "responseClass" => "void", - "endpoint" => "/:username", - "notes" => "This can only be done by the logged in user.", - "parameters" => [ - { - "name" => "username", - "description" => "The name that needs to be deleted", - "dataType" => "string", - "paramType" => "path", - }, - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('get', '/:username', { - "resourcePath" => "/user", - "summary" => "Get user by user name", - "nickname" => "getUserByName", - "responseClass" => "User", - "endpoint" => "/:username", - "notes" => "", - "parameters" => [ - { - "name" => "username", - "description" => "The name that needs to be fetched. Use user1 for testing.", - "dataType" => "string", - "paramType" => "path", - }, - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('get', '/login', { - "resourcePath" => "/user", - "summary" => "Logs user into the system", - "nickname" => "loginUser", - "responseClass" => "string", - "endpoint" => "/login", - "notes" => "", - "parameters" => [ - { - "name" => "username", - "description" => "The user name for login", - "dataType" => "string", - "paramType" => "query", - "allowMultiple" => false, - "allowableValues" => "", - }, - { - "name" => "password", - "description" => "The password for login in clear text", - "dataType" => "string", - "paramType" => "query", - "allowMultiple" => false, - "allowableValues" => "", - }, - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -MyApp.add_route('get', '/logout', { - "resourcePath" => "/user", - "summary" => "Logs out current logged in user session", - "nickname" => "logoutUser", - "responseClass" => "void", - "endpoint" => "/logout", - "notes" => "", - "parameters" => [ - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - - diff --git a/samples/server-generator/sinatra/output/my_app.rb b/samples/server-generator/sinatra/output/my_app.rb deleted file mode 100644 index 415efe1a84d7..000000000000 --- a/samples/server-generator/sinatra/output/my_app.rb +++ /dev/null @@ -1,13 +0,0 @@ -require './lib/swaggering' - -# only need to extend if you want special configuration! -class MyApp < Swaggering - self.configure do |config| - config.api_version = '0.2' - end -end - -require './lib/store_api.rb' -require './lib/pet_api.rb' -require './lib/user_api.rb' - diff --git a/samples/server-generator/sinatra/templates/Gemfile b/samples/server-generator/sinatra/templates/Gemfile deleted file mode 100644 index be9c3168ea6f..000000000000 --- a/samples/server-generator/sinatra/templates/Gemfile +++ /dev/null @@ -1,4 +0,0 @@ -source 'https://rubygems.org' - -gem "sinatra" -gem "sinatra-cross_origin" \ No newline at end of file diff --git a/samples/server-generator/sinatra/templates/README.md b/samples/server-generator/sinatra/templates/README.md deleted file mode 100644 index 23c501353da5..000000000000 --- a/samples/server-generator/sinatra/templates/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Swagger for Sinatra - -## Overview -This is a project to provide Swagger support inside the [Sinatra](http://www.sinatrarb.com/) framework. You can find -out more about both the spec and the framework at http://swagger.wordnik.com. For more information about -Wordnik's APIs, please visit http://developer.wordnik.com. - -## Prerequisites -You need to install ruby 1.9.3 and the following gems: - -``` -sinatra -sinatra-cross_origin -``` - -## Getting started -This sample was generated with the [swagger-codegen](https://github.com/wordnik/swagger-codegen) project. - -``` -rackup -p 4567 config.ru -``` - -In your [swagger ui](https://github.com/wordnik/swagger-ui), put in the following URL: - -``` -http://localhost:4567/resources.json -``` - -Voila! diff --git a/samples/server-generator/sinatra/templates/api.mustache b/samples/server-generator/sinatra/templates/api.mustache deleted file mode 100644 index cfeae19de7ac..000000000000 --- a/samples/server-generator/sinatra/templates/api.mustache +++ /dev/null @@ -1,57 +0,0 @@ -require 'json' - -{{#operations}} -{{#operation}} - -MyApp.add_route('{{httpMethod}}', '{{path}}', { - "resourcePath" => "/{{baseName}}", - "summary" => "{{{summary}}}", - "nickname" => "{{nickname}}", - "responseClass" => "{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}", - "endpoint" => "{{path}}", - "notes" => "{{{notes}}}", - "parameters" => [ - {{#queryParams}} - { - "name" => "{{paramName}}", - "description" => "{{description}}", - "dataType" => "{{swaggerDataType}}", - "paramType" => "query", - "allowMultiple" => {{allowMultiple}}, - "allowableValues" => "{{allowableValues}}", - {{#defaultValue}}"defaultValue" => {{{defaultValue}}}{{/defaultValue}} - }, - {{/queryParams}} - {{#pathParams}} - { - "name" => "{{paramName}}", - "description" => "{{description}}", - "dataType" => "{{swaggerDataType}}", - "paramType" => "path", - }, - {{/pathParams}} - {{#headerParams}} - { - "name" => "{{paramName}}", - "description" => "{{description}}", - "dataType" => "{{swaggerDataType}}", - "paramType" => "header", - }, - {{/headerParams}} - {{#bodyParams}} - { - "name" => "body", - "description" => "{{description}}", - "dataType" => "{{swaggerDataType}}", - "paramType" => "body", - } - {{/bodyParams}} - ]}) do - cross_origin - # the guts live here - - {"message" => "yes, it worked"}.to_json -end - -{{/operation}} -{{/operations}} diff --git a/samples/server-generator/sinatra/templates/config.ru b/samples/server-generator/sinatra/templates/config.ru deleted file mode 100644 index 395d05871239..000000000000 --- a/samples/server-generator/sinatra/templates/config.ru +++ /dev/null @@ -1,2 +0,0 @@ -require './my_app' -run MyApp diff --git a/samples/server-generator/sinatra/templates/lib/Swaggering.rb b/samples/server-generator/sinatra/templates/lib/Swaggering.rb deleted file mode 100644 index 79aca1da2c92..000000000000 --- a/samples/server-generator/sinatra/templates/lib/Swaggering.rb +++ /dev/null @@ -1,154 +0,0 @@ -require 'json' -require 'sinatra/base' -require 'sinatra/cross_origin' - -class Configuration - attr_accessor :base_path, :api_version, :swagger_version, :format_specifier - - def initialize - @api_version = '1.0' - @base_path = 'http://localhost:4567' - @swagger_version = '1.1' - @format_specifier = ".json" - end -end - -class Swaggering < Sinatra::Base - register Sinatra::CrossOrigin - - @@routes = {} - @@configuration = Configuration.new - - attr_accessor :configuration - - def self.configure - get("/resources" + @@configuration.format_specifier) { - cross_origin - Swaggering.to_resource_listing - } - @@configuration ||= Configuration.new - yield(@@configuration) if block_given? - end - - def self.add_route(method, path, swag={}, opts={}, &block) - fullPath = swag["resourcePath"].to_s + @@configuration.format_specifier + path - - accepted = case method - when 'get' - get(fullPath, opts, &block) - true - when 'post' - post(fullPath, opts, &block) - true - when 'delete' - delete(fullPath, opts, &block) - true - when 'put' - put(fullPath, opts, &block) - true - else - false - end - - if accepted then - resourcePath = swag["resourcePath"].to_s - ops = @@routes[resourcePath] - if ops.nil? - ops = Array.new - @@routes.merge!(resourcePath => ops) - - get(resourcePath + @@configuration.format_specifier) do - cross_origin - Swaggering.to_api(resourcePath) - end - end - - swag.merge!("httpMethod" => method.to_s.upcase) - ops.push(swag) - end - end - - def self.to_resource_listing - apis = Array.new - (@@routes.keys).each do |key| - api = { - "path" => (key + ".{format}"), - "description" => "no description" - } - apis.push api - end - - resource = { - "apiVersion" => @@configuration.api_version, - "swaggerVersion" => @@configuration.swagger_version, - "apis" => apis - } - - resource.to_json - end - - def self.to_api(resourcePath) - apis = {} - models = [] - - @@routes[resourcePath].each do |route| - endpoint = route["endpoint"].gsub(/:(\w+)(\/?)/,'{\1}\2') - path = (resourcePath + ".{format}" + endpoint) - api = apis[path] - if api.nil? - api = {"path" => path, "description" => "description", "operations" => []} - apis.merge!(path => api) - end - - parameters = route["parameters"] - - unless parameters.nil? then - parameters.each do |param| - av_string = param["allowableValues"] - unless av_string.nil? - if av_string.count('[') > 0 - pattern = /^([A-Z]*)\[(.*)\]/ - match = pattern.match av_string - case match.to_a[1] - when "LIST" - allowables = match.to_a[2].split(',') - param["allowableValues"] = { - "valueType" => "LIST", - "values" => allowables - } - when "RANGE" - allowables = match.to_a[2].split(',') - param["allowableValues"] = { - "valueType" => "RANGE", - "min" => allowables[0], - "max" => allowables[1] - } - end - end - end - end - end - - op = { - "httpMethod" => route["httpMethod"], - "description" => route["summary"], - "responseClass" => route["responseClass"], - "notes" => route["notes"], - "nickname" => route["nickname"], - "summary" => route["summary"], - "parameters" => route["parameters"] - } - api["operations"].push(op) - end - - api_listing = { - "apiVersion" => @@configuration.api_version, - "swaggerVersion" => @@configuration.swagger_version, - "basePath" => @@configuration.base_path, - "resourcePath" => resourcePath, - "apis" => apis.values, - "models" => models - } - api_listing.to_json - end -end diff --git a/samples/server-generator/sinatra/templates/my_app.mustache b/samples/server-generator/sinatra/templates/my_app.mustache deleted file mode 100644 index 72b5267a1407..000000000000 --- a/samples/server-generator/sinatra/templates/my_app.mustache +++ /dev/null @@ -1,12 +0,0 @@ -require './lib/swaggering' - -# only need to extend if you want special configuration! -class MyApp < Swaggering - self.configure do |config| - config.api_version = '0.2' - end -end - -{{#apis}} -require './lib/{{className}}.rb' -{{/apis}} \ No newline at end of file diff --git a/samples/server-generator/scalatra/output/README.md b/samples/server/petstore/jaxrs/README.md similarity index 93% rename from samples/server-generator/scalatra/output/README.md rename to samples/server/petstore/jaxrs/README.md index 45d023e4da61..f8a560b776f5 100644 --- a/samples/server-generator/scalatra/output/README.md +++ b/samples/server/petstore/jaxrs/README.md @@ -7,4 +7,4 @@ is an example of building a swagger-enabled scalatra server. This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: -[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) +[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file diff --git a/samples/server-generator/java-jaxrs/output/pom.xml b/samples/server/petstore/jaxrs/pom.xml similarity index 72% rename from samples/server-generator/java-jaxrs/output/pom.xml rename to samples/server/petstore/jaxrs/pom.xml index d22317ce5b77..fa94509ad550 100644 --- a/samples/server-generator/java-jaxrs/output/pom.xml +++ b/samples/server/petstore/jaxrs/pom.xml @@ -1,10 +1,10 @@ 4.0.0 - com.wordnik - swagger-java-jaxrs-petstore - war - swagger-java-jaxrs-petstore - 1.0.0-SNAPSHOT + io.swagger + swagger-server + jar + swagger-server + 1.0.0 src/main/java @@ -31,7 +31,7 @@ ${jetty-version} - /api + /v2 target/${project.artifactId}-${project.version} ${project.basedir}/conf/jetty/webdefault.xml @@ -71,15 +71,40 @@ com.wordnik - swagger-jaxrs_2.9.1 + swagger-jersey-jaxrs ${swagger-core-version} - compile org.slf4j slf4j-log4j12 ${slf4j-version} + + com.sun.jersey + jersey-core + ${jersey-version} + + + com.sun.jersey + jersey-json + ${jersey-version} + + + com.sun.jersey + jersey-servlet + ${jersey-version} + + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + + + com.sun.jersey + jersey-server + ${jersey-version} + + org.scalatest scalatest_2.9.1 @@ -99,8 +124,9 @@ - 1.2.1 - 7.6.0.v20120127 + 1.5.1-M1 + 8.1.11.v20130520 + 1.13 1.6.3 1.6.1 4.8.1 diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/ApiException.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiException.java similarity index 85% rename from samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/ApiException.java rename to samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiException.java index 6cbb0aabcedb..cae767c0393f 100644 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/ApiException.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiException.java @@ -1,4 +1,4 @@ -package com.wordnik.api; +package io.swagger.api; public class ApiException extends Exception{ private int code; @@ -7,4 +7,3 @@ public class ApiException extends Exception{ this.code = code; } } - diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiOriginFilter.java similarity index 96% rename from samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/ApiOriginFilter.java rename to samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiOriginFilter.java index cc5a89c386a3..c2eeacf13d3f 100644 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -1,4 +1,4 @@ -package com.wordnik.api; +package io.swagger.api; import java.io.IOException; @@ -23,4 +23,4 @@ public class ApiOriginFilter implements javax.servlet.Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } -} +} \ No newline at end of file diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/ApiResponse.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiResponseMessage.java similarity index 87% rename from samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/ApiResponse.java rename to samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiResponseMessage.java index fb9fdc8cda41..9e5b0ee44e2d 100644 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/ApiResponse.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -1,9 +1,9 @@ -package com.wordnik.api; +package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -public class ApiResponse { +public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; public static final int INFO = 3; @@ -14,9 +14,9 @@ public class ApiResponse { String type; String message; - public ApiResponse(){} + public ApiResponseMessage(){} - public ApiResponse(int code, String message){ + public ApiResponseMessage(int code, String message){ this.code = code; switch(code){ case ERROR: @@ -66,4 +66,3 @@ public class ApiResponse { this.message = message; } } - diff --git a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/NotFoundException.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/NotFoundException.java similarity index 86% rename from samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/NotFoundException.java rename to samples/server/petstore/jaxrs/src/main/java/io/swagger/api/NotFoundException.java index c8d4d6e16f1a..9c8410e47ab8 100644 --- a/samples/server-generator/java-jaxrs/output/src/main/java/com/wordnik/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/NotFoundException.java @@ -1,4 +1,4 @@ -package com.wordnik.api; +package io.swagger.api; public class NotFoundException extends ApiException { private int code; @@ -7,4 +7,3 @@ public class NotFoundException extends ApiException { this.code = code; } } - diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java new file mode 100644 index 000000000000..77d30c736ad5 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java @@ -0,0 +1,165 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import com.wordnik.swagger.annotations.*; +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.Pet; +import java.io.File; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.*; + +@Path("/pet") +@Api(value = "/pet", description = "the pet API") +public class PetApi { + + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Validation exception"), + + @ApiResponse(code = 404, message = "Pet not found"), + + @ApiResponse(code = 400, message = "Invalid ID supplied") }) + + public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @POST + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input") }) + + public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @GET + @Path("/findByStatus") + + @Produces({ "application/json", "application/xml" }) + // Pet + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid status value") }) + + public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter") @QueryParam("status") List status) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @GET + @Path("/findByTags") + + @Produces({ "application/json", "application/xml" }) + // Pet + @ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List") + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid tag value") }) + + public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @GET + @Path("/{petId}") + + @Produces({ "application/json", "application/xml" }) + // Pet + @ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Pet not found"), + + @ApiResponse(code = 400, message = "Invalid ID supplied") }) + + public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("petId") Long petId) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 405, message = "Invalid input") }) + + public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathParam("petId") String petId, + @ApiParam(value = "Updated name of the pet" )@FormParam("name") String name, + @ApiParam(value = "Updated status of the pet" )@FormParam("status") String status) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @DELETE + @Path("/{petId}") + + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid pet value") }) + + public Response deletePet(@ApiParam(value = "" )@HeaderParam("api_key") String api_key, + @ApiParam(value = "Pet id to delete",required=true ) @PathParam("petId") Long petId) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "uploads an image", notes = "", response = Void.class) + @ApiResponses(value = { }) + + public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathParam("petId") Long petId, + @ApiParam(value = "Additional data to pass to server" )@FormParam("additionalMetadata") String additionalMetadata, + @ApiParam(value = "file to upload") @FormDataParam("file") InputStream inputStream, + @ApiParam(value = "file detail") @FormDataParam("file") FormDataContentDisposition fileDetail) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + +} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/StoreApi.java new file mode 100644 index 000000000000..cc49b9340c82 --- /dev/null +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/StoreApi.java @@ -0,0 +1,93 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import com.wordnik.swagger.annotations.*; +import com.sun.jersey.multipart.FormDataParam; + +import java.util.Map; +import io.swagger.model.Order; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.*; + +@Path("/store") +@Api(value = "/store", description = "the store API") +public class StoreApi { + + @GET + @Path("/inventory") + + @Produces({ "application/json", "application/xml" }) + // Integer + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "map") + @ApiResponses(value = { }) + + public Response getInventory() + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @POST + @Path("/order") + + @Produces({ "application/json", "application/xml" }) + // Order + @ApiOperation(value = "Place an order for a pet", notes = "", response = Order.class) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid Order") }) + + public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @GET + @Path("/order/{orderId}") + + @Produces({ "application/json", "application/xml" }) + // Order + @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Order not found"), + + @ApiResponse(code = 400, message = "Invalid ID supplied") }) + + public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("orderId") String orderId) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @DELETE + @Path("/order/{orderId}") + + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "Order not found"), + + @ApiResponse(code = 400, message = "Invalid ID supplied") }) + + public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathParam("orderId") String orderId) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + +} diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/UserApi.java new file mode 100644 index 000000000000..c06d88e41f7f --- /dev/null +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/UserApi.java @@ -0,0 +1,158 @@ +package io.swagger.api; + +import io.swagger.model.*; + +import com.wordnik.swagger.annotations.*; +import com.sun.jersey.multipart.FormDataParam; + +import io.swagger.model.User; +import java.util.*; + +import java.util.List; +import io.swagger.api.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; +import javax.ws.rs.*; + +@Path("/user") +@Api(value = "/user", description = "the user API") +public class UserApi { + + @POST + + + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiResponses(value = { }) + + public Response createUser(@ApiParam(value = "Created user object" ) User body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @POST + @Path("/createWithArray") + + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiResponses(value = { }) + + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @POST + @Path("/createWithList") + + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) + @ApiResponses(value = { }) + + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @GET + @Path("/login") + + @Produces({ "application/json", "application/xml" }) + // String + @ApiOperation(value = "Logs user into the system", notes = "", response = String.class) + @ApiResponses(value = { + @ApiResponse(code = 400, message = "Invalid username/password supplied") }) + + public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username, + @ApiParam(value = "The password for login in clear text") @QueryParam("password") String password) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @GET + @Path("/logout") + + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) + @ApiResponses(value = { }) + + public Response logoutUser() + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @GET + @Path("/{username}") + + @Produces({ "application/json", "application/xml" }) + // User + @ApiOperation(value = "Get user by user name", notes = "", response = User.class) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "User not found"), + + @ApiResponse(code = 400, message = "Invalid username supplied") }) + + public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathParam("username") String username) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @PUT + @Path("/{username}") + + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "User not found"), + + @ApiResponse(code = 400, message = "Invalid user supplied") }) + + public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathParam("username") String username, + @ApiParam(value = "Updated user object" ) User body) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + + @DELETE + @Path("/{username}") + + @Produces({ "application/json", "application/xml" }) + // Void + @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) + @ApiResponses(value = { + @ApiResponse(code = 404, message = "User not found"), + + @ApiResponse(code = 400, message = "Invalid username supplied") }) + + public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathParam("username") String username) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + +} diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Category.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Category.java similarity index 70% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Category.java rename to samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Category.java index a2dc94401c9f..7c67f92e745c 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Category.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Category.java @@ -1,12 +1,21 @@ -package com.wordnik.petstore.model; +package io.swagger.model; + +import com.wordnik.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; -public class Category { - @JsonProperty("id") + +@ApiModel(description = "") +public class Category { + private Long id = null; - @JsonProperty("name") private String name = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -14,6 +23,11 @@ public class Category { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("name") public String getName() { return name; } @@ -21,14 +35,16 @@ public class Category { this.name = name; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Category {\n"); + sb.append(" id: ").append(id).append("\n"); sb.append(" name: ").append(name).append("\n"); sb.append("}\n"); return sb.toString(); } } - diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Order.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Order.java similarity index 56% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Order.java rename to samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Order.java index 28e1e74d27a3..884686b1cd73 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Order.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Order.java @@ -1,20 +1,29 @@ -package com.wordnik.petstore.model; - -import com.fasterxml.jackson.annotation.JsonProperty; +package io.swagger.model; import java.util.Date; -public class Order { - @JsonProperty("id") + +import com.wordnik.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class Order { + private Long id = null; - @JsonProperty("petId") private Long petId = null; - @JsonProperty("quantity") private Integer quantity = null; - /* Order Status */ - @JsonProperty("status") - private String status = null; - @JsonProperty("shipDate") private Date shipDate = null; + public enum StatusEnum { + placed, approved, delivered, + }; + private StatusEnum status = null; + private Boolean complete = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -22,6 +31,11 @@ public class Order { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("petId") public Long getPetId() { return petId; } @@ -29,6 +43,11 @@ public class Order { this.petId = petId; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("quantity") public Integer getQuantity() { return quantity; } @@ -36,13 +55,11 @@ public class Order { this.quantity = quantity; } - public String getStatus() { - return status; - } - public void setStatus(String status) { - this.status = status; - } - + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("shipDate") public Date getShipDate() { return shipDate; } @@ -50,17 +67,45 @@ public class Order { this.shipDate = shipDate; } + + /** + * Order Status + **/ + @ApiModelProperty(required = false, value = "Order Status") + @JsonProperty("status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("complete") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Order {\n"); + sb.append(" id: ").append(id).append("\n"); sb.append(" petId: ").append(petId).append("\n"); sb.append(" quantity: ").append(quantity).append("\n"); - sb.append(" status: ").append(status).append("\n"); sb.append(" shipDate: ").append(shipDate).append("\n"); + sb.append(" status: ").append(status).append("\n"); + sb.append(" complete: ").append(complete).append("\n"); sb.append("}\n"); return sb.toString(); } } - diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Pet.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Pet.java similarity index 61% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Pet.java rename to samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Pet.java index b12906bd2350..5a5cc2c8fb01 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Pet.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Pet.java @@ -1,24 +1,31 @@ -package com.wordnik.petstore.model; +package io.swagger.model; +import io.swagger.model.Category; +import io.swagger.model.Tag; +import java.util.*; + +import com.wordnik.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.*; -import com.wordnik.petstore.model.Category; -public class Pet { - /* unique identifier for the pet */ - @JsonProperty("id") + +@ApiModel(description = "") +public class Pet { + private Long id = null; - @JsonProperty("category") private Category category = null; - @JsonProperty("name") private String name = null; - @JsonProperty("photoUrls") - private List photoUrls = new ArrayList(); - @JsonProperty("tags") - private List tags = new ArrayList(); - /* pet status in the store */ - @JsonProperty("status") - private String status = null; + private List photoUrls = new ArrayList() ; + private List tags = new ArrayList() ; + public enum StatusEnum { + available, pending, sold, + }; + private StatusEnum status = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -26,6 +33,11 @@ public class Pet { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("category") public Category getCategory() { return category; } @@ -33,6 +45,11 @@ public class Pet { this.category = category; } + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("name") public String getName() { return name; } @@ -40,6 +57,11 @@ public class Pet { this.name = name; } + + /** + **/ + @ApiModelProperty(required = true, value = "") + @JsonProperty("photoUrls") public List getPhotoUrls() { return photoUrls; } @@ -47,6 +69,11 @@ public class Pet { this.photoUrls = photoUrls; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("tags") public List getTags() { return tags; } @@ -54,17 +81,26 @@ public class Pet { this.tags = tags; } - public String getStatus() { + + /** + * pet status in the store + **/ + @ApiModelProperty(required = false, value = "pet status in the store") + @JsonProperty("status") + public StatusEnum getStatus() { return status; } - public void setStatus(String status) { + public void setStatus(StatusEnum status) { this.status = status; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Pet {\n"); + sb.append(" id: ").append(id).append("\n"); sb.append(" category: ").append(category).append("\n"); sb.append(" name: ").append(name).append("\n"); @@ -75,4 +111,3 @@ public class Pet { return sb.toString(); } } - diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Tag.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Tag.java similarity index 71% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Tag.java rename to samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Tag.java index 52407da12671..4f98cb9ab636 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Tag.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/Tag.java @@ -1,12 +1,21 @@ -package com.wordnik.petstore.model; +package io.swagger.model; + +import com.wordnik.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; -public class Tag { - @JsonProperty("id") + +@ApiModel(description = "") +public class Tag { + private Long id = null; - @JsonProperty("name") private String name = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -14,6 +23,11 @@ public class Tag { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("name") public String getName() { return name; } @@ -21,14 +35,16 @@ public class Tag { this.name = name; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Tag {\n"); + sb.append(" id: ").append(id).append("\n"); sb.append(" name: ").append(name).append("\n"); sb.append("}\n"); return sb.toString(); } } - diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/User.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/User.java similarity index 76% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/User.java rename to samples/server/petstore/jaxrs/src/main/java/io/swagger/model/User.java index 117dd216308d..1af132430194 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/User.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/model/User.java @@ -1,25 +1,27 @@ -package com.wordnik.petstore.model; +package io.swagger.model; + +import com.wordnik.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; -public class User { - @JsonProperty("id") + +@ApiModel(description = "") +public class User { + private Long id = null; - @JsonProperty("firstName") - private String firstName = null; - @JsonProperty("username") private String username = null; - @JsonProperty("lastName") + private String firstName = null; private String lastName = null; - @JsonProperty("email") private String email = null; - @JsonProperty("password") private String password = null; - @JsonProperty("phone") private String phone = null; - /* User Status */ - @JsonProperty("userStatus") private Integer userStatus = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("id") public Long getId() { return id; } @@ -27,13 +29,11 @@ public class User { this.id = id; } - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("username") public String getUsername() { return username; } @@ -41,6 +41,23 @@ public class User { this.username = username; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("firstName") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("lastName") public String getLastName() { return lastName; } @@ -48,6 +65,11 @@ public class User { this.lastName = lastName; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("email") public String getEmail() { return email; } @@ -55,6 +77,11 @@ public class User { this.email = email; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("password") public String getPassword() { return password; } @@ -62,6 +89,11 @@ public class User { this.password = password; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + @JsonProperty("phone") public String getPhone() { return phone; } @@ -69,6 +101,12 @@ public class User { this.phone = phone; } + + /** + * User Status + **/ + @ApiModelProperty(required = false, value = "User Status") + @JsonProperty("userStatus") public Integer getUserStatus() { return userStatus; } @@ -76,13 +114,16 @@ public class User { this.userStatus = userStatus; } + + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class User {\n"); + sb.append(" id: ").append(id).append("\n"); - sb.append(" firstName: ").append(firstName).append("\n"); sb.append(" username: ").append(username).append("\n"); + sb.append(" firstName: ").append(firstName).append("\n"); sb.append(" lastName: ").append(lastName).append("\n"); sb.append(" email: ").append(email).append("\n"); sb.append(" password: ").append(password).append("\n"); @@ -92,4 +133,3 @@ public class User { return sb.toString(); } } - diff --git a/samples/server-generator/java-jaxrs/output/src/main/webapp/WEB-INF/web.xml b/samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml similarity index 72% rename from samples/server-generator/java-jaxrs/output/src/main/webapp/WEB-INF/web.xml rename to samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml index 2a758c9516b5..2708ad5dd48c 100644 --- a/samples/server-generator/java-jaxrs/output/src/main/webapp/WEB-INF/web.xml +++ b/samples/server/petstore/jaxrs/src/main/webapp/WEB-INF/web.xml @@ -8,7 +8,7 @@ com.sun.jersey.spi.container.servlet.ServletContainer com.sun.jersey.config.property.packages - com.wordnik.swagger.jaxrs.listing;com.wordnik.api + com.wordnik.swagger.jaxrs.json;com.wordnik.swagger.jaxrs.listing;io.swagger.api com.sun.jersey.spi.container.ContainerRequestFilters @@ -18,23 +18,25 @@ com.sun.jersey.api.json.POJOMappingFeature true + 1 + + + + DefaultJaxrsConfig + com.wordnik.swagger.jaxrs.config.DefaultJaxrsConfig api.version - 0.1 + 1.0.0 - swagger.version - 1.1 + swagger.api.title + Swagger Server swagger.api.basepath - http://localhost:8002/api + http://localhost:8002 - - swagger.security.filter - com.wordnik.swagger.sample.util.ApiAuthorizationFilterImpl - - 1 + 2 @@ -43,11 +45,10 @@ ApiOriginFilter - com.wordnik.api.ApiOriginFilter + io.swagger.api.ApiOriginFilter ApiOriginFilter /* - diff --git a/samples/server/petstore/nodejs/README.md b/samples/server/petstore/nodejs/README.md new file mode 100644 index 000000000000..ac6dc37d3dc0 --- /dev/null +++ b/samples/server/petstore/nodejs/README.md @@ -0,0 +1,8 @@ +# Swagger generated server + +## Overview +This server 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 a server stub. This is an example of building a node.js server. + +This example uses the [expressjs](http://expressjs.com/) framework. To see how to make this your own, look here: + +[README](https://github.com/wordnik/swagger-codegen/README.md) \ No newline at end of file diff --git a/samples/server-generator/node/output/App/apis/PetApi.js b/samples/server/petstore/nodejs/app/apis/PetApi.js similarity index 63% rename from samples/server-generator/node/output/App/apis/PetApi.js rename to samples/server/petstore/nodejs/app/apis/PetApi.js index 9d290732a63e..630b32359562 100644 --- a/samples/server-generator/node/output/App/apis/PetApi.js +++ b/samples/server/petstore/nodejs/app/apis/PetApi.js @@ -15,101 +15,26 @@ function writeResponse (response, data) { exports.models = models = require("../models.js"); -exports.getPetById = { +exports.updatePet = { 'spec': { "description" : "Operations about pets", - "path" : "/pet/{petId}", - "notes" : "Returns a pet based on ID", - "summary" : "Find pet by ID", - "method": "GET", - "params" : [].concat([params.path("petId", "ID of pet that needs to be fetched")]).concat([]).concat([]), - "type" : "Pet", - "responseMessages" : [errors.invalid('id'), errors.notFound('Pet')], - "nickname" : "getPetById" - }, - 'action': function (req,res) { - if (!req.params.petId) { - throw errors.invalid('petId'); - } - writeResponse(res, {message: "how about implementing getPetById as a GET method?"}); - } -}; -exports.deletePet = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet/{petId}", + "path" : "/pet", "notes" : "", - "summary" : "Deletes a pet", - "method": "DELETE", - "params" : [].concat([params.path("petId", "Pet id to delete")]).concat([]).concat([]), - "type" : "", - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "deletePet" - }, - 'action': function (req,res) { - if (!req.params.petId) { - throw errors.invalid('petId'); - } - writeResponse(res, {message: "how about implementing deletePet as a DELETE method?"}); - } -}; -exports.partialUpdate = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet/{petId}", - "notes" : "", - "summary" : "partial updates to a pet", - "method": "PATCH", - "params" : [].concat([params.path("petId", "ID of pet that needs to be fetched")]).concat([]).concat([params.body("body", "Pet", "Pet object that needs to be added to the store", true) + "summary" : "Update an existing pet", + "method": "PUT", + "params" : [].concat([]).concat([]).concat([ + params.body("body", "", "Pet object that needs to be added to the store", false) ]), - "type" : "List[Pet]", - "responseMessages" : [errors.invalid('id'), errors.notFound('List[Pet]')], - "nickname" : "partialUpdate" - }, - 'action': function (req,res) { - if (!req.params.petId) { - throw errors.invalid('petId'); - } - if (!req.params.body) { - throw errors.invalid('body'); - } - writeResponse(res, {message: "how about implementing partialUpdate as a PATCH method?"}); - } -}; -exports.updatePetWithForm = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet/{petId}", - "notes" : "", - "summary" : "Updates a pet in the store with form data", - "method": "POST", - "params" : [].concat([params.path("petId", "ID of pet that needs to be updated")]).concat([]).concat([]), + + "type" : "", + "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "updatePetWithForm" + "nickname" : "updatePet" }, 'action': function (req,res) { - if (!req.params.petId) { - throw errors.invalid('petId'); - } - writeResponse(res, {message: "how about implementing updatePetWithForm as a POST method?"}); - } -}; -exports.uploadFile = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet/uploadImage", - "notes" : "", - "summary" : "uploads an image", - "method": "POST", - "params" : [].concat([]).concat([]).concat([params.body("body", "File", "file to upload", false) - ]), - "type" : "", - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "uploadFile" - }, - 'action': function (req,res) { - writeResponse(res, {message: "how about implementing uploadFile as a POST method?"}); + + writeResponse(res, {message: "how about implementing updatePet as a PUT method?"}); } }; exports.addPet = { @@ -119,39 +44,21 @@ exports.addPet = { "notes" : "", "summary" : "Add a new pet to the store", "method": "POST", - "params" : [].concat([]).concat([]).concat([params.body("body", "Pet", "Pet object that needs to be added to the store", true) + "params" : [].concat([]).concat([]).concat([ + params.body("body", "", "Pet object that needs to be added to the store", false) ]), + + "type" : "", + "responseMessages" : [errors.invalid('id'), errors.notFound('')], "nickname" : "addPet" }, 'action': function (req,res) { - if (!req.params.body) { - throw errors.invalid('body'); - } + writeResponse(res, {message: "how about implementing addPet as a POST method?"}); } }; -exports.updatePet = { - 'spec': { - "description" : "Operations about pets", - "path" : "/pet", - "notes" : "", - "summary" : "Update an existing pet", - "method": "PUT", - "params" : [].concat([]).concat([]).concat([params.body("body", "Pet", "Pet object that needs to be updated in the store", true) - ]), - "type" : "", - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "updatePet" - }, - 'action': function (req,res) { - if (!req.params.body) { - throw errors.invalid('body'); - } - writeResponse(res, {message: "how about implementing updatePet as a PUT method?"}); - } -}; exports.findPetsByStatus = { 'spec': { "description" : "Operations about pets", @@ -159,15 +66,23 @@ exports.findPetsByStatus = { "notes" : "Multiple status values can be provided with comma seperated strings", "summary" : "Finds Pets by status", "method": "GET", - "params" : [params.query("status", "Status values that need to be considered for filter", "string", true, true, "LIST[available,pending,sold]", "available")].concat([]).concat([]).concat([]), - "type" : "List[Pet]", - "responseMessages" : [errors.invalid('id'), errors.notFound('List[Pet]')], + "params" : [ + params.query("status", "Status values that need to be considered for filter", "", false, false, "") + ].concat([]).concat([]).concat([]), + + "type": "array", + "items": { + + "$ref": "array" + }, + // container + + + "responseMessages" : [errors.invalid('id'), errors.notFound('array')], "nickname" : "findPetsByStatus" }, 'action': function (req,res) { - if (!req.params.status) { - throw errors.invalid('status'); - } + writeResponse(res, {message: "how about implementing findPetsByStatus as a GET method?"}); } }; @@ -178,16 +93,111 @@ exports.findPetsByTags = { "notes" : "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", "summary" : "Finds Pets by tags", "method": "GET", - "params" : [params.query("tags", "Tags to filter by", "string", true, true, "")].concat([]).concat([]).concat([]), - "type" : "List[Pet]", - "responseMessages" : [errors.invalid('id'), errors.notFound('List[Pet]')], + "params" : [ + params.query("tags", "Tags to filter by", "", false, false, "") + ].concat([]).concat([]).concat([]), + + "type": "array", + "items": { + + "$ref": "array" + }, + // container + + + "responseMessages" : [errors.invalid('id'), errors.notFound('array')], "nickname" : "findPetsByTags" }, 'action': function (req,res) { - if (!req.params.tags) { - throw errors.invalid('tags'); - } + writeResponse(res, {message: "how about implementing findPetsByTags as a GET method?"}); } }; - +exports.getPetById = { + 'spec': { + "description" : "Operations about pets", + "path" : "/pet/{petId}", + "notes" : "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", + "summary" : "Find pet by ID", + "method": "GET", + "params" : [].concat([ + params.path("petId", "ID of pet that needs to be fetched") + ]).concat([]).concat([]), + + + "type" : "Pet", + + "responseMessages" : [errors.invalid('id'), errors.notFound('Pet')], + "nickname" : "getPetById" + }, + 'action': function (req,res) { + + writeResponse(res, {message: "how about implementing getPetById as a GET method?"}); + } +}; +exports.updatePetWithForm = { + 'spec': { + "description" : "Operations about pets", + "path" : "/pet/{petId}", + "notes" : "", + "summary" : "Updates a pet in the store with form data", + "method": "POST", + "params" : [].concat([ + params.path("petId", "ID of pet that needs to be updated") + ]).concat([]).concat([]), + + + "type" : "", + + "responseMessages" : [errors.invalid('id'), errors.notFound('')], + "nickname" : "updatePetWithForm" + }, + 'action': function (req,res) { + + writeResponse(res, {message: "how about implementing updatePetWithForm as a POST method?"}); + } +}; +exports.deletePet = { + 'spec': { + "description" : "Operations about pets", + "path" : "/pet/{petId}", + "notes" : "", + "summary" : "Deletes a pet", + "method": "DELETE", + "params" : [].concat([ + params.path("petId", "Pet id to delete") + ]).concat([ + params.header("api_key", "") + ]).concat([]), + + + "type" : "", + + "responseMessages" : [errors.invalid('id'), errors.notFound('')], + "nickname" : "deletePet" + }, + 'action': function (req,res) { + + writeResponse(res, {message: "how about implementing deletePet as a DELETE method?"}); + } +}; +exports.uploadFile = { + 'spec': { + "description" : "Operations about pets", + "path" : "/pet/{petId}/uploadImage", + "notes" : "", + "summary" : "uploads an image", + "method": "POST", + "params" : [].concat([]).concat([]).concat([]), + + + "type" : "", + + "responseMessages" : [errors.invalid('id'), errors.notFound('')], + "nickname" : "uploadFile" + }, + 'action': function (req,res) { + + writeResponse(res, {message: "how about implementing uploadFile as a POST method?"}); + } +}; diff --git a/samples/server-generator/node/output/App/apis/StoreApi.js b/samples/server/petstore/nodejs/app/apis/StoreApi.js similarity index 62% rename from samples/server-generator/node/output/App/apis/StoreApi.js rename to samples/server/petstore/nodejs/app/apis/StoreApi.js index eb5411c91b02..bbe929bd492c 100644 --- a/samples/server-generator/node/output/App/apis/StoreApi.js +++ b/samples/server/petstore/nodejs/app/apis/StoreApi.js @@ -15,42 +15,29 @@ function writeResponse (response, data) { exports.models = models = require("../models.js"); -exports.getOrderById = { +exports.getInventory = { 'spec': { "description" : "Operations about pets", - "path" : "/store/order/{orderId}", - "notes" : "For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors", - "summary" : "Find purchase order by ID", + "path" : "/store/inventory", + "notes" : "Returns a map of status codes to quantities", + "summary" : "Returns pet inventories by status", "method": "GET", - "params" : [].concat([params.path("orderId", "ID of pet that needs to be fetched")]).concat([]).concat([]), - "type" : "Order", - "responseMessages" : [errors.invalid('id'), errors.notFound('Order')], - "nickname" : "getOrderById" + "params" : [].concat([]).concat([]).concat([]), + + "type": "Map", + "items": { + + "$ref": "map" + }, + // container + + + "responseMessages" : [errors.invalid('id'), errors.notFound('Map')], + "nickname" : "getInventory" }, 'action': function (req,res) { - if (!req.params.orderId) { - throw errors.invalid('orderId'); - } - writeResponse(res, {message: "how about implementing getOrderById as a GET method?"}); - } -}; -exports.deleteOrder = { - 'spec': { - "description" : "Operations about pets", - "path" : "/store/order/{orderId}", - "notes" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "summary" : "Delete purchase order by ID", - "method": "DELETE", - "params" : [].concat([params.path("orderId", "ID of the order that needs to be deleted")]).concat([]).concat([]), - "type" : "", - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "deleteOrder" - }, - 'action': function (req,res) { - if (!req.params.orderId) { - throw errors.invalid('orderId'); - } - writeResponse(res, {message: "how about implementing deleteOrder as a DELETE method?"}); + + writeResponse(res, {message: "how about implementing getInventory as a GET method?"}); } }; exports.placeOrder = { @@ -60,17 +47,62 @@ exports.placeOrder = { "notes" : "", "summary" : "Place an order for a pet", "method": "POST", - "params" : [].concat([]).concat([]).concat([params.body("body", "Order", "order placed for purchasing the pet", true) + "params" : [].concat([]).concat([]).concat([ + params.body("body", "", "order placed for purchasing the pet", false) ]), - "type" : "", - "responseMessages" : [errors.invalid('id'), errors.notFound('')], + + + "type" : "Order", + + "responseMessages" : [errors.invalid('id'), errors.notFound('Order')], "nickname" : "placeOrder" }, 'action': function (req,res) { - if (!req.params.body) { - throw errors.invalid('body'); - } + writeResponse(res, {message: "how about implementing placeOrder as a POST method?"}); } }; - +exports.getOrderById = { + 'spec': { + "description" : "Operations about pets", + "path" : "/store/order/{orderId}", + "notes" : "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + "summary" : "Find purchase order by ID", + "method": "GET", + "params" : [].concat([ + params.path("orderId", "ID of pet that needs to be fetched") + ]).concat([]).concat([]), + + + "type" : "Order", + + "responseMessages" : [errors.invalid('id'), errors.notFound('Order')], + "nickname" : "getOrderById" + }, + 'action': function (req,res) { + + writeResponse(res, {message: "how about implementing getOrderById as a GET method?"}); + } +}; +exports.deleteOrder = { + 'spec': { + "description" : "Operations about pets", + "path" : "/store/order/{orderId}", + "notes" : "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "summary" : "Delete purchase order by ID", + "method": "DELETE", + "params" : [].concat([ + params.path("orderId", "ID of the order that needs to be deleted") + ]).concat([]).concat([]), + + + "type" : "", + + "responseMessages" : [errors.invalid('id'), errors.notFound('')], + "nickname" : "deleteOrder" + }, + 'action': function (req,res) { + + writeResponse(res, {message: "how about implementing deleteOrder as a DELETE method?"}); + } +}; diff --git a/samples/server-generator/node/output/App/apis/UserApi.js b/samples/server/petstore/nodejs/app/apis/UserApi.js similarity index 72% rename from samples/server-generator/node/output/App/apis/UserApi.js rename to samples/server/petstore/nodejs/app/apis/UserApi.js index 326174fb1ae2..02a17bff0870 100644 --- a/samples/server-generator/node/output/App/apis/UserApi.js +++ b/samples/server/petstore/nodejs/app/apis/UserApi.js @@ -15,65 +15,70 @@ function writeResponse (response, data) { exports.models = models = require("../models.js"); -exports.updateUser = { +exports.createUser = { 'spec': { "description" : "Operations about pets", - "path" : "/user/{username}", + "path" : "/user", "notes" : "This can only be done by the logged in user.", - "summary" : "Updated user", - "method": "PUT", - "params" : [].concat([params.path("username", "name that need to be deleted")]).concat([]).concat([params.body("body", "User", "Updated user object", true) + "summary" : "Create user", + "method": "POST", + "params" : [].concat([]).concat([]).concat([ + params.body("body", "", "Created user object", false) ]), + + "type" : "", + "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "updateUser" + "nickname" : "createUser" }, 'action': function (req,res) { - if (!req.params.username) { - throw errors.invalid('username'); - } - if (!req.params.body) { - throw errors.invalid('body'); - } - writeResponse(res, {message: "how about implementing updateUser as a PUT method?"}); + + writeResponse(res, {message: "how about implementing createUser as a POST method?"}); } }; -exports.deleteUser = { +exports.createUsersWithArrayInput = { 'spec': { "description" : "Operations about pets", - "path" : "/user/{username}", - "notes" : "This can only be done by the logged in user.", - "summary" : "Delete user", - "method": "DELETE", - "params" : [].concat([params.path("username", "The name that needs to be deleted")]).concat([]).concat([]), - "type" : "", - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "deleteUser" - }, - 'action': function (req,res) { - if (!req.params.username) { - throw errors.invalid('username'); - } - writeResponse(res, {message: "how about implementing deleteUser as a DELETE method?"}); - } -}; -exports.getUserByName = { - 'spec': { - "description" : "Operations about pets", - "path" : "/user/{username}", + "path" : "/user/createWithArray", "notes" : "", - "summary" : "Get user by user name", - "method": "GET", - "params" : [].concat([params.path("username", "The name that needs to be fetched. Use user1 for testing.")]).concat([]).concat([]), - "type" : "User", - "responseMessages" : [errors.invalid('id'), errors.notFound('User')], - "nickname" : "getUserByName" + "summary" : "Creates list of users with given input array", + "method": "POST", + "params" : [].concat([]).concat([]).concat([ + params.body("body", "", "List of user object", false) + ]), + + + "type" : "", + + "responseMessages" : [errors.invalid('id'), errors.notFound('')], + "nickname" : "createUsersWithArrayInput" }, 'action': function (req,res) { - if (!req.params.username) { - throw errors.invalid('username'); - } - writeResponse(res, {message: "how about implementing getUserByName as a GET method?"}); + + writeResponse(res, {message: "how about implementing createUsersWithArrayInput as a POST method?"}); + } +}; +exports.createUsersWithListInput = { + 'spec': { + "description" : "Operations about pets", + "path" : "/user/createWithList", + "notes" : "", + "summary" : "Creates list of users with given input array", + "method": "POST", + "params" : [].concat([]).concat([]).concat([ + params.body("body", "", "List of user object", false) + ]), + + + "type" : "", + + "responseMessages" : [errors.invalid('id'), errors.notFound('')], + "nickname" : "createUsersWithListInput" + }, + 'action': function (req,res) { + + writeResponse(res, {message: "how about implementing createUsersWithListInput as a POST method?"}); } }; exports.loginUser = { @@ -83,18 +88,20 @@ exports.loginUser = { "notes" : "", "summary" : "Logs user into the system", "method": "GET", - "params" : [params.query("username", "The user name for login", "string", true, false, ""),params.query("password", "The password for login in clear text", "string", true, false, "")].concat([]).concat([]).concat([]), + "params" : [ + params.query("username", "The user name for login", "", false, false, ""), + + params.query("password", "The password for login in clear text", "", false, false, "") + ].concat([]).concat([]).concat([]), + + "type" : "String", + "responseMessages" : [errors.invalid('id'), errors.notFound('String')], "nickname" : "loginUser" }, 'action': function (req,res) { - if (!req.params.username) { - throw errors.invalid('username'); - } - if (!req.params.password) { - throw errors.invalid('password'); - } + writeResponse(res, {message: "how about implementing loginUser as a GET method?"}); } }; @@ -106,72 +113,83 @@ exports.logoutUser = { "summary" : "Logs out current logged in user session", "method": "GET", "params" : [].concat([]).concat([]).concat([]), + + "type" : "", + "responseMessages" : [errors.invalid('id'), errors.notFound('')], "nickname" : "logoutUser" }, 'action': function (req,res) { + writeResponse(res, {message: "how about implementing logoutUser as a GET method?"}); } }; -exports.createUser = { +exports.getUserByName = { 'spec': { "description" : "Operations about pets", - "path" : "/user", + "path" : "/user/{username}", + "notes" : "", + "summary" : "Get user by user name", + "method": "GET", + "params" : [].concat([ + params.path("username", "The name that needs to be fetched. Use user1 for testing. ") + ]).concat([]).concat([]), + + + "type" : "User", + + "responseMessages" : [errors.invalid('id'), errors.notFound('User')], + "nickname" : "getUserByName" + }, + 'action': function (req,res) { + + writeResponse(res, {message: "how about implementing getUserByName as a GET method?"}); + } +}; +exports.updateUser = { + 'spec': { + "description" : "Operations about pets", + "path" : "/user/{username}", "notes" : "This can only be done by the logged in user.", - "summary" : "Create user", - "method": "POST", - "params" : [].concat([]).concat([]).concat([params.body("body", "User", "Created user object", true) + "summary" : "Updated user", + "method": "PUT", + "params" : [].concat([ + params.path("username", "name that need to be deleted") + ]).concat([]).concat([ + params.body("body", "", "Updated user object", false) ]), + + "type" : "", + "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "createUser" + "nickname" : "updateUser" }, 'action': function (req,res) { - if (!req.params.body) { - throw errors.invalid('body'); - } - writeResponse(res, {message: "how about implementing createUser as a POST method?"}); + + writeResponse(res, {message: "how about implementing updateUser as a PUT method?"}); } }; -exports.createUsersWithArrayInput = { +exports.deleteUser = { 'spec': { "description" : "Operations about pets", - "path" : "/user/createWithArray", - "notes" : "", - "summary" : "Creates list of users with given input array", - "method": "POST", - "params" : [].concat([]).concat([]).concat([params.body("body", "Array[User]", "List of user object", true) - ]), + "path" : "/user/{username}", + "notes" : "This can only be done by the logged in user.", + "summary" : "Delete user", + "method": "DELETE", + "params" : [].concat([ + params.path("username", "The name that needs to be deleted") + ]).concat([]).concat([]), + + "type" : "", + "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "createUsersWithArrayInput" + "nickname" : "deleteUser" }, 'action': function (req,res) { - if (!req.params.body) { - throw errors.invalid('body'); - } - writeResponse(res, {message: "how about implementing createUsersWithArrayInput as a POST method?"}); + + writeResponse(res, {message: "how about implementing deleteUser as a DELETE method?"}); } }; -exports.createUsersWithListInput = { - 'spec': { - "description" : "Operations about pets", - "path" : "/user/createWithList", - "notes" : "", - "summary" : "Creates list of users with given list input", - "method": "POST", - "params" : [].concat([]).concat([]).concat([params.body("body", "Array[User]", "List of user object", true) - ]), - "type" : "", - "responseMessages" : [errors.invalid('id'), errors.notFound('')], - "nickname" : "createUsersWithListInput" - }, - 'action': function (req,res) { - if (!req.params.body) { - throw errors.invalid('body'); - } - writeResponse(res, {message: "how about implementing createUsersWithListInput as a POST method?"}); - } -}; - diff --git a/samples/server-generator/node/output/App/models.js b/samples/server/petstore/nodejs/app/models.js similarity index 72% rename from samples/server-generator/node/output/App/models.js rename to samples/server/petstore/nodejs/app/models.js index 98712f2fad10..f54703af71d4 100644 --- a/samples/server-generator/node/output/App/models.js +++ b/samples/server/petstore/nodejs/app/models.js @@ -1,84 +1,39 @@ exports.models = { - "Tag": { - "id" : "Tag", - "name" : "", + "User": { "properties" : { "id" : { "type" : "integer", "format" : "int64" }, - "name" : { - "type" : "string" - } - } -}, - - "User": { - "id" : "User", - "name" : "", - "properties" : { - "email" : { - "type" : "string" - }, "username" : { "type" : "string" }, - "userStatus" : { - "type" : "integer", - "format" : "int32", - "description" : "User Status", - "enum" : [ "1-registered", "2-active", "3-closed" ] - }, - "lastName" : { - "type" : "string" - }, "firstName" : { "type" : "string" }, - "id" : { - "type" : "integer", - "format" : "int64" + "lastName" : { + "type" : "string" }, - "phone" : { + "email" : { "type" : "string" }, "password" : { "type" : "string" + }, + "phone" : { + "type" : "string" + }, + "userStatus" : { + "type" : "integer", + "format" : "int32", + "description" : "User Status" } - } -}, - - "Order": { - "id" : "Order", - "name" : "", - "properties" : { - "shipDate" : { - "type" : "string", - "format" : "date-time" - }, - "quantity" : { - "type" : "integer", - "format" : "int32" - }, - "petId" : { - "type" : "integer", - "format" : "int64" - }, - "id" : { - "type" : "integer", - "format" : "int64" - }, - "status" : { - "type" : "string", - "description" : "Order Status", - "enum" : [ "placed", " approved", " delivered" ] - } - } -}, - - "Category": { - "id" : "Category", - "name" : "", + }, + "xml" : { + "name" : "User" + }, + "id" : "User" +},"Category": { "properties" : { "id" : { "type" : "integer", @@ -87,22 +42,24 @@ exports.models = { "name" : { "type" : "string" } - } -}, - - "Pet": { - "id" : "Pet", - "name" : "", - "required" : [ "id", "name" ], + }, + "xml" : { + "name" : "Category" + }, + "id" : "Category" +},"Pet": { + "required" : [ "name", "photoUrls" ], "properties" : { - "name" : { - "type" : "string" + "id" : { + "type" : "integer", + "format" : "int64" }, - "tags" : { - "type" : "array", - "items" : { - "$ref" : "Tag" - } + "category" : { + "$ref" : "Category" + }, + "name" : { + "type" : "string", + "example" : "doggie" }, "photoUrls" : { "type" : "array", @@ -110,20 +67,66 @@ exports.models = { "type" : "string" } }, - "id" : { - "type" : "integer", - "format" : "int64", - "description" : "unique identifier for the pet" + "tags" : { + "type" : "array", + "items" : { + "$ref" : "Tag" + } }, "status" : { "type" : "string", "description" : "pet status in the store", "enum" : [ "available", "pending", "sold" ] - }, - "category" : { - "type" : "Category" } - } + }, + "xml" : { + "name" : "Pet" + }, + "id" : "Pet" +},"Tag": { + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "name" : { + "type" : "string" + } + }, + "xml" : { + "name" : "Tag" + }, + "id" : "Tag" +},"Order": { + "properties" : { + "id" : { + "type" : "integer", + "format" : "int64" + }, + "petId" : { + "type" : "integer", + "format" : "int64" + }, + "quantity" : { + "type" : "integer", + "format" : "int32" + }, + "shipDate" : { + "type" : "string", + "format" : "date-time" + }, + "status" : { + "type" : "string", + "description" : "Order Status", + "enum" : [ "placed", "approved", "delivered" ] + }, + "complete" : { + "type" : "boolean" + } + }, + "xml" : { + "name" : "Order" + }, + "id" : "Order" } - - } +} \ No newline at end of file diff --git a/samples/server/petstore/nodejs/main.js b/samples/server/petstore/nodejs/main.js new file mode 100644 index 000000000000..bd84d18c3e2c --- /dev/null +++ b/samples/server/petstore/nodejs/main.js @@ -0,0 +1,65 @@ +var express = require("express") + , url = require("url") + , cors = require("cors") + , app = express() + , swagger = require("swagger-node-express") + , db = false + + +var corsOptions = { + credentials: true, + origin: function(origin,callback) { + if(origin===undefined) { + callback(null,false); + } else { + callback(null,true); + } + } +}; + +app.use(express.json()); +app.use(express.urlencoded()); +app.use(cors(corsOptions)); + +var subpath = express(); + +app.use("/v2", subpath); + +swagger.setAppHandler(subpath); + +swagger.configureSwaggerPaths("", "api-docs", "") + +var models = require("./app/models.js"); + +var UserApi = require("./app/apis/UserApi.js"); +var StoreApi = require("./app/apis/StoreApi.js"); +var PetApi = require("./app/apis/PetApi.js"); + +swagger.addModels(models) + .addPOST(UserApi.createUser) + .addPOST(UserApi.createUsersWithArrayInput) + .addPOST(UserApi.createUsersWithListInput) + .addGET(UserApi.loginUser) + .addGET(UserApi.logoutUser) + .addGET(UserApi.getUserByName) + .addPUT(UserApi.updateUser) + .addDELETE(UserApi.deleteUser) + .addGET(StoreApi.getInventory) + .addPOST(StoreApi.placeOrder) + .addGET(StoreApi.getOrderById) + .addDELETE(StoreApi.deleteOrder) + .addPUT(PetApi.updatePet) + .addPOST(PetApi.addPet) + .addGET(PetApi.findPetsByStatus) + .addGET(PetApi.findPetsByTags) + .addGET(PetApi.getPetById) + .addPOST(PetApi.updatePetWithForm) + .addDELETE(PetApi.deletePet) + .addPOST(PetApi.uploadFile) + ; + +// configures the app +swagger.configure("http://localhost:8002/v2", "0.1"); + +// start the server +app.listen(8002); diff --git a/samples/server-generator/node/output/package.json b/samples/server/petstore/nodejs/package.json similarity index 70% rename from samples/server-generator/node/output/package.json rename to samples/server/petstore/nodejs/package.json index 1581b6a42542..09424acf1575 100644 --- a/samples/server-generator/node/output/package.json +++ b/samples/server/petstore/nodejs/package.json @@ -1,9 +1,9 @@ { - "name": "swagger-sample-app", + "name": "swagger-client", "description": "Wordnik node.js server generator", "version": "1.0.0", - "homepage": "http://swagger.wordnik.com", - "main": "./app/main.js", + "homepage": "", + "main": "./main.js", "engines": { "node": ">= 0.8.x" }, @@ -13,4 +13,4 @@ "cors": "2.1.1", "express": "3.x" } -} +} \ No newline at end of file diff --git a/samples/server-generator/java-jaxrs/output/README.md b/samples/server/petstore/scalatra/README.md similarity index 93% rename from samples/server-generator/java-jaxrs/output/README.md rename to samples/server/petstore/scalatra/README.md index 45d023e4da61..f8a560b776f5 100644 --- a/samples/server-generator/java-jaxrs/output/README.md +++ b/samples/server/petstore/scalatra/README.md @@ -7,4 +7,4 @@ is an example of building a swagger-enabled scalatra server. This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: -[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) +[README](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file diff --git a/samples/server-generator/scalatra/output/build.sbt b/samples/server/petstore/scalatra/build.sbt similarity index 79% rename from samples/server-generator/scalatra/output/build.sbt rename to samples/server/petstore/scalatra/build.sbt index 9f04adc46ba6..afe84c2c7f09 100644 --- a/samples/server-generator/scalatra/output/build.sbt +++ b/samples/server/petstore/scalatra/build.sbt @@ -18,24 +18,27 @@ name := "scalatra-sample" version := "0.1.0-SNAPSHOT" -scalaVersion := "2.10.0" +scalaVersion := "2.11.2" + +scalacOptions += "-language:postfixOps" libraryDependencies ++= Seq( - "org.scalatest" %% "scalatest" % "2.0" % "test", + "org.scalatest" %% "scalatest" % "2.2.1" % "test", "org.scalatra" %% "scalatra" % "2.3.0.RC3", "org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3", "org.scalatra" %% "scalatra-json" % "2.3.0.RC3", "org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3", "org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3", "org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3", - "org.json4s" %% "json4s-jackson" % "3.1.0", - "org.json4s" %% "json4s-ext" % "3.1.0", + "org.json4s" %% "json4s-jackson" % "3.2.10", + "org.json4s" %% "json4s-ext" % "3.2.10", "commons-codec" % "commons-codec" % "1.7", - "net.databinder.dispatch" %% "dispatch-core" % "0.9.5", - "net.databinder.dispatch" %% "json4s-jackson" % "0.9.5", - "com.typesafe.akka" %% "akka-actor" % "2.1.0", - "org.eclipse.jetty" % "jetty-server" % "8.1.7.v20120910" % "container;provided", - "org.eclipse.jetty" % "jetty-webapp" % "8.1.7.v20120910" % "container;provided", + "net.databinder.dispatch" %% "dispatch-core" % "0.11.2", + //"net.databinder.dispatch" %% "json4s-jackson" % "0.11.2", + "net.databinder.dispatch" %% "dispatch-json4s-jackson" % "0.11.2", + "com.typesafe.akka" %% "akka-actor" % "2.3.6", + "org.eclipse.jetty" % "jetty-server" % "9.2.3.v20140905" % "container;compile;test", + "org.eclipse.jetty" % "jetty-webapp" % "9.2.3.v20140905" % "container;compile;test", "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar")) ) @@ -51,9 +54,11 @@ ivyXML := -mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) => - { +mergeStrategy in assembly <<= (mergeStrategy in assembly) { + (old) => { case "about.html" => MergeStrategy.discard case x => old(x) } } + +net.virtualvoid.sbt.graph.Plugin.graphSettings diff --git a/samples/server/petstore/scalatra/project/build.properties b/samples/server/petstore/scalatra/project/build.properties new file mode 100644 index 000000000000..be6c454fbaca --- /dev/null +++ b/samples/server/petstore/scalatra/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.13.5 diff --git a/samples/server/petstore/scalatra/project/plugins.sbt b/samples/server/petstore/scalatra/project/plugins.sbt new file mode 100644 index 000000000000..7358abbbbc6a --- /dev/null +++ b/samples/server/petstore/scalatra/project/plugins.sbt @@ -0,0 +1,9 @@ +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.1") + +addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "0.7.5") + +addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.9.0") + +addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.3.0") + +addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.7.4") diff --git a/samples/server/petstore/scalatra/sbt b/samples/server/petstore/scalatra/sbt new file mode 100644 index 000000000000..08e58821219c --- /dev/null +++ b/samples/server/petstore/scalatra/sbt @@ -0,0 +1,525 @@ +#!/usr/bin/env bash +# +# A more capable sbt runner, coincidentally also called sbt. +# Author: Paul Phillips + +# todo - make this dynamic +declare -r sbt_release_version="0.13.6" +declare -r sbt_unreleased_version="0.13.6" +declare -r buildProps="project/build.properties" + +declare sbt_jar sbt_dir sbt_create sbt_version +declare scala_version sbt_explicit_version +declare verbose noshare batch trace_level log_level +declare sbt_saved_stty debugUs + +echoerr () { echo >&2 "$@"; } +vlog () { [[ -n "$verbose" ]] && echoerr "$@"; } + +# spaces are possible, e.g. sbt.version = 0.13.0 +build_props_sbt () { + [[ -r "$buildProps" ]] && \ + grep '^sbt\.version' "$buildProps" | tr '=' ' ' | awk '{ print $2; }' +} + +update_build_props_sbt () { + local ver="$1" + local old="$(build_props_sbt)" + + [[ -r "$buildProps" ]] && [[ "$ver" != "$old" ]] && { + perl -pi -e "s/^sbt\.version\b.*\$/sbt.version=${ver}/" "$buildProps" + grep -q '^sbt.version[ =]' "$buildProps" || printf "\nsbt.version=%s\n" "$ver" >> "$buildProps" + + vlog "!!!" + vlog "!!! Updated file $buildProps setting sbt.version to: $ver" + vlog "!!! Previous value was: $old" + vlog "!!!" + } +} + +set_sbt_version () { + sbt_version="${sbt_explicit_version:-$(build_props_sbt)}" + [[ -n "$sbt_version" ]] || sbt_version=$sbt_release_version + export sbt_version +} + +# restore stty settings (echo in particular) +onSbtRunnerExit() { + [[ -n "$sbt_saved_stty" ]] || return + vlog "" + vlog "restoring stty: $sbt_saved_stty" + stty "$sbt_saved_stty" + unset sbt_saved_stty +} + +# save stty and trap exit, to ensure echo is reenabled if we are interrupted. +trap onSbtRunnerExit EXIT +sbt_saved_stty="$(stty -g 2>/dev/null)" +vlog "Saved stty: $sbt_saved_stty" + +# this seems to cover the bases on OSX, and someone will +# have to tell me about the others. +get_script_path () { + local path="$1" + [[ -L "$path" ]] || { echo "$path" ; return; } + + local target="$(readlink "$path")" + if [[ "${target:0:1}" == "/" ]]; then + echo "$target" + else + echo "${path%/*}/$target" + fi +} + +die() { + echo "Aborting: $@" + exit 1 +} + +make_url () { + version="$1" + + case "$version" in + 0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;; + 0.10.* ) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + 0.11.[12]) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + *) echo "$sbt_launch_repo/org.scala-sbt/sbt-launch/$version/sbt-launch.jar" ;; + esac +} + +init_default_option_file () { + local overriding_var="${!1}" + local default_file="$2" + if [[ ! -r "$default_file" && "$overriding_var" =~ ^@(.*)$ ]]; then + local envvar_file="${BASH_REMATCH[1]}" + if [[ -r "$envvar_file" ]]; then + default_file="$envvar_file" + fi + fi + echo "$default_file" +} + +declare -r cms_opts="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC" +declare -r jit_opts="-XX:ReservedCodeCacheSize=256m -XX:+TieredCompilation" +declare -r default_jvm_opts_common="-Xms512m -Xmx1536m -Xss2m $jit_opts $cms_opts" +declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" +declare -r latest_28="2.8.2" +declare -r latest_29="2.9.3" +declare -r latest_210="2.10.4" +declare -r latest_211="2.11.2" + +declare -r script_path="$(get_script_path "$BASH_SOURCE")" +declare -r script_name="${script_path##*/}" + +# some non-read-onlies set with defaults +declare java_cmd="java" +declare sbt_opts_file="$(init_default_option_file SBT_OPTS .sbtopts)" +declare jvm_opts_file="$(init_default_option_file JVM_OPTS .jvmopts)" +declare sbt_launch_repo="http://typesafe.artifactoryonline.com/typesafe/ivy-releases" + +# pull -J and -D options to give to java. +declare -a residual_args +declare -a java_args +declare -a scalac_args +declare -a sbt_commands + +# args to jvm/sbt via files or environment variables +declare -a extra_jvm_opts extra_sbt_opts + +# if set, use JAVA_HOME over java found in path +[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java" + +# directory to store sbt launchers +declare sbt_launch_dir="$HOME/.sbt/launchers" +[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir" +[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers.XXXXXX)" + +java_version () { + local version=$("$java_cmd" -version 2>&1 | grep -e 'java version' | awk '{ print $3 }' | tr -d \") + vlog "Detected Java version: $version" + echo "${version:2:1}" +} + +# MaxPermSize critical on pre-8 jvms but incurs noisy warning on 8+ +default_jvm_opts () { + local v="$(java_version)" + if [[ $v -ge 8 ]]; then + echo "$default_jvm_opts_common" + else + echo "-XX:MaxPermSize=384m $default_jvm_opts_common" + fi +} + +build_props_scala () { + if [[ -r "$buildProps" ]]; then + versionLine="$(grep '^build.scala.versions' "$buildProps")" + versionString="${versionLine##build.scala.versions=}" + echo "${versionString%% .*}" + fi +} + +execRunner () { + # print the arguments one to a line, quoting any containing spaces + vlog "# Executing command line:" && { + for arg; do + if [[ -n "$arg" ]]; then + if printf "%s\n" "$arg" | grep -q ' '; then + printf >&2 "\"%s\"\n" "$arg" + else + printf >&2 "%s\n" "$arg" + fi + fi + done + vlog "" + } + + [[ -n "$batch" ]] && exec /dev/null; then + curl --fail --silent "$url" --output "$jar" + elif which wget >/dev/null; then + wget --quiet -O "$jar" "$url" + fi + } && [[ -r "$jar" ]] +} + +acquire_sbt_jar () { + sbt_url="$(jar_url "$sbt_version")" + sbt_jar="$(jar_file "$sbt_version")" + + [[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar" +} + +usage () { + cat < display stack traces with a max of frames (default: -1, traces suppressed) + -debug-inc enable debugging log for the incremental compiler + -no-colors disable ANSI color codes + -sbt-create start sbt even if current directory contains no sbt project + -sbt-dir path to global settings/plugins directory (default: ~/.sbt/) + -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11+) + -ivy path to local Ivy repository (default: ~/.ivy2) + -no-share use all local caches; no sharing + -offline put sbt in offline mode + -jvm-debug Turn on JVM debugging, open at the given port. + -batch Disable interactive mode + -prompt Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted + + # sbt version (default: sbt.version from $buildProps if present, otherwise $sbt_release_version) + -sbt-force-latest force the use of the latest release of sbt: $sbt_release_version + -sbt-version use the specified version of sbt (default: $sbt_release_version) + -sbt-dev use the latest pre-release version of sbt: $sbt_unreleased_version + -sbt-jar use the specified jar as the sbt launcher + -sbt-launch-dir directory to hold sbt launchers (default: ~/.sbt/launchers) + -sbt-launch-repo repo url for downloading sbt launcher jar (default: $sbt_launch_repo) + + # scala version (default: as chosen by sbt) + -28 use $latest_28 + -29 use $latest_29 + -210 use $latest_210 + -211 use $latest_211 + -scala-home use the scala build at the specified directory + -scala-version use the specified version of scala + -binary-version use the specified scala version when searching for dependencies + + # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) + -java-home alternate JAVA_HOME + + # passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution + # The default set is used if JVM_OPTS is unset and no -jvm-opts file is found + $(default_jvm_opts) + JVM_OPTS environment variable holding either the jvm args directly, or + the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts') + Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument. + -jvm-opts file containing jvm args (if not given, .jvmopts in project root is used if present) + -Dkey=val pass -Dkey=val directly to the jvm + -J-X pass option -X directly to the jvm (-J is stripped) + + # passing options to sbt, OR to this runner + SBT_OPTS environment variable holding either the sbt args directly, or + the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts') + Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument. + -sbt-opts file containing sbt args (if not given, .sbtopts in project root is used if present) + -S-X add -X to sbt's scalacOptions (-S is stripped) +EOM +} + +addJava () { + vlog "[addJava] arg = '$1'" + java_args=( "${java_args[@]}" "$1" ) +} +addSbt () { + vlog "[addSbt] arg = '$1'" + sbt_commands=( "${sbt_commands[@]}" "$1" ) +} +setThisBuild () { + vlog "[addBuild] args = '$@'" + local key="$1" && shift + addSbt "set $key in ThisBuild := $@" +} + +addScalac () { + vlog "[addScalac] arg = '$1'" + scalac_args=( "${scalac_args[@]}" "$1" ) +} +addResidual () { + vlog "[residual] arg = '$1'" + residual_args=( "${residual_args[@]}" "$1" ) +} +addResolver () { + addSbt "set resolvers += $1" +} +addDebugger () { + addJava "-Xdebug" + addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1" +} +setScalaVersion () { + [[ "$1" == *"-SNAPSHOT" ]] && addResolver 'Resolver.sonatypeRepo("snapshots")' + addSbt "++ $1" +} + +process_args () +{ + require_arg () { + local type="$1" + local opt="$2" + local arg="$3" + + if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then + die "$opt requires <$type> argument" + fi + } + while [[ $# -gt 0 ]]; do + case "$1" in + -h|-help) usage; exit 1 ;; + -v) verbose=true && shift ;; + -d) addSbt "--debug" && shift ;; + -w) addSbt "--warn" && shift ;; + -q) addSbt "--error" && shift ;; + -x) debugUs=true && shift ;; + -trace) require_arg integer "$1" "$2" && trace_level="$2" && shift 2 ;; + -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; + -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; + -no-share) noshare=true && shift ;; + -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; + -sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;; + -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; + -offline) addSbt "set offline := true" && shift ;; + -jvm-debug) require_arg port "$1" "$2" && addDebugger "$2" && shift 2 ;; + -batch) batch=true && shift ;; + -prompt) require_arg "expr" "$1" "$2" && setThisBuild shellPrompt "(s => { val e = Project.extract(s) ; $2 })" && shift 2 ;; + + -sbt-create) sbt_create=true && shift ;; + -sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;; + -sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;; + -sbt-force-latest) sbt_explicit_version="$sbt_release_version" && shift ;; + -sbt-dev) sbt_explicit_version="$sbt_unreleased_version" && shift ;; + -sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;; + -sbt-launch-repo) require_arg path "$1" "$2" && sbt_launch_repo="$2" && shift 2 ;; + -scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;; + -binary-version) require_arg version "$1" "$2" && setThisBuild scalaBinaryVersion "\"$2\"" && shift 2 ;; + -scala-home) require_arg path "$1" "$2" && setThisBuild scalaHome "Some(file(\"$2\"))" && shift 2 ;; + -java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;; + -sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;; + -jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;; + + -D*) addJava "$1" && shift ;; + -J*) addJava "${1:2}" && shift ;; + -S*) addScalac "${1:2}" && shift ;; + -28) setScalaVersion "$latest_28" && shift ;; + -29) setScalaVersion "$latest_29" && shift ;; + -210) setScalaVersion "$latest_210" && shift ;; + -211) setScalaVersion "$latest_211" && shift ;; + + *) addResidual "$1" && shift ;; + esac + done +} + +# process the direct command line arguments +process_args "$@" + +# skip #-styled comments and blank lines +readConfigFile() { + while read line; do + [[ $line =~ ^# ]] || [[ -z $line ]] || echo "$line" + done < "$1" +} + +# if there are file/environment sbt_opts, process again so we +# can supply args to this runner +if [[ -r "$sbt_opts_file" ]]; then + vlog "Using sbt options defined in file $sbt_opts_file" + while read opt; do extra_sbt_opts+=("$opt"); done < <(readConfigFile "$sbt_opts_file") +elif [[ -n "$SBT_OPTS" && ! ("$SBT_OPTS" =~ ^@.*) ]]; then + vlog "Using sbt options defined in variable \$SBT_OPTS" + extra_sbt_opts=( $SBT_OPTS ) +else + vlog "No extra sbt options have been defined" +fi + +[[ -n "${extra_sbt_opts[*]}" ]] && process_args "${extra_sbt_opts[@]}" + +# reset "$@" to the residual args +set -- "${residual_args[@]}" +argumentCount=$# + +# set sbt version +set_sbt_version + +# only exists in 0.12+ +setTraceLevel() { + case "$sbt_version" in + "0.7."* | "0.10."* | "0.11."* ) echoerr "Cannot set trace level in sbt version $sbt_version" ;; + *) setThisBuild traceLevel $trace_level ;; + esac +} + +# set scalacOptions if we were given any -S opts +[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\"" + +# Update build.properties on disk to set explicit version - sbt gives us no choice +[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version" +vlog "Detected sbt version $sbt_version" + +[[ -n "$scala_version" ]] && vlog "Overriding scala version to $scala_version" + +# no args - alert them there's stuff in here +(( argumentCount > 0 )) || { + vlog "Starting $script_name: invoke with -help for other options" + residual_args=( shell ) +} + +# verify this is an sbt dir or -create was given +[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || { + cat < e.printStackTrace() } } -} +} \ No newline at end of file diff --git a/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala b/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala new file mode 100644 index 000000000000..90a6a5dc2dc8 --- /dev/null +++ b/samples/server/petstore/scalatra/src/main/scala/ServletApp.scala @@ -0,0 +1,39 @@ +package com.wordnik.swagger.app + +import _root_.akka.actor.ActorSystem + +import org.scalatra.swagger.{ ApiInfo, SwaggerWithAuth, Swagger } +import org.scalatra.swagger.{JacksonSwaggerBase, Swagger} +import org.scalatra.ScalatraServlet +import org.json4s.{DefaultFormats, Formats} + +class ResourcesApp(implicit protected val system: ActorSystem, val swagger: SwaggerApp) + extends ScalatraServlet with JacksonSwaggerBase { + before() { + response.headers += ("Access-Control-Allow-Origin" -> "*") + } + + protected def buildFullUrl(path: String) = if (path.startsWith("http")) path else { + val port = request.getServerPort + val h = request.getServerName + val prot = if (port == 443) "https" else "http" + val (proto, host) = if (port != 80 && port != 443) ("http", h+":"+port.toString) else (prot, h) + "%s://%s%s%s".format( + proto, + host, + request.getContextPath, + path) + } +} + +class SwaggerApp extends Swagger(apiInfo = ApiSwagger.apiInfo, apiVersion = "1.0", swaggerVersion = "1.2") + +object ApiSwagger { + val apiInfo = ApiInfo( + """Swagger Petstore""", + """This is a sample server Petstore server. You can find out more about Swagger at http://swagger.wordnik.com or on irc.freenode.net, #swagger. For this sample, you can use the api key "special-key" to test the authorization filters""", + """""", + """hello@helloreverb.com""", + """Apache 2.0""", + """http://www.apache.org/licenses/LICENSE-2.0.html""") +} \ No newline at end of file diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala new file mode 100644 index 000000000000..b29c49ab238d --- /dev/null +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala @@ -0,0 +1,365 @@ +package com.wordnik.client.api + +import com.wordnik.client.model.Pet + +import java.io.File + +import org.scalatra.{ TypedParamSupport, ScalatraServlet } +import org.scalatra.swagger._ +import org.json4s._ +import org.json4s.JsonDSL._ +import org.scalatra.json.{ JValueResult, JacksonJsonSupport } +import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException} + +import scala.collection.JavaConverters._ + +class PetApi (implicit val swagger: Swagger) extends ScalatraServlet + with FileUploadSupport + with JacksonJsonSupport + with SwaggerSupport { + protected implicit val jsonFormats: Formats = DefaultFormats + + protected val applicationDescription: String = "PetApi" + override protected val applicationName: Option[String] = Some("Pet") + + before() { + contentType = formats("json") + response.headers += ("Access-Control-Allow-Origin" -> "*") + } + + + val updatePetOperation = (apiOperation[Unit]("updatePet") + summary "Update an existing pet" + parameters( + + + + bodyParam[Pet]("body").description("").optional + + + + ) + ) + + put("/pet",operation(updatePetOperation)) { + + + + + + + + + + + + + val body = parsedBody.extract[Pet] + + + println("body: " + body) + + } + + + + val addPetOperation = (apiOperation[Unit]("addPet") + summary "Add a new pet to the store" + parameters( + + + + bodyParam[Pet]("body").description("").optional + + + + ) + ) + + post("/pet",operation(addPetOperation)) { + + + + + + + + + + + + + val body = parsedBody.extract[Pet] + + + println("body: " + body) + + } + + + + val findPetsByStatusOperation = (apiOperation[List[Pet]]("findPetsByStatus") + summary "Finds Pets by status" + parameters( + queryParam[List[String]]("status").description("").optional + + + + + + + ) + ) + + get("/pet/findByStatus",operation(findPetsByStatusOperation)) { + + + + + + + val statusString = params.getAs[String]("status") + val status = if("multi".equals("default")) { + statusString match { + case Some(str) => str.split(",") + case None => List() + } + } + else + List() + + + + + + + + + + + + println("status: " + status) + + } + + + + val findPetsByTagsOperation = (apiOperation[List[Pet]]("findPetsByTags") + summary "Finds Pets by tags" + parameters( + queryParam[List[String]]("tags").description("").optional + + + + + + + ) + ) + + get("/pet/findByTags",operation(findPetsByTagsOperation)) { + + + + + + + val tagsString = params.getAs[String]("tags") + val tags = if("multi".equals("default")) { + tagsString match { + case Some(str) => str.split(",") + case None => List() + } + } + else + List() + + + + + + + + + + + + println("tags: " + tags) + + } + + + + val getPetByIdOperation = (apiOperation[Pet]("getPetById") + summary "Find pet by ID" + parameters( + + pathParam[Long]("petId").description("") + + + + + + ) + ) + + get("/pet/{petId}",operation(getPetByIdOperation)) { + + + + + val petId = params.getOrElse("petId", halt(400)) + + + + + + + + + + + println("petId: " + petId) + + } + + + + val updatePetWithFormOperation = (apiOperation[Unit]("updatePetWithForm") + summary "Updates a pet in the store with form data" + parameters( + + pathParam[String]("petId").description("") + + + + + , + + + + + formParam[String]("name").description("").optional + + , + + + + + formParam[String]("status").description("").optional + + + ) + ) + + post("/pet/{petId}",operation(updatePetWithFormOperation)) { + + + + + val petId = params.getOrElse("petId", halt(400)) + + + + + + + + + + + println("petId: " + petId) + + + + + + + + + + + val name = params.getAs[String]("name") + + + + + println("name: " + name) + + + + + + + + + + + val status = params.getAs[String]("status") + + + + + println("status: " + status) + + } + + + + val deletePetOperation = (apiOperation[Unit]("deletePet") + summary "Deletes a pet" + parameters( + + + headerParam[String]("api_key").description("").optional + + + + , + + pathParam[Long]("petId").description("") + + + + + + ) + ) + + delete("/pet/{petId}",operation(deletePetOperation)) { + + + + + + + + + val api_key = request.getHeader("api_key") + + + + + + + println("api_key: " + api_key) + + + + + val petId = params.getOrElse("petId", halt(400)) + + + + + + + + + + + println("petId: " + petId) + + } + +} \ No newline at end of file diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala new file mode 100644 index 000000000000..4c32e94eeae7 --- /dev/null +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala @@ -0,0 +1,146 @@ +package com.wordnik.client.api + +import com.wordnik.client.model.Order + +import java.io.File + +import org.scalatra.{ TypedParamSupport, ScalatraServlet } +import org.scalatra.swagger._ +import org.json4s._ +import org.json4s.JsonDSL._ +import org.scalatra.json.{ JValueResult, JacksonJsonSupport } +import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException} + +import scala.collection.JavaConverters._ + +class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet + with FileUploadSupport + with JacksonJsonSupport + with SwaggerSupport { + protected implicit val jsonFormats: Formats = DefaultFormats + + protected val applicationDescription: String = "StoreApi" + override protected val applicationName: Option[String] = Some("Store") + + before() { + contentType = formats("json") + response.headers += ("Access-Control-Allow-Origin" -> "*") + } + + + val getInventoryOperation = (apiOperation[Map[String, Int]]("getInventory") + summary "Returns pet inventories by status" + parameters( + ) + ) + + get("/store/inventory",operation(getInventoryOperation)) { + + } + + + + val placeOrderOperation = (apiOperation[Order]("placeOrder") + summary "Place an order for a pet" + parameters( + + + + bodyParam[Order]("body").description("").optional + + + + ) + ) + + post("/store/order",operation(placeOrderOperation)) { + + + + + + + + + + + + + val body = parsedBody.extract[Order] + + + println("body: " + body) + + } + + + + val getOrderByIdOperation = (apiOperation[Order]("getOrderById") + summary "Find purchase order by ID" + parameters( + + pathParam[String]("orderId").description("") + + + + + + ) + ) + + get("/store/order/{orderId}",operation(getOrderByIdOperation)) { + + + + + val orderId = params.getOrElse("orderId", halt(400)) + + + + + + + + + + + println("orderId: " + orderId) + + } + + + + val deleteOrderOperation = (apiOperation[Unit]("deleteOrder") + summary "Delete purchase order by ID" + parameters( + + pathParam[String]("orderId").description("") + + + + + + ) + ) + + delete("/store/order/{orderId}",operation(deleteOrderOperation)) { + + + + + val orderId = params.getOrElse("orderId", halt(400)) + + + + + + + + + + + println("orderId: " + orderId) + + } + +} \ No newline at end of file diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala new file mode 100644 index 000000000000..42cf754cfd7b --- /dev/null +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala @@ -0,0 +1,336 @@ +package com.wordnik.client.api + +import com.wordnik.client.model.User + +import java.io.File + +import org.scalatra.{ TypedParamSupport, ScalatraServlet } +import org.scalatra.swagger._ +import org.json4s._ +import org.json4s.JsonDSL._ +import org.scalatra.json.{ JValueResult, JacksonJsonSupport } +import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException} + +import scala.collection.JavaConverters._ + +class UserApi (implicit val swagger: Swagger) extends ScalatraServlet + with FileUploadSupport + with JacksonJsonSupport + with SwaggerSupport { + protected implicit val jsonFormats: Formats = DefaultFormats + + protected val applicationDescription: String = "UserApi" + override protected val applicationName: Option[String] = Some("User") + + before() { + contentType = formats("json") + response.headers += ("Access-Control-Allow-Origin" -> "*") + } + + + val createUserOperation = (apiOperation[Unit]("createUser") + summary "Create user" + parameters( + + + + bodyParam[User]("body").description("").optional + + + + ) + ) + + post("/user",operation(createUserOperation)) { + + + + + + + + + + + + + val body = parsedBody.extract[User] + + + println("body: " + body) + + } + + + + val createUsersWithArrayInputOperation = (apiOperation[Unit]("createUsersWithArrayInput") + summary "Creates list of users with given input array" + parameters( + + + + bodyParam[List[User]]("body").description("").optional + + + + ) + ) + + post("/user/createWithArray",operation(createUsersWithArrayInputOperation)) { + + + + + + + + + + + + + val body = parsedBody.extract[List[User]] + + + println("body: " + body) + + } + + + + val createUsersWithListInputOperation = (apiOperation[Unit]("createUsersWithListInput") + summary "Creates list of users with given input array" + parameters( + + + + bodyParam[List[User]]("body").description("").optional + + + + ) + ) + + post("/user/createWithList",operation(createUsersWithListInputOperation)) { + + + + + + + + + + + + + val body = parsedBody.extract[List[User]] + + + println("body: " + body) + + } + + + + val loginUserOperation = (apiOperation[String]("loginUser") + summary "Logs user into the system" + parameters( + queryParam[String]("username").description("").optional + + + + + + , + queryParam[String]("password").description("").optional + + + + + + + ) + ) + + get("/user/login",operation(loginUserOperation)) { + + + + + + + + val username = params.getAs[String]("username") + + + + + + + + + + println("username: " + username) + + + + + + + + val password = params.getAs[String]("password") + + + + + + + + + + println("password: " + password) + + } + + + + val logoutUserOperation = (apiOperation[Unit]("logoutUser") + summary "Logs out current logged in user session" + parameters( + ) + ) + + get("/user/logout",operation(logoutUserOperation)) { + + } + + + + val getUserByNameOperation = (apiOperation[User]("getUserByName") + summary "Get user by user name" + parameters( + + pathParam[String]("username").description("") + + + + + + ) + ) + + get("/user/{username}",operation(getUserByNameOperation)) { + + + + + val username = params.getOrElse("username", halt(400)) + + + + + + + + + + + println("username: " + username) + + } + + + + val updateUserOperation = (apiOperation[Unit]("updateUser") + summary "Updated user" + parameters( + + pathParam[String]("username").description("") + + + + + , + + + + bodyParam[User]("body").description("").optional + + + + ) + ) + + put("/user/{username}",operation(updateUserOperation)) { + + + + + val username = params.getOrElse("username", halt(400)) + + + + + + + + + + + println("username: " + username) + + + + + + + + + + + + + val body = parsedBody.extract[User] + + + println("body: " + body) + + } + + + + val deleteUserOperation = (apiOperation[Unit]("deleteUser") + summary "Delete user" + parameters( + + pathParam[String]("username").description("") + + + + + + ) + ) + + delete("/user/{username}",operation(deleteUserOperation)) { + + + + + val username = params.getOrElse("username", halt(400)) + + + + + + + + + + + println("username: " + username) + + } + +} \ No newline at end of file diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala new file mode 100644 index 000000000000..d4ee7a692e66 --- /dev/null +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Category.scala @@ -0,0 +1,8 @@ +package com.wordnik.client.model + + + +case class Category ( + id: Long, + name: String +) diff --git a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/Order.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala similarity index 58% rename from samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/Order.scala rename to samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala index 75f89aacca67..918cf132d2cd 100644 --- a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/model/Order.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Order.scala @@ -1,11 +1,13 @@ -package com.wordnik.petstore.model +package com.wordnik.client.model import java.util.Date + + case class Order ( id: Long, petId: Long, quantity: Int, - /* Order Status */ + shipDate: Date, status: String, - shipDate: Date) - + complete: Boolean +) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala new file mode 100644 index 000000000000..cea17dedae7b --- /dev/null +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Pet.scala @@ -0,0 +1,14 @@ +package com.wordnik.client.model + +import com.wordnik.client.model.Category +import com.wordnik.client.model.Tag + + +case class Pet ( + id: Long, + category: Category, + name: String, + photoUrls: List[String], + tags: List[Tag], + status: String +) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala new file mode 100644 index 000000000000..bd28dd4d44dc --- /dev/null +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/Tag.scala @@ -0,0 +1,8 @@ +package com.wordnik.client.model + + + +case class Tag ( + id: Long, + name: String +) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala new file mode 100644 index 000000000000..acadf78f7a1c --- /dev/null +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/model/User.scala @@ -0,0 +1,14 @@ +package com.wordnik.client.model + + + +case class User ( + id: Long, + username: String, + firstName: String, + lastName: String, + email: String, + password: String, + phone: String, + userStatus: Int +) diff --git a/samples/server-generator/scalatra/templates/web.xml b/samples/server/petstore/scalatra/src/main/webapp/WEB-INF/web.xml similarity index 100% rename from samples/server-generator/scalatra/templates/web.xml rename to samples/server/petstore/scalatra/src/main/webapp/WEB-INF/web.xml diff --git a/samples/swagger-static-docs/docs/models/Category.html b/samples/swagger-static-docs/docs/models/Category.html deleted file mode 100644 index 7917b84c824c..000000000000 --- a/samples/swagger-static-docs/docs/models/Category.html +++ /dev/null @@ -1,12 +0,0 @@ -

    Category

    -
      -
    • id : long -
      {description}} -
    • -
    -
      -
    • name : string -
      {description}} -
    • -
    - diff --git a/samples/swagger-static-docs/docs/models/Order.html b/samples/swagger-static-docs/docs/models/Order.html deleted file mode 100644 index c5c129ae6dbe..000000000000 --- a/samples/swagger-static-docs/docs/models/Order.html +++ /dev/null @@ -1,27 +0,0 @@ -

    Order

    -
      -
    • id : long -
      {description}} -
    • -
    -
      -
    • petId : long -
      {description}} -
    • -
    -
      -
    • quantity : int -
      {description}} -
    • -
    -
      -
    • status : string -
      {description}} -
    • -
    -
      -
    • shipDate : Date -
      {description}} -
    • -
    - diff --git a/samples/swagger-static-docs/docs/models/Pet.html b/samples/swagger-static-docs/docs/models/Pet.html deleted file mode 100644 index 4409c2ddddeb..000000000000 --- a/samples/swagger-static-docs/docs/models/Pet.html +++ /dev/null @@ -1,32 +0,0 @@ -

    Pet

    -
      -
    • id : long -
      {description}} -
    • -
    -
      -
    • category : Category -
      {description}} -
    • -
    -
      -
    • name : string -
      {description}} -
    • -
    -
      -
    • photoUrls : List[string] -
      {description}} -
    • -
    -
      -
    • tags : List[Tag] -
      {description}} -
    • -
    -
      -
    • status : string -
      {description}} -
    • -
    - diff --git a/samples/swagger-static-docs/docs/models/Tag.html b/samples/swagger-static-docs/docs/models/Tag.html deleted file mode 100644 index aa0705acd830..000000000000 --- a/samples/swagger-static-docs/docs/models/Tag.html +++ /dev/null @@ -1,12 +0,0 @@ -

    Tag

    -
      -
    • id : long -
      {description}} -
    • -
    -
      -
    • name : string -
      {description}} -
    • -
    - diff --git a/samples/swagger-static-docs/docs/models/User.html b/samples/swagger-static-docs/docs/models/User.html deleted file mode 100644 index bf89f5a46bff..000000000000 --- a/samples/swagger-static-docs/docs/models/User.html +++ /dev/null @@ -1,42 +0,0 @@ -

    User

    -
      -
    • id : long -
      {description}} -
    • -
    -
      -
    • firstName : string -
      {description}} -
    • -
    -
      -
    • username : string -
      {description}} -
    • -
    -
      -
    • lastName : string -
      {description}} -
    • -
    -
      -
    • email : string -
      {description}} -
    • -
    -
      -
    • password : string -
      {description}} -
    • -
    -
      -
    • phone : string -
      {description}} -
    • -
    -
      -
    • userStatus : int -
      {description}} -
    • -
    - diff --git a/samples/swagger-static-docs/docs/operations/PetApi.html b/samples/swagger-static-docs/docs/operations/PetApi.html deleted file mode 100644 index c90614ad3e17..000000000000 --- a/samples/swagger-static-docs/docs/operations/PetApi.html +++ /dev/null @@ -1,191 +0,0 @@ -
    -

    PetApi

    -

    This is the PetApi API

    - -

    getPetById

    -
    -

    -

    Returns a pet based on ID

    URL

    - http://petstore.swagger.wordnik.com/api/pet/{petId} -

    HTTP Method

    - GET -

    Response Type

    - -

    Parameters

    -
      -
      -
      petId : long (path)
      - -
      -

      ID of pet that needs to be fetched

      -
    - -

    deletePet

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/pet/{petId} -

    HTTP Method

    - DELETE -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      petId : string (path)
      - -
      -

      Pet id to delete

      - -
    -

    partialUpdate

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/pet/{petId} -

    HTTP Method

    - PATCH -

    Response Type

    - -

    Parameters

    -
      -
      -
      petId : string (path)
      - -
      -

      ID of pet that needs to be fetched

      - -
      -
      body :  
      Pet (body)
      - -
      -

      Pet object that needs to be added to the store

      -
      -
    -

    updatePetWithForm

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/pet/{petId} -

    HTTP Method

    - POST -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      petId : string (path)
      - -
      -

      ID of pet that needs to be updated

      - -
      -
      name : string (form)
      - optional -
      -

      Updated name of the pet

      - -
      -
      status : string (form)
      - optional -
      -

      Updated status of the pet

      - -
    -

    uploadFile

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/pet/uploadImage -

    HTTP Method

    - POST -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      additionalMetadata : string (form)
      - optional -
      -

      Additional data to pass to server

      - -
      -
      body :  
      File (body)
      - optional -
      -

      file to upload

      -
      -
    -

    addPet

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/pet -

    HTTP Method

    - POST -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      body :  
      Pet (body)
      - -
      -

      Pet object that needs to be added to the store

      -
      -
    -

    updatePet

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/pet -

    HTTP Method

    - PUT -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      body :  
      Pet (body)
      - -
      -

      Pet object that needs to be updated in the store

      -
      -
    -

    findPetsByStatus

    -
    -

    -

    Multiple status values can be provided with comma seperated strings

    URL

    - http://petstore.swagger.wordnik.com/api/pet/findByStatus -

    HTTP Method

    - GET -

    Response Type

    - -

    Parameters

    -
      -
      -
      status : string (query)
      - -
      -

      Status values that need to be considered for filter

      - -
    -

    findPetsByTags

    -
    -

    -

    Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.

    URL

    - http://petstore.swagger.wordnik.com/api/pet/findByTags -

    HTTP Method

    - GET -

    Response Type

    - -

    Parameters

    -
      -
      -
      tags : string (query)
      - -
      -

      Tags to filter by

      - -
    - diff --git a/samples/swagger-static-docs/docs/operations/StoreApi.html b/samples/swagger-static-docs/docs/operations/StoreApi.html deleted file mode 100644 index fdca080c5640..000000000000 --- a/samples/swagger-static-docs/docs/operations/StoreApi.html +++ /dev/null @@ -1,59 +0,0 @@ -
    -

    StoreApi

    -

    This is the StoreApi API

    - -

    getOrderById

    -
    -

    -

    For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors

    URL

    - http://petstore.swagger.wordnik.com/api/store/order/{orderId} -

    HTTP Method

    - GET -

    Response Type

    - -

    Parameters

    -
      -
      -
      orderId : string (path)
      - -
      -

      ID of pet that needs to be fetched

      -
    - -

    deleteOrder

    -
    -

    -

    For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors

    URL

    - http://petstore.swagger.wordnik.com/api/store/order/{orderId} -

    HTTP Method

    - DELETE -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      orderId : string (path)
      - -
      -

      ID of the order that needs to be deleted

      - -
    -

    placeOrder

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/store/order -

    HTTP Method

    - POST -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      body :  
      Order (body)
      - -
      -

      order placed for purchasing the pet

      -
      -
    - diff --git a/samples/swagger-static-docs/docs/operations/UserApi.html b/samples/swagger-static-docs/docs/operations/UserApi.html deleted file mode 100644 index addb63e48942..000000000000 --- a/samples/swagger-static-docs/docs/operations/UserApi.html +++ /dev/null @@ -1,155 +0,0 @@ -
    -

    UserApi

    -

    This is the UserApi API

    - -

    updateUser

    -
    -

    -

    This can only be done by the logged in user.

    URL

    - http://petstore.swagger.wordnik.com/api/user/{username} -

    HTTP Method

    - PUT -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      username : string (path)
      - -
      -

      name that need to be deleted

      -
    -
    -
    body :  
    User (body)
    - -
    -

    Updated user object

    -
    - -

    deleteUser

    -
    -

    -

    This can only be done by the logged in user.

    URL

    - http://petstore.swagger.wordnik.com/api/user/{username} -

    HTTP Method

    - DELETE -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      username : string (path)
      - -
      -

      The name that needs to be deleted

      - -
    -

    getUserByName

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/user/{username} -

    HTTP Method

    - GET -

    Response Type

    - -

    Parameters

    -
      -
      -
      username : string (path)
      - -
      -

      The name that needs to be fetched. Use user1 for testing.

      - -
    -

    loginUser

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/user/login -

    HTTP Method

    - GET -

    Response Type

    - -

    Parameters

    -
      -
      -
      username : string (query)
      - -
      -

      The user name for login

      - -
      -
      password : string (query)
      - -
      -

      The password for login in clear text

      - -
    -

    logoutUser

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/user/logout -

    HTTP Method

    - GET -

    Response Type

    -
    -

    Parameters

    -
      -
    -

    createUser

    -
    -

    -

    This can only be done by the logged in user.

    URL

    - http://petstore.swagger.wordnik.com/api/user -

    HTTP Method

    - POST -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      body :  
      User (body)
      - -
      -

      Created user object

      -
      -
    -

    createUsersWithArrayInput

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/user/createWithArray -

    HTTP Method

    - POST -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      body :  
      Array[User] (body)
      - -
      -

      List of user object

      -
      -
    -

    createUsersWithListInput

    -
    -

    -

    URL

    - http://petstore.swagger.wordnik.com/api/user/createWithList -

    HTTP Method

    - POST -

    Response Type

    -
    -

    Parameters

    -
      -
      -
      body :  
      Array[User] (body)
      - -
      -

      List of user object

      -
      -
    - diff --git a/samples/yaml/echo.yaml b/samples/yaml/echo.yaml new file mode 100644 index 000000000000..ce60293f6eea --- /dev/null +++ b/samples/yaml/echo.yaml @@ -0,0 +1,51 @@ +swagger: 2 +info: + title: Echo API + description: Simple Rest Echo + version: "1.0.0" +host: "localhost:8002" +schemes: + - http +basePath: /v1 +produces: + - application/json +paths: + /echo: + get: + description: "Returns the 'message' to the caller" + operationId: "echo" + parameters: + #- name: X-header-param + - name: headerParam + in: header + type: string + required: false + - name: message + in: query + type: string + required: true + responses: + 200: + description: "Success" + schema: + $ref: EchoResponse + default: + description: "Error" + schema: + $ref: Error +definitions: + EchoResponse: + required: + - message + properties: + message: + type: string + Error: + properties: + code: + type: integer + format: int32 + message: + type: string + fields: + type: string diff --git a/sbt b/sbt deleted file mode 100755 index 491debf4fb3f..000000000000 --- a/sbt +++ /dev/null @@ -1,518 +0,0 @@ -#!/usr/bin/env bash -# -# A more capable sbt runner, coincidentally also called sbt. -# Author: Paul Phillips - -# todo - make this dynamic -declare -r sbt_release_version=0.12.4 -declare -r sbt_beta_version=0.13.0-RC4 -declare -r sbt_snapshot_version=0.13.0-SNAPSHOT - -declare sbt_jar sbt_dir sbt_create sbt_snapshot sbt_launch_dir -declare scala_version java_home sbt_explicit_version -declare verbose debug quiet noshare batch trace_level log_level -declare sbt_saved_stty - -echoerr () { [[ -z $quiet ]] && echo "$@" >&2; } -vlog () { [[ -n "$verbose$debug" ]] && echoerr "$@"; } -dlog () { [[ -n $debug ]] && echoerr "$@"; } - -# we'd like these set before we get around to properly processing arguments -for arg in "$@"; do - case $arg in - -q|-quiet) quiet=true ;; - -d|-debug) debug=true ;; - -v|-verbose) verbose=true ;; - *) ;; - esac -done - -build_props_sbt () { - if [[ -r project/build.properties ]]; then - versionLine=$(grep ^sbt.version project/build.properties | tr -d '\r') - versionString=${versionLine##sbt.version=} - echo "$versionString" - fi -} - -update_build_props_sbt () { - local ver="$1" - local old=$(build_props_sbt) - - if [[ $ver == $old ]]; then - return - elif [[ -r project/build.properties ]]; then - perl -pi -e "s/^sbt\.version=.*\$/sbt.version=${ver}/" project/build.properties - grep -q '^sbt.version=' project/build.properties || echo "sbt.version=${ver}" >> project/build.properties - - echoerr !!! - echoerr !!! Updated file project/build.properties setting sbt.version to: $ver - echoerr !!! Previous value was: $old - echoerr !!! - fi -} - -sbt_version () { - if [[ -n $sbt_explicit_version ]]; then - echo $sbt_explicit_version - else - local v=$(build_props_sbt) - if [[ -n $v ]]; then - echo $v - else - echo $sbt_release_version - fi - fi -} - -# restore stty settings (echo in particular) -onSbtRunnerExit() { - [[ -n $sbt_saved_stty ]] || return - dlog "" - dlog "restoring stty: $sbt_saved_stty" - stty $sbt_saved_stty - unset sbt_saved_stty -} - -# save stty and trap exit, to ensure echo is reenabled if we are interrupted. -trap onSbtRunnerExit EXIT -sbt_saved_stty=$(stty -g 2>/dev/null) -dlog "Saved stty: $sbt_saved_stty" - -# this seems to cover the bases on OSX, and someone will -# have to tell me about the others. -get_script_path () { - local path="$1" - [[ -L "$path" ]] || { echo "$path" ; return; } - - local target=$(readlink "$path") - if [[ "${target:0:1}" == "/" ]]; then - echo "$target" - else - echo "$(dirname $path)/$target" - fi -} - -die() { - echo "Aborting: $@" - exit 1 -} - -make_url () { - groupid="$1" - category="$2" - version="$3" - - echo "http://typesafe.artifactoryonline.com/typesafe/ivy-$category/$groupid/sbt-launch/$version/sbt-launch.jar" -} - -readarr () { - while read ; do - eval "$1+=(\"$REPLY\")" - done -} - -init_default_option_file () { - local overriding_var=${!1} - local default_file=$2 - if [[ ! -r "$default_file" && $overriding_var =~ ^@(.*)$ ]]; then - local envvar_file=${BASH_REMATCH[1]} - if [[ -r $envvar_file ]]; then - default_file=$envvar_file - fi - fi - echo $default_file -} - -declare -r default_jvm_opts="-Dfile.encoding=UTF8 -XX:MaxPermSize=256m -Xms512m -Xmx1g -XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC" -declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" -declare -r latest_28="2.8.2" -declare -r latest_29="2.9.3" -declare -r latest_210="2.10.0" - -declare -r script_path=$(get_script_path "$BASH_SOURCE") -declare -r script_dir="$(dirname $script_path)" -declare -r script_name="$(basename $script_path)" - -# some non-read-onlies set with defaults -declare java_cmd=java -declare sbt_opts_file=$(init_default_option_file SBT_OPTS .sbtopts) -declare jvm_opts_file=$(init_default_option_file JVM_OPTS .jvmopts) - -# pull -J and -D options to give to java. -declare -a residual_args -declare -a java_args -declare -a scalac_args -declare -a sbt_commands - -# args to jvm/sbt via files or environment variables -declare -a extra_jvm_opts extra_sbt_opts - -# if set, use JAVA_HOME over java found in path -[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java" - -# directory to store sbt launchers -declare sbt_launch_dir="$HOME/.sbt/launchers" -[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir" -[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers)" - -build_props_scala () { - if [[ -r project/build.properties ]]; then - versionLine=$(grep ^build.scala.versions project/build.properties) - versionString=${versionLine##build.scala.versions=} - echo ${versionString%% .*} - fi -} - -execRunner () { - # print the arguments one to a line, quoting any containing spaces - [[ $verbose || $debug ]] && echo "# Executing command line:" && { - for arg; do - if [[ -n "$arg" ]]; then - if printf "%s\n" "$arg" | grep -q ' '; then - printf "\"%s\"\n" "$arg" - else - printf "%s\n" "$arg" - fi - fi - done - echo "" - } - - if [[ -n $batch ]]; then - # the only effective way I've found to avoid sbt hanging when backgrounded. - exec 0<&- - ( "$@" & ) - # I'm sure there's some way to get our hands on the pid and wait for it - # but it exceeds my present level of ambition. - else - { "$@"; } - fi -} - -sbt_groupid () { - case $(sbt_version) in - 0.7.*) echo org.scala-tools.sbt ;; - 0.10.*) echo org.scala-tools.sbt ;; - 0.11.[12]) echo org.scala-tools.sbt ;; - *) echo org.scala-sbt ;; - esac -} - -sbt_artifactory_list () { - local version0=$(sbt_version) - local version=${version0%-SNAPSHOT} - local url="http://typesafe.artifactoryonline.com/typesafe/ivy-snapshots/$(sbt_groupid)/sbt-launch/" - dlog "Looking for snapshot list at: $url " - - curl -s --list-only "$url" | \ - grep -F $version | \ - perl -e 'print reverse <>' | \ - perl -pe 's#^/dev/null - dlog "curl returned: $?" - echo "$url" - return - done -} - -jar_url () { - case $(sbt_version) in - 0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;; - *-SNAPSHOT) make_snapshot_url ;; - *) make_release_url ;; - esac -} - -jar_file () { - case $1 in - 0.13.*) echo "$sbt_launch_dir/$1/sbt-launch.jar" ;; - *) echo "$sbt_launch_dir/$sbt_release_version/sbt-launch.jar" ;; - esac -} - -download_url () { - local url="$1" - local jar="$2" - - echo "Downloading sbt launcher $(sbt_version):" - echo " From $url" - echo " To $jar" - - mkdir -p $(dirname "$jar") && { - if which curl >/dev/null; then - curl --fail --silent "$url" --output "$jar" - elif which wget >/dev/null; then - wget --quiet -O "$jar" "$url" - fi - } && [[ -r "$jar" ]] -} - -acquire_sbt_jar () { - sbt_url="$(jar_url)" - sbt_jar="$(jar_file $(sbt_version))" - - [[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar" -} - -usage () { - cat < display stack traces with a max of frames (default: -1, traces suppressed) - -no-colors disable ANSI color codes - -sbt-create start sbt even if current directory contains no sbt project - -sbt-dir path to global settings/plugins directory (default: ~/.sbt/) - -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11+) - -ivy path to local Ivy repository (default: ~/.ivy2) - -no-share use all local caches; no sharing - -offline put sbt in offline mode - -jvm-debug Turn on JVM debugging, open at the given port. - -batch Disable interactive mode - -prompt Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted - - # sbt version (default: from project/build.properties if present, else latest release) - !!! The only way to accomplish this pre-0.12.0 if there is a build.properties file which - !!! contains an sbt.version property is to update the file on disk. That's what this does. - -sbt-version use the specified version of sbt (default: $sbt_release_version) - -sbt-jar use the specified jar as the sbt launcher - -sbt-beta use a beta version of sbt (currently: $sbt_beta_version) - -sbt-snapshot use a snapshot version of sbt (currently: $sbt_snapshot_version) - -sbt-launch-dir directory to hold sbt launchers (default: $sbt_launch_dir) - - # scala version (default: as chosen by sbt) - -28 use $latest_28 - -29 use $latest_29 - -210 use $latest_210 - -scala-home use the scala build at the specified directory - -scala-version use the specified version of scala - -binary-version use the specified scala version when searching for dependencies - - # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) - -java-home alternate JAVA_HOME - - # passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution - # The default set is used if JVM_OPTS is unset and no -jvm-opts file is found - $default_jvm_opts - JVM_OPTS environment variable holding either the jvm args directly, or - the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts') - Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument. - -jvm-opts file containing jvm args (if not given, .jvmopts in project root is used if present) - -Dkey=val pass -Dkey=val directly to the jvm - -J-X pass option -X directly to the jvm (-J is stripped) - - # passing options to sbt, OR to this runner - SBT_OPTS environment variable holding either the sbt args directly, or - the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts') - Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument. - -sbt-opts file containing sbt args (if not given, .sbtopts in project root is used if present) - -S-X add -X to sbt's scalacOptions (-S is stripped) -EOM -} - -addJava () { - dlog "[addJava] arg = '$1'" - java_args=( "${java_args[@]}" "$1" ) -} -addSbt () { - dlog "[addSbt] arg = '$1'" - sbt_commands=( "${sbt_commands[@]}" "$1" ) -} -addScalac () { - dlog "[addScalac] arg = '$1'" - scalac_args=( "${scalac_args[@]}" "$1" ) -} -addResidual () { - dlog "[residual] arg = '$1'" - residual_args=( "${residual_args[@]}" "$1" ) -} -addResolver () { - addSbt "set resolvers in ThisBuild += $1" -} -addDebugger () { - addJava "-Xdebug" - addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1" -} -setScalaVersion () { - addSbt "set scalaVersion in ThisBuild := \"$1\"" - if [[ "$1" == *SNAPSHOT* ]]; then - addResolver Opts.resolver.sonatypeSnapshots - fi -} - -process_args () -{ - require_arg () { - local type="$1" - local opt="$2" - local arg="$3" - - if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then - die "$opt requires <$type> argument" - fi - } - while [[ $# -gt 0 ]]; do - case "$1" in - -h|-help) usage; exit 1 ;; - -v|-verbose) verbose=true && log_level=Info && shift ;; - -d|-debug) debug=true && log_level=Debug && shift ;; - -q|-quiet) quiet=true && log_level=Error && shift ;; - - -trace) require_arg integer "$1" "$2" && trace_level=$2 && shift 2 ;; - -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; - -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; - -no-share) noshare=true && shift ;; - -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; - -sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;; - -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; - -offline) addSbt "set offline := true" && shift ;; - -jvm-debug) require_arg port "$1" "$2" && addDebugger $2 && shift 2 ;; - -batch) batch=true && shift ;; - -prompt) require_arg "expr" "$1" "$2" && addSbt "set shellPrompt in ThisBuild := (s => { val e = Project.extract(s) ; $2 })" && shift 2 ;; - - -sbt-create) sbt_create=true && shift ;; - -sbt-snapshot) sbt_explicit_version=$sbt_snapshot_version && shift ;; - -sbt-beta) sbt_explicit_version=$sbt_beta_version && shift ;; - -sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;; - -sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;; --sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;; - -scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;; --binary-version) require_arg version "$1" "$2" && addSbt "set scalaBinaryVersion in ThisBuild := \"$2\"" && shift 2 ;; - -scala-home) require_arg path "$1" "$2" && addSbt "set every scalaHome := Some(file(\"$2\"))" && shift 2 ;; - -java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;; - -sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;; - -jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;; - - -D*) addJava "$1" && shift ;; - -J*) addJava "${1:2}" && shift ;; - -S*) addScalac "${1:2}" && shift ;; - -28) addSbt "++ $latest_28" && shift ;; - -29) addSbt "++ $latest_29" && shift ;; - -210) addSbt "++ $latest_210" && shift ;; - - *) addResidual "$1" && shift ;; - esac - done -} - - -# process the direct command line arguments -process_args "$@" - -# skip #-styled comments -readConfigFile() { - while read line; do echo ${line/\#*/} | grep -vE '^\s*$'; done < $1 -} - -# if there are file/environment sbt_opts, process again so we -# can supply args to this runner -if [[ -r "$sbt_opts_file" ]]; then - vlog "Using sbt options defined in file $sbt_opts_file" - readarr extra_sbt_opts < <(readConfigFile "$sbt_opts_file") -elif [[ -n "$SBT_OPTS" && !($SBT_OPTS =~ ^@.*) ]]; then - vlog "Using sbt options defined in variable \$SBT_OPTS" - extra_sbt_opts=( $SBT_OPTS ) -else - vlog "No extra sbt options have been defined" -fi - -[[ -n $extra_sbt_opts ]] && process_args "${extra_sbt_opts[@]}" - -# reset "$@" to the residual args -set -- "${residual_args[@]}" -argumentCount=$# - -# only exists in 0.12+ -setTraceLevel() { - case $(sbt_version) in - 0.{7,10,11}.*) echoerr "Cannot set trace level in sbt version $(sbt_version)" ;; - *) addSbt "set every traceLevel := $trace_level" ;; - esac -} - -# set scalacOptions if we were given any -S opts -[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\"" - -# Update build.properties no disk to set explicit version - sbt gives us no choice -[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version" -vlog "Detected sbt version $(sbt_version)" - -[[ -n "$scala_version" ]] && echoerr "Overriding scala version to $scala_version" - -# no args - alert them there's stuff in here -(( $argumentCount > 0 )) || vlog "Starting $script_name: invoke with -help for other options" - -# verify this is an sbt dir or -create was given -[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || { - cat < - val artifactory = "https://ci.aws.wordnik.com/artifactory/m2-" - if (version.trim.endsWith("SNAPSHOT")) - Some("snapshots" at artifactory + "snapshots") - else - Some("releases" at artifactory + "releases") -} - -publishMavenStyle := true - -publishArtifact in Test := false - -pomIncludeRepository := { x => false } - -credentials += Credentials("Artifactory Realm", "ci.aws.wordnik.com", "mavenuser", "DEEaffe987a") - -resolvers ++= Seq(wordnikSnapshots, wordnikReleases, wordnikRemoteRepos) \ No newline at end of file diff --git a/specs/resources.json b/specs/resources.json deleted file mode 100755 index 9258a3f9f5fb..000000000000 --- a/specs/resources.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "apiVersion": "0.5", - "swaggerVersion": "1.1", - "basePath": "http://localhost:8000", - "apis": [ - { - "path": "/admin.{format}", - "description": "Administrative operations" - }, - { - "path": "/discovery.{format}", - "description": "Discovery Service's Core Operations" - } - ] -} \ No newline at end of file diff --git a/src/main/resources/Java/model.mustache b/src/main/resources/Java/model.mustache deleted file mode 100644 index d3b7b4b5247d..000000000000 --- a/src/main/resources/Java/model.mustache +++ /dev/null @@ -1,44 +0,0 @@ -package {{package}}; - -{{#imports}}import {{import}}; -{{/imports}} -{{#models}} -{{#model}} -public class {{classname}} { - {{#vars}} - - {{#description}}/* {{{description}}} */ - {{/description}} - private {{{datatype}}} {{name}} = {{{defaultValue}}}; - {{#allowableValues}}{{#min}} // range from {{min}} to {{max}} - {{/min}} - //{{^min}}public enum {{name}}Enum { {{#values}} {{.}}, {{/values}} }; - {{/min}} - {{/allowableValues}} - - {{/vars}} - - {{#vars}} - - public {{{datatype}}} {{getter}}() { - return {{name}}; - } - public void {{setter}}({{{datatype}}} {{name}}) { - this.{{name}} = {{name}}; - } - - {{/vars}} - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class {{classname}} {\n"); - {{#vars}} - sb.append(" {{name}}: ").append({{name}}).append("\n"); - {{/vars}} - sb.append("}\n"); - return sb.toString(); - } -} -{{/model}} -{{/models}} \ No newline at end of file diff --git a/src/main/resources/android-java/model.mustache b/src/main/resources/android-java/model.mustache deleted file mode 100644 index afa4a4957556..000000000000 --- a/src/main/resources/android-java/model.mustache +++ /dev/null @@ -1,40 +0,0 @@ -package {{package}}; - -import com.fasterxml.jackson.annotation.JsonProperty; - -{{#imports}}import {{import}}; -{{/imports}} -{{#models}} -{{#model}} -public class {{classname}} { - {{#vars}} - - {{#description}}/* {{{description}}} */ - {{/description}} - @JsonProperty("{{name}}") - private {{{datatype}}} {{name}} = {{{defaultValue}}}; - {{/vars}} - - {{#vars}} - public {{{datatype}}} {{getter}}() { - return {{name}}; - } - public void {{setter}}({{{datatype}}} {{name}}) { - this.{{name}} = {{name}}; - } - - {{/vars}} - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class {{classname}} {\n"); - {{#vars}} - sb.append(" {{name}}: ").append({{name}}).append("\n"); - {{/vars}} - sb.append("}\n"); - return sb.toString(); - } -} -{{/model}} -{{/models}} \ No newline at end of file diff --git a/src/main/resources/asyncscala/api.mustache b/src/main/resources/asyncscala/api.mustache deleted file mode 100644 index 2a8664450d53..000000000000 --- a/src/main/resources/asyncscala/api.mustache +++ /dev/null @@ -1,59 +0,0 @@ -package {{package}} - -{{#imports}}import {{import}} -{{/imports}} -import com.wordnik.swagger.client._ -import scala.concurrent.{ Future, Await } -import scala.concurrent.duration._ -import collection.mutable - -{{#operations}} -class {{className}}(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { - - {{#operation}} - - def {{nickname}}({{#allParams}} - {{#optional}} - {{paramName}}: Option[{{dataType}}] = {{#defaultValue}}Some({{defaultValue}}){{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{#hasMore}}, {{/hasMore}} - {{/optional}} - {{^optional}} - {{paramName}}: {{dataType}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}} - {{/optional}}{{/allParams}})(implicit reader: ClientResponseReader[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]{{#bodyParams}}, writer: RequestWriter[{{dataType}}]{{/bodyParams}}){{#returnType}}: Future[{{returnType}}]{{/returnType}}{{^returnType}}: Future[Unit]{{/returnType}} = { - // create path and map variables - val path = - (addFmt("{{path}}"){{#pathParams}} - replaceAll ("\\{" + "{{baseName}}" + "\\}",{{paramName}}.toString) - {{/pathParams}}) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - {{#requiredParamCount}} - // verify required params are set - val paramCount = (Set[Any]({{/requiredParamCount}}{{#requiredParams}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) - null).size - if (paramCount != {{requiredParamCount}}) sys.error("missing required params") - {{/requiredParamCount}} - - {{#queryParams}} - {{#optional}} - if({{paramName}} != null) {{paramName}}.foreach { v => queryParams += "{{baseName}}" -> v.toString } - {{/optional}} - {{^optional}} - if({{paramName}} != null) queryParams += "{{baseName}}" -> {{paramName}}.toString - {{/optional}} - {{/queryParams}} - - {{#headerParams}}headerParams += "{{baseName}}" -> {{paramName}}.toString - {{/headerParams}} - - val resFuture = client.submit("{{httpMethod}}", path, queryParams.toMap, headerParams.toMap, {{#bodyParam}}writer.write({{bodyParam}}){{/bodyParam}}{{^bodyParam}}"{{emptyBodyParam}}"{{/bodyParam}}) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - {{/operation}} - -} -{{/operations}} diff --git a/src/main/resources/asyncscala/model.mustache b/src/main/resources/asyncscala/model.mustache deleted file mode 100644 index 3892f28302ec..000000000000 --- a/src/main/resources/asyncscala/model.mustache +++ /dev/null @@ -1,15 +0,0 @@ -package {{package}} - -import org.joda.time.DateTime - -{{#models}} - -{{#model}} -case class {{classname}} ( - {{#vars}} - - {{name}}: {{#isNotRequired}}Option[{{/isNotRequired}}{{datatype}}{{#isNotRequired}}]{{/isNotRequired}} {{#hasMore}},{{/hasMore}}{{#description}} // {{description}}{{/description}}{{newline}} - {{/vars}} -) -{{/model}} -{{/models}} \ No newline at end of file diff --git a/src/main/resources/objc/api-body.mustache b/src/main/resources/objc/api-body.mustache deleted file mode 100644 index 1ec88547b60b..000000000000 --- a/src/main/resources/objc/api-body.mustache +++ /dev/null @@ -1,239 +0,0 @@ -{{#operations}} -#import "{{classname}}.h" -#import "SWGFile.h" -#import "SWGApiClient.h" -{{#imports}}#import "{{import}}.h" -{{/imports}} -{{newline}} - - -@implementation {{classname}} -static NSString * basePath = @"{{basePath}}"; - -+({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - static {{classname}}* singletonAPI = nil; - - if (singletonAPI == nil) { - singletonAPI = [[{{classname}} alloc] init]; - [singletonAPI addHeader:headerValue forKey:key]; - } - return singletonAPI; -} - -+(void) setBasePath:(NSString*)path { - basePath = path; -} - -+(NSString*) getBasePath { - return basePath; -} - --(SWGApiClient*) apiClient { - return [SWGApiClient sharedClientFromPool:basePath]; -} - --(void) addHeader:(NSString*)value forKey:(NSString*)key { - [[self apiClient] setHeaderValue:value forKey:key]; -} - --(id) init { - self = [super init]; - [self apiClient]; - return self; -} - --(void) setHeaderValue:(NSString*) value - forKey:(NSString*)key { - [[self apiClient] setHeaderValue:value forKey:key]; -} - --(unsigned long) requestQueueSize { - return [SWGApiClient requestQueueSize]; -} - - -{{#operation}} --(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}}{{newline}} {{/allParams}} - {{#returnBaseType}}{{#hasParams}}completionHandler : {{/hasParams}}(void (^)({{returnType}} output, NSError* error))completionBlock{{/returnBaseType}} - {{^returnBaseType}}{{#hasParams}}completionHandler : {{/hasParams}}(void (^)(NSError* error))completionBlock{{/returnBaseType}} { - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@{{path}}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - {{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [SWGApiClient escape:{{paramName}}]]; - {{/pathParams}} - - NSString* requestContentType = @"application/json"; - NSString* responseContentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - {{#queryParams}}if({{paramName}} != nil) - queryParams[@"{{baseName}}"] = {{paramName}}; - {{/queryParams}} - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - {{#headerParams}}if({{paramName}} != nil) - headerParams[@"{{baseName}}"] = {{paramName}}; - {{/headerParams}} - - id bodyDictionary = nil; - {{#bodyParam}} - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(SWGObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(SWGObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - // convert it to a dictionary - NSError * error; - NSString * str = (NSString*)body; - NSDictionary *JSON = - [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] - options:NSJSONReadingMutableContainers - error:&error]; - bodyDictionary = JSON; - } - else if([body isKindOfClass: [SWGFile class]]) { - requestContentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - {{/bodyParam}} - - {{#requiredParamCount}} - {{#requiredParams}} - if({{paramName}} == nil) { - // error - } - {{/requiredParams}} - {{/requiredParamCount}} - - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - - {{#returnContainer}} - return [client dictionary: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}} - {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} - return; - } - - {{#returnBaseType}} - if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - {{#returnTypeIsPrimitive}} - // {{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}"){{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}}{{/instantiationType}}{{newline}} - {{returnBaseType}}* d = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data]; - {{/returnTypeIsPrimitive}} - {{^returnTypeIsPrimitive}} - {{{returnBaseType}}}* d = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithValues: dict]; - {{/returnTypeIsPrimitive}} - [objs addObject:d]; - } - completionBlock(objs, nil); - } - {{#returnSimpleType}} - {{#returnTypeIsPrimitive}}{{#returnBaseType}}completionBlock( [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data], nil;{{/returnBaseType}} - {{/returnTypeIsPrimitive}} - {{^returnTypeIsPrimitive}} - {{#returnBaseType}}completionBlock( [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithValues: data], nil);{{/returnBaseType}} - {{/returnTypeIsPrimitive}} - {{/returnSimpleType}} - - {{/returnBaseType}} - }]; - {{/returnContainer}} - - {{#returnSimpleType}} - {{#returnTypeIsPrimitive}} - {{#returnBaseType}} - return [client stringWithCompletionBlock:requestUrl - method:@"{{httpMethod}}" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(nil, error); - return; - } - {{returnBaseType}} *result = data ? [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data] : nil; - completionBlock(result, nil); - }]; - {{/returnBaseType}} - {{^returnBaseType}} - return [client stringWithCompletionBlock:requestUrl - method:@"{{httpMethod}}" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - {{/returnBaseType}} - {{/returnTypeIsPrimitive}} - {{#returnBaseType}} - {{^returnTypeIsPrimitive}} - return [client dictionary:requestUrl - method:@"{{httpMethod}}" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - requestContentType:requestContentType - responseContentType:responseContentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}} - {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} - return; - } - {{#returnBaseType}} - {{returnBaseType}} *result = nil; - if (data) { - result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithValues: data]; - } - {{#returnBaseType}}completionBlock(result , nil);{{/returnBaseType}} - {{/returnBaseType}} - }]; - {{/returnTypeIsPrimitive}} - {{/returnBaseType}} - {{/returnSimpleType}} -{{newline}} -} - -{{/operation}} - -{{newline}} -{{/operations}} -@end \ No newline at end of file diff --git a/src/main/resources/php/Swagger.mustache b/src/main/resources/php/Swagger.mustache deleted file mode 100644 index c1d85c05e75b..000000000000 --- a/src/main/resources/php/Swagger.mustache +++ /dev/null @@ -1,223 +0,0 @@ -apiKey = $apiKey; - $this->apiServer = $apiServer; - } - - - /** - * @param string $resourcePath path to method endpoint - * @param string $method method to call - * @param array $queryParams parameters to be place in query URL - * @param array $postData parameters to be placed in POST body - * @param array $headerParams parameters to be place in request header - * @return mixed - */ - public function callAPI($resourcePath, $method, $queryParams, $postData, - $headerParams) { - - $headers = array(); - - # Allow API key from $headerParams to override default - $added_api_key = False; - if ($headerParams != null) { - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - if ($key == 'api_key') { - $added_api_key = True; - } - } - } - if (! $added_api_key) { - $headers[] = "api_key: " . $this->apiKey; - } - - if (is_object($postData) or is_array($postData)) { - $postData = json_encode($this->sanitizeForSerialization($postData)); - } - - $url = $this->apiServer . $resourcePath; - - $curl = curl_init(); - curl_setopt($curl, CURLOPT_TIMEOUT, 5); - // return the result on success, rather than just TRUE - curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - - if (! empty($queryParams)) { - $url = ($url . '?' . http_build_query($queryParams)); - } - - if ($method == self::$POST) { - curl_setopt($curl, CURLOPT_POST, true); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$PUT) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method == self::$DELETE) { - curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); - } else if ($method != self::$GET) { - throw new Exception('Method ' . $method . ' is not recognized.'); - } - curl_setopt($curl, CURLOPT_URL, $url); - - // Make the request - $response = curl_exec($curl); - $response_info = curl_getinfo($curl); - - // Handle the response - if ($response_info['http_code'] == 0) { - throw new Exception("TIMEOUT: api call to " . $url . - " took more than 5s to return" ); - } else if ($response_info['http_code'] == 200) { - $data = json_decode($response); - } else if ($response_info['http_code'] == 401) { - throw new Exception("Unauthorized API request to " . $url . - ": ".json_decode($response)->message ); - } else if ($response_info['http_code'] == 404) { - $data = null; - } else { - throw new Exception("Can't connect to the api: " . $url . - " response code: " . - $response_info['http_code']); - } - - return $data; - } - - /** - * Build a JSON POST object - */ - protected function sanitizeForSerialization($data) - { - if (is_scalar($data) || null === $data) { - $sanitized = $data; - } else if ($data instanceof \DateTime) { - $sanitized = $data->format(\DateTime::ISO8601); - } else if (is_array($data)) { - foreach ($data as $property => $value) { - $data[$property] = $this->sanitizeForSerialization($value); - } - $sanitized = $data; - } else if (is_object($data)) { - $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - $values[$property] = $this->sanitizeForSerialization($data->$property); - } - $sanitized = $values; - } else { - $sanitized = (string)$data; - } - - return $sanitized; - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the path, by url-encoding. - * @param string $value a string which will be part of the path - * @return string the serialized object - */ - public static function toPathValue($value) { - return rawurlencode($value); - } - - /** - * Take value and turn it into a string suitable for inclusion in - * the query, by imploding comma-separated if it's an object. - * If it's a string, pass through unchanged. It will be url-encoded - * later. - * @param object $object an object to be serialized to a string - * @return string the serialized object - */ - public static function toQueryValue($object) { - if (is_array($object)) { - return implode(',', $object); - } else { - return $object; - } - } - - /** - * Just pass through the header value for now. Placeholder in case we - * find out we need to do something with header values. - * @param string $value a string which will be part of the header - * @return string the header string - */ - public static function toHeaderValue($value) { - return $value; - } - - /** - * Deserialize a JSON string into an object - * - * @param object $object object or primitive to be deserialized - * @param string $class class name is passed as a string - * @return object an instance of $class - */ - - public static function deserialize($data, $class) - { - if (null === $data) { - $deserialized = null; - } else if (strcasecmp(substr($class, 0, 6),'array[') == 0) { - $subClass = substr($class, 6, -1); - $values = array(); - foreach ($data as $value) { - $values[] = self::deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { - settype($data, $class); - $deserialized = $data; - } else { - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - if (isset($data->$property)) { - $instance->$property = self::deserialize($data->$property, $type); - } - } - $deserialized = $instance; - } - - return $deserialized; - } - -} - diff --git a/src/main/resources/python/swagger.mustache b/src/main/resources/python/swagger.mustache deleted file mode 100644 index b4e1fab35951..000000000000 --- a/src/main/resources/python/swagger.mustache +++ /dev/null @@ -1,211 +0,0 @@ -#!/usr/bin/env python -"""Wordnik.com's Swagger generic API client. This client handles the client- -server communication, and is invariant across implementations. Specifics of -the methods and models for each application are generated from the Swagger -templates.""" - -import sys -import os -import re -import urllib -import urllib2 -import httplib -import json -import datetime - -from models import * - - -class ApiClient: - """Generic API client for Swagger client library builds""" - - def __init__(self, apiKey=None, apiServer=None): - if apiKey == None: - raise Exception('You must pass an apiKey when instantiating the ' - 'APIClient') - self.apiKey = apiKey - self.apiServer = apiServer - self.cookie = None - - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None): - - url = self.apiServer + resourcePath - headers = {} - if headerParams: - for param, value in headerParams.iteritems(): - headers[param] = value - - #headers['Content-type'] = 'application/json' - headers['api_key'] = self.apiKey - - if self.cookie: - headers['Cookie'] = self.cookie - - data = None - - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.urlencode(sentQueryParams) - - if method in ['GET']: - - #Options to add statements later on and for compatibility - pass - - elif method in ['POST', 'PUT', 'DELETE']: - - if postData: - data = self.sanitizeForSerialization(postData) - if 'Content-type' not in headers: - headers['Content-type'] = 'application/json' - data = json.dumps(data) - else: - data = urllib.urlencode(data) - - else: - raise Exception('Method ' + method + ' is not recognized.') - - request = MethodRequest(method=method, url=url, headers=headers, - data=data) - - # Make the request - response = urllib2.urlopen(request) - if 'Set-Cookie' in response.headers: - self.cookie = response.headers['Set-Cookie'] - string = response.read() - - try: - data = json.loads(string) - except ValueError: # PUT requests don't return anything - data = None - - return data - - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value - """ - if type(obj) == list: - return urllib.quote(','.join(obj)) - else: - return urllib.quote(str(obj)) - - def sanitizeForSerialization(self, obj): - """Dump an object into JSON for POSTing.""" - - if type(obj) == type(None): - return None - elif type(obj) in [str, int, long, float, bool]: - return obj - elif type(obj) == list: - return [self.sanitizeForSerialization(subObj) for subObj in obj] - elif type(obj) == datetime.datetime: - return obj.isoformat() - else: - if type(obj) == dict: - objDict = obj - else: - objDict = obj.__dict__ - return {key: self.sanitizeForSerialization(val) - for (key, val) in objDict.iteritems() - if key != 'swaggerTypes'} - - if type(postData) == list: - # Could be a list of objects - if type(postData[0]) in safeToDump: - data = json.dumps(postData) - else: - data = json.dumps([datum.__dict__ for datum in postData]) - elif type(postData) not in safeToDump: - data = json.dumps(postData.__dict__) - - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. - - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" - - # Have to accept objClass as string or actual type. Type could be a - # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] - - if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) - else: # not a native type, must be model class - objClass = eval(objClass + '.' + objClass) - - if objClass in [int, long, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: - # Server will always return a time stamp in UTC, but with - # trailing +0000 indicating no offset from UTC. So don't process - # last 5 characters. - return datetime.datetime.strptime(obj[:-5], - "%Y-%m-%dT%H:%M:%S.%f") - - instance = objClass() - - for attr, attrType in instance.swaggerTypes.iteritems(): - if obj is not None and attr in obj and type(obj) in [list, dict]: - value = obj[attr] - if attrType in ['str', 'int', 'long', 'float', 'bool']: - attrType = eval(attrType) - try: - value = attrType(value) - except UnicodeEncodeError: - value = unicode(value) - except TypeError: - value = value - setattr(instance, attr, value) - elif (attrType == 'datetime'): - setattr(instance, attr, datetime.datetime.strptime(value[:-5], - "%Y-%m-%dT%H:%M:%S.%f")) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] - if not value: - setattr(instance, attr, None) - else: - for subValue in value: - subValues.append(self.deserialize(subValue, - subClass)) - setattr(instance, attr, subValues) - else: - setattr(instance, attr, self.deserialize(value, - objClass)) - - return instance - - -class MethodRequest(urllib2.Request): - - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib2.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" - - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib2.Request.__init__(self, *args, **kwargs) - - def get_method(self): - return getattr(self, 'method', urllib2.Request.get_method(self)) - diff --git a/src/main/resources/scala/model.mustache b/src/main/resources/scala/model.mustache deleted file mode 100644 index 59b6084dd207..000000000000 --- a/src/main/resources/scala/model.mustache +++ /dev/null @@ -1,18 +0,0 @@ -package {{package}} - -{{#imports}}import {{import}} -{{/imports}} - -{{#models}} - -{{#model}} - -case class {{classname}} ( - {{#vars}} - - {{#description}}/* {{{description}}} */ - {{/description}} - {{name}}: {{datatype}}{{#hasMore}},{{newline}} {{/hasMore}} - {{/vars}}) -{{/model}} -{{/models}} \ No newline at end of file diff --git a/src/main/resources/swagger-static/assets/images/logo.png b/src/main/resources/swagger-static/assets/images/logo.png deleted file mode 100644 index 209e5a473fc0..000000000000 Binary files a/src/main/resources/swagger-static/assets/images/logo.png and /dev/null differ diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicAndroidJavaClient.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicAndroidJavaClient.scala deleted file mode 100644 index d9166b562ff7..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicAndroidJavaClient.scala +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.model._ - -object BasicAndroidJavaClient extends BasicAndroidJavaGenerator { - def main(args: Array[String]) = generateClient(args) -} - -class BasicAndroidJavaGenerator extends BasicJavaGenerator { - override def typeMapping = super.typeMapping ++ Map( - "file" -> "File") - - override def importMapping = super.importMapping ++ Map( - "Set" -> "java.util.Set") - - override def defaultIncludes = Set( - "Integer", - "String", - "Long", - "Short", - "Char", - "Byte", - "Float", - "Double", - "Boolean", - "AnyRef", - "Any") - - // package for api invoker, error files - override def invokerPackage:Option[String] = Some("com.wordnik.client") - - override def templateDir = "android-java" - - // where to write generated code - override def destinationDir = "generated-code/android-java/src/main/java" - - // package for models - override def modelPackage: Option[String] = Some("com.wordnik.client.model") - - // package for api classes - override def apiPackage: Option[String] = Some("com.wordnik.client.api") - - /** - * you should override these params for generating the pom.xml and processing - * additional params - **/ - additionalParams ++= Map( - "artifactId" -> "android-client", - "artifactVersion" -> "1.0.0", - "groupId" -> "com.wordnik") - - // supporting classes - override def supportingFiles = List( - ("httpPatch.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "HttpPatch.java"), - ("apiInvoker.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiInvoker.java"), - ("jsonUtil.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "JsonUtil.java"), - ("apiException.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiException.java"), - ("pom.mustache", "generated-code/android-java", "pom.xml") - ) -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicCSharpGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicCSharpGenerator.scala deleted file mode 100644 index 3490ff00a7fa..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicCSharpGenerator.scala +++ /dev/null @@ -1,209 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.model._ - -object BasicCSharpGenerator extends BasicCSharpGenerator { - def main(args: Array[String]) = generateClient(args) -} - -class BasicCSharpGenerator extends BasicGenerator { - override def defaultIncludes = Set( - "char", - "double", - "int", - "long", - "float", - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float") - - /** - * We are using csharp objects instead of primitives to avoid showing default - * primitive values when the API returns missing data. For instance, having a - * {"count":0} != count is unknown. You can change this to use primitives if you - * desire, but update the default values as well or they'll be set to null in - * variable declarations. - */ - override def typeMapping = Map( - "array" -> "List", - "boolean" -> "bool?", - "string" -> "string", - "int" -> "int?", - "float" -> "float?", - "long" -> "long?", - "double" -> "double?", - "object" -> "object", - "Date" -> "DateTime?", - "date" -> "DateTime?", - "File" -> "byte[]", - "file" -> "byte[]") - - // location of templates - override def templateDir = "csharp" - - // where to write generated code - override def destinationDir = "generated-code/csharp/src" - - override def invokerPackage: Option[String] = Some("Swagger.Client.Common") - - // template used for models - modelTemplateFiles += "model.mustache" -> ".cs" - - // template used for models - apiTemplateFiles += "api.mustache" -> ".cs" - - override def reservedWords = Set("abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "do", "goto", "private", "this", "break", - "implements", "protected", "throw", "else", "import", "public", "throws", "case", - "enum", "instanceof", "return", "transient", "catch", "extends", "try", "final", - "interface", "static", "void", "class", "finally", "strictfp", "volatile", "const", - "native", "super", "while") - - // import/require statements for specific datatypes - override def importMapping = Map() - - // package for models - override def modelPackage: Option[String] = Some("Swagger.Client.Model") - - // package for api classes - override def apiPackage: Option[String] = Some("Swagger.Client.Api") - - // file suffix - override def fileSuffix = ".cs" - - // response classes - override def processResponseClass(responseClass: String): Option[String] = { - responseClass match { - case "void" => None - case e: String => Some(typeMapping.getOrElse(e, e.replaceAll("\\[", "<").replaceAll("\\]", ">"))) - } - } - - override def processResponseDeclaration(responseClass: String): Option[String] = { - responseClass match { - case "void" => None - case e: String => { - val ComplexTypeMatcher = "(.*)\\[(.*)\\].*".r - val t = e match { - case ComplexTypeMatcher(container, inner) => { - e.replaceAll(container, typeMapping.getOrElse(container.toLowerCase, container)) - } - case _ => e - } - Some(typeMapping.getOrElse(t, t.replaceAll("\\[", "<").replaceAll("\\]", ">"))) - } - } - } - - override def toDeclaredType(dt: String): String = { - val declaredType = dt.indexOf("[") match { - case -1 => dt - case n: Int => { - if (dt.substring(0, n) == "Array") - "List" + dt.substring(n).replaceAll("\\[", "<").replaceAll("\\]", ">") - else dt.replaceAll("\\[", "<").replaceAll("\\]", ">") - } - } - typeMapping.getOrElse(declaredType, declaredType) - } - - override def toDeclaration(obj: ModelProperty) = { - var declaredType = toDeclaredType(obj.`type`) - - declaredType.toLowerCase match { - case "array" => declaredType = "List" - case e: String => e - } - - val defaultValue = toDefaultValue(declaredType, obj) - declaredType match { - case "List" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + obj) - throw new Exception("no inner type defined") - } - } - } - declaredType += "<" + toDeclaredType(inner) + ">" - } - case _ => - } - (declaredType, defaultValue) - } - - /** - * we are defaulting to null values since the codegen uses csharp objects instead of primitives - * If you change to primitives, you can put in the appropriate values (0.0f, etc). - */ - override def toDefaultValue(dataType: String, obj: ModelProperty) = { - dataType match { - case "Boolean" => "null" - case "Integer" => "null" - case "Long" => "null" - case "Float" => "null" - case "Double" => "null" - case "List" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + dataType + ", " + obj) - throw new Exception("no inner type defined") - } - } - } - "new ArrayList<" + toDeclaredType(inner) + ">" + "()" - } - case _ => "null" - } - } - - override def escapeReservedWord(word: String) = { - if (reservedWords.contains(word)) - throw new Exception("reserved word " + "\"" + word + "\" not allowed") - else word - } - - /*override def toVarName(name: String): String = { - name match { - case _ if (reservedWords.contains(name)) => escapeReservedWord(name) - case _ => typeMapping.getOrElse(name, name) - } - capitalize(name) - } - - def capitalize(s: String) = { - s(0).toUpper + s.substring(1, s.length).toLowerCase - }*/ - - // supporting classes - override def supportingFiles = - List( - ("apiInvoker.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiInvoker.cs"), - ("apiException.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiException.cs"), - ("Newtonsoft.Json.dll", "generated-code/csharp/bin", "Newtonsoft.Json.dll"), - ("compile.mustache", "generated-code/csharp", "compile.bat")) -} \ No newline at end of file diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicFlashCodegen.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicFlashCodegen.scala deleted file mode 100644 index 95cf887ba3be..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicFlashCodegen.scala +++ /dev/null @@ -1,168 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.model._ - -abstract class BasicFlashCodegen extends BasicGenerator { - override def defaultIncludes = Set( - "Date", - "String", - "Boolean", - "Number") - - override def typeMapping = Map( - "boolean" -> "Boolean", - "string" -> "String", - "int" -> "Number", - "float" -> "Number", - "long" -> "Number", - "double" -> "Number") - - override def packageName = "com.wordnik.client" - - // location of templates - override def templateDir = "flash" - - // template used for models - modelTemplateFiles += "model.mustache" -> ".as" - modelTemplateFiles += "modelList.mustache" -> "List.as" - - // template used for models - apiTemplateFiles += "api.mustache" -> ".as" - - // where to write generated code - override def destinationDir = "src/test/flash" - - // import/require statements for specific datatypes - override def importMapping = Map() - - - // package for models - override def modelPackage: Option[String] = Some("com.wordnik.client.model") - - // package for api classes - override def apiPackage: Option[String] = Some("com.wordnik.client.api") - - // file suffix - override def fileSuffix = ".as" - - override def toVarName(name: String): String = { - name.substring(0, 1).toLowerCase + name.substring(1, name.length) - } - - // response classes - override def processResponseClass(responseClass: String): Option[String] = { - responseClass match { - case "void" => None - case e: String => Some(e) - } - } - - override def processResponseDeclaration(responseClass: String): Option[String] = { - responseClass match { - case "void" => None - case e: String => { - responseClass.startsWith("List") match { - case true => { - val responseSubClass = responseClass.dropRight(1).substring(5) - typeMapping.contains(responseSubClass) match { - case true => Some("Array") - case false => Some(packageName + ".model." + - responseSubClass + "List") - } - } - case false => Some(responseClass) - } - } - } - } - - override def toDeclaredType(dt: String): String = { - val declaredType = dt.indexOf("[") match { - case -1 => dt - case n: Int => { - if (dt.substring(0, n) == "Array") { - "Array" - } else if (dt.substring(0, n) == "List") { - "Array" - } else dt - } - } - typeMapping.getOrElse(declaredType, declaredType) - } - - override def toDeclaration(obj: ModelProperty) = { - var declaredType = toDeclaredType(obj.`type`) - - declaredType match { - case "Array" => { - declaredType = "Array" - } - case "List" => { - declaredType = "Array" - } - case e: String => e - } - - val defaultValue = toDefaultValue(declaredType, obj) - declaredType match { - case "List" => "Array" - case _ => - } - (declaredType, defaultValue) - } - - override def toDefaultValue(dataType: String, obj: ModelProperty) = { - dataType match { - case "Boolean" => "false" - case "Number" => "0.0" - case "List" => "new Array()" - case "Array" => "new Array()" - case _ => "null" - } - } - - def destinationRoot: String - - // supporting classes - def baseSupportingFiles = List( - ("ApiInvoker.as", destinationRoot + "/src/main/flex/com/wordnik/swagger/common", "ApiInvoker.as"), - ("ApiUrlHelper.as", destinationRoot + "/src/main/flex/com/wordnik/swagger/common", "ApiUrlHelper.as"), - ("ApiUserCredentials.as", destinationRoot + "/src/main/flex/com/wordnik/swagger/common", "ApiUserCredentials.as"), - ("ListWrapper.as", destinationRoot + "/src/main/flex/com/wordnik/swagger/common", "ListWrapper.as"), - ("SwaggerApi.as", destinationRoot + "/src/main/flex/com/wordnik/swagger/common", "SwaggerApi.as"), - ("XMLWriter.as", destinationRoot + "/src/main/flex/com/wordnik/swagger/common", "XMLWriter.as"), - - ("ApiError.as", destinationRoot + "/src/main/flex/com/wordnik/swagger/exception", "ApiError.as"), - ("ApiErrorCodes.as", destinationRoot + "/src/main/flex/com/wordnik/swagger/exception", "ApiErrorCodes.as"), - - ("ApiClientEvent.as", destinationRoot + "/src/main/flex/com/wordnik/swagger/event", "ApiClientEvent.as"), - ("Response.as", destinationRoot + "/src/main/flex/com/wordnik/swagger/event", "Response.as"), - - ("build.properties", destinationRoot, "build.properties"), - ("build.xml", destinationRoot, "build.xml"), - ("AirExecutorApp-app.xml", destinationRoot + "/bin", "AirExecutorApp-app.xml"), - - ("ASAXB-0.1.1.swc", destinationRoot + "/lib", "ASAXB-0.1.1.swc"), - ("as3corelib.swc", destinationRoot + "/lib/ext", "as3corelib.swc"), - ("flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc", destinationRoot + "/lib/ext", "flexunit-4.1.0_RC2-28-flex_3.5.0.12683.swc"), - ("flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc", destinationRoot + "/lib/ext", "flexunit-aircilistener-4.1.0_RC2-28-3.5.0.12683.swc"), - ("flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc", destinationRoot + "/lib/ext", "flexunit-cilistener-4.1.0_RC2-28-3.5.0.12683.swc"), - ("flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc", destinationRoot + "/lib/ext", "flexunit-core-flex-4.0.0.2-sdk3.5.0.12683.swc") - ) -} \ No newline at end of file diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicGenerator.scala deleted file mode 100644 index 254fda3fb482..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicGenerator.scala +++ /dev/null @@ -1,397 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen._ -import com.wordnik.swagger.codegen.util._ -import com.wordnik.swagger.codegen.language.CodegenConfig -import com.wordnik.swagger.codegen.spec.SwaggerSpecValidator -import com.wordnik.swagger.codegen.model._ -import com.wordnik.swagger.codegen.model.SwaggerSerializers -import com.wordnik.swagger.codegen.spec.ValidationMessage -import com.wordnik.swagger.codegen.spec.SwaggerSpec._ -import com.wordnik.swagger.util.ValidationException - -import java.io.{ File, FileWriter } - -import net.iharder.Base64 -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.write - -import scala.io._ -import scala.collection.JavaConversions._ -import scala.collection.mutable.{ ListBuffer, HashMap, HashSet } -import scala.io.Source - -abstract class BasicGenerator extends CodegenConfig with PathUtil { - implicit val formats = SwaggerSerializers.formats("1.2") - - def packageName = "com.wordnik.client" - def templateDir = "src/main/resources/scala" - def destinationDir = "generated-code/src/main/scala" - def fileSuffix = ".scala" - - override def invokerPackage: Option[String] = Some("com.wordnik.client.common") - override def modelPackage: Option[String] = Some("com.wordnik.client.model") - override def apiPackage: Option[String] = Some("com.wordnik.client.api") - - var codegen = new Codegen(this) - var fileMap: Option[String] = None - - @deprecated(message = "please use the generate function", since = "2.0.16") - def generateClient(args: Array[String]): Unit = { - generateClientWithoutExit(args) - System.exit(0) - } - - @deprecated(message = "please use the generate function", since = "2.0.16") - def generateClientWithoutExit(args: Array[String]): Seq[File] = { - if (args.length == 0) { - throw new RuntimeException("Need url to resource listing as argument. You can also specify VM Argument -DfileMap=/path/to/folder/containing.resources.json/") - } - val host = args(0) - val apiKey = if(args.length > 1) Some(args(1)) else None - val authorization = authenticate(apiKey) - - val opts = new ClientOpts() - opts.uri = host - opts.auth = authorization - opts.properties = Map("fileMap" -> sys.props("fileMap")) - - generate(opts) - } - - def generate(opts: ClientOpts) = { - if (opts == null) { - throw new RuntimeException("Need url to resource listing as argument. You can also specify VM Argument -DfileMap=/path/to/folder/containing.resources.json/") - } - val host = opts.uri - val authorization = opts.auth - - fileMap = Option(opts.properties.getOrElse("fileMap", null)) - val doc = ResourceExtractor.fetchListing(getResourcePath(host, fileMap), authorization) - - additionalParams ++= opts.properties - val apis: List[ApiListing] = getApis(host, doc, authorization) - - val errors = new ListBuffer[ValidationError] ++ SwaggerValidator.validate(doc) - for(api <- apis) - SwaggerValidator.validate(api, errors) - - errors.filter(_.severity == SwaggerValidator.ERROR).size match { - case i: Int if i > 0 => { - println("********* Failed to read swagger json!") - errors.foreach(msg => { - println(msg) - }) - Option(System.getProperty("skipErrors")) match { - case Some(str) => println("**** ignoring errors and continuing") - case None => { - val out = new StringBuilder - errors.foreach(m => out.append(m).append("\n")) - println(errors) - throw new ValidationException(400, "Failed validation", errors.toList) - } - } - } - case 0 => - } - - implicit val basePath = getBasePath(host, doc.basePath, fileMap) - - new SwaggerSpecValidator(doc, apis).validate() - - val allModels = new HashMap[String, Model] - val operations = extractApiOperations(apis, allModels) - val operationMap: Map[(String, String), List[(String, Operation)]] = - groupOperationsToFiles(operations) - - val modelMap = prepareModelMap(allModels.toMap) - val modelFileContents = writeFiles(modelMap, modelTemplateFiles.toMap) - val modelFiles = new ListBuffer[File]() - - for((filename, contents) <- modelFileContents) { - val file = new java.io.File(filename) - modelFiles += file - file.getParentFile().mkdirs - val fw = new FileWriter(filename, false) - fw.write(contents + "\n") - fw.close() - } - - val apiBundle = prepareApiBundle(operationMap.toMap) - val apiInfo = writeFiles(apiBundle, apiTemplateFiles.toMap) - val apiFiles = new ListBuffer[File]() - - apiInfo.map(m => { - val filename = m._1 - val file = new java.io.File(filename) - apiFiles += file - file.getParentFile().mkdirs - - val fw = new FileWriter(filename, false) - fw.write(m._2 + "\n") - fw.close() - println("wrote api " + filename) - }) - - codegen.writeSupportingClasses2(apiBundle, modelMap, doc.apiVersion) ++ - modelFiles ++ apiFiles - } - - /** - * applies a template to each of the models - */ - def writeFiles(models: List[Map[String, AnyRef]], templates: Map[String, String]): List[(String, String)] = { - val output = new ListBuffer[Tuple2[String, String]] - models.foreach(m => { - for ((templateFile, suffix) <- templates) { - val imports = m.getOrElse("imports", None) - val filename = m("outputDirectory").toString + File.separator + m("filename").toString + suffix - output += Tuple2(filename, generateSource(m, templateFile)) - } - }) - output.toList - } - - def generateSource(bundle: Map[String, AnyRef], templateFile: String): String = { - val rootDir = new java.io.File(".") - val (resourcePath, (engine, template)) = Codegen.templates.getOrElseUpdate(templateFile, codegen.compileTemplate(templateFile, Some(rootDir))) - var output = engine.layout(resourcePath, template, bundle) - - engine.compiler.shutdown - output - } - - def getApis(host: String, doc: ResourceListing, authorization: Option[ApiKeyValue]): List[ApiListing] = { - implicit val basePath = getBasePath(host, doc.basePath, fileMap) - println("base path is " + basePath) - - val apiReferences = doc.apis - if (apiReferences == null) - throw new Exception("No APIs specified by resource") - ApiExtractor.fetchApiListings(doc.swaggerVersion, basePath, apiReferences, authorization) - } - - def authenticate(apiKey: Option[String]): Option[ApiKeyValue] = { - val headerAuth = sys.props.get("header") map { e => - // this is ugly and will be replaced with proper arg parsing like in ScalaAsyncClientGenerator soon - val authInfo = e.split(":") - ApiKeyValue(authInfo(0), "header", authInfo(1)) - } - val basicAuth = sys.props.get("auth.basic") map { e => - val creds = if (e.contains(":")) Base64.encodeBytes(e.getBytes) else e - ApiKeyValue("Authorization", "header", s"Basic $creds") - } - val apiKeyAuth = apiKey map { key => - ApiKeyValue("api_key", "query", key) - } - - headerAuth orElse basicAuth orElse apiKeyAuth - } - - def extractApiOperations(apiListings: List[ApiListing], allModels: HashMap[String, Model] )(implicit basePath:String) = { - val output = new ListBuffer[(String, String, Operation)] - apiListings.foreach(apiDescription => { - val basePath = apiDescription.basePath - val resourcePath = apiDescription.resourcePath - if(apiDescription.apis != null) { - apiDescription.apis.foreach(api => { - for ((apiPath, operation) <- ApiExtractor.extractApiOperations(basePath, api)) { - output += Tuple3(basePath, apiPath, operation) - } - }) - } - output.map(op => processApiOperation(op._2, op._3)) - allModels ++= CoreUtils.extractApiModels(apiDescription) - }) - - output.toList - } - - /** - * creates a map of models and properties needed to write source - */ - def prepareModelMap(models: Map[String, Model]): List[Map[String, AnyRef]] = { - val allImports = new HashSet[String] - val outputDirectory = (destinationDir + File.separator + modelPackage.getOrElse("").replace(".", File.separator)) - (for ((name, schema) <- models) yield { - if (!defaultIncludes.contains(name)) { - val modelMap: Map[String, AnyRef] = codegen.modelToMap(name, schema) - - val imports = modelMap("imports").asInstanceOf[Set[Map[String, AnyRef]]] - - val models: List[Map[String, Map[String, AnyRef]]] = List(Map("model" -> modelMap)) - val m = new HashMap[String, AnyRef] - m += "imports" -> processImports(imports) - m += "name" -> toModelName(name) - m += "className" -> name - m += "filename" -> toModelFilename(name) - m += "apis" -> None - m += "models" -> models - m += "package" -> modelPackage - m += "invokerPackage" -> invokerPackage - m += "outputDirectory" -> outputDirectory - m += "newline" -> "\n" - m += "modelPackage" -> modelPackage - m += "modelJson" -> codegen.writeJson(schema) - m ++= additionalParams - Some(m.toMap) - } - else None - }).flatten.toList - } - - def processImports(ii: Set[Map[String, AnyRef]]) = { - val allImports = new HashSet[String]() - - ii.foreach(_.map(m => allImports += m._2.asInstanceOf[String])) - - val imports = new ListBuffer[Map[String, String]] - val includedModels = new HashSet[String] - val importScope = modelPackage match { - case Some(s) => s + "." - case _ => "" - } - // do the mapping before removing primitives! - allImports.foreach(value => { - val model = toModelName(value.asInstanceOf[String]) - includedModels.contains(model) match { - case false => { - importMapping.containsKey(model) match { - case true => { - if(!imports.flatten.map(m => m._2).toSet.contains(importMapping(model))) { - imports += Map("import" -> importMapping(model)) - } - } - case false => - } - } - case true => - } - }) - - allImports --= defaultIncludes - allImports --= primitives - allImports --= containers - allImports.foreach(i => { - val model = toModelName(i) - includedModels.contains(model) match { - case false => { - importMapping.containsKey(model) match { - case true => - case false => { - if(!imports.flatten.map(m => m._2).toSet.contains(importScope + model)){ - imports += Map("import" -> (importScope + model)) - } - } - } - } - case true => // no need to add the model - } - }) - imports - } - - def prepareApiBundle(apiMap: Map[(String, String), List[(String, Operation)]] ): List[Map[String, AnyRef]] = { - (for ((identifier, operationList) <- apiMap) yield { - val basePath = identifier._1 - val name = identifier._2 - val className = toApiName(name) - val allImports = new HashSet[String] - val operations = new ListBuffer[AnyRef] - val o = new ListBuffer[AnyRef] - - val classNameToOperationList = new HashMap[String, ListBuffer[AnyRef]] - for ((apiPath, operation) <- operationList) { - CoreUtils.extractModelNames(operation).foreach(i => allImports += i) - } - val imports = new ListBuffer[Map[String, String]] - val includedModels = new HashSet[String] - val modelList = new ListBuffer[Map[String, AnyRef]] - val importScope = modelPackage match { - case Some(s) => s + "." - case None => "" - } - - allImports --= defaultIncludes - allImports --= primitives - allImports --= containers - allImports.foreach(i => { - val model = toModelName(i) - if(!includedModels.contains(model) && !importMapping.containsKey(model)) { - if(!imports.flatten.map(m => m._2).toSet.contains(importScope + model)){ - imports += Map("import" -> (importScope + model)) - } - } - }) - - val names = new HashSet[String] - for((path, operation) <- operationList) { - val op = codegen.apiToMap(path, operation) - val nickname = op.getOrElse("nickname", op("httpMethod")).asInstanceOf[String] - var updatedNickname = nickname - if(names.contains(nickname)) { - var counter = 0 - var done = false - while(!done) { - updatedNickname = nickname + "_" + className + "_" + counter - if(!names.contains(updatedNickname)) done = true - counter += 1 - } - } - names += updatedNickname - o += (Map("path" -> path) ++ op ++ Map("nickname" -> updatedNickname)) - } - operations += Map("operation" -> o) - - val m = new HashMap[String, AnyRef] - m += "imports" -> imports - m += "baseName" -> name - m += "filename" -> toApiFilename(name) - m += "name" -> toApiName(name) - m += "classname" -> className - m += "className" -> className - m += "basePath" -> basePath - m += "package" -> apiPackage - m += "invokerPackage" -> invokerPackage - m += "operations" -> operations - m += "models" -> None - m += "outputDirectory" -> (destinationDir + File.separator + apiPackage.getOrElse("").replace(".", File.separator)) - m += "newline" -> "\n" - m += "modelPackage" -> modelPackage - - m ++= additionalParams - - Some(m.toMap) - }).flatten.toList - } - - def groupOperationsToFiles(operations: List[(String, String, Operation)]): Map[(String, String), List[(String, Operation)]] = { - val opMap = new HashMap[(String, String), ListBuffer[(String, Operation)]] - for ((basePath, apiPath, operation) <- operations) { - val className = resourceNameFromFullPath(apiPath) - val listToAddTo = opMap.getOrElse((basePath, className), { - val l = new ListBuffer[(String, Operation)] - opMap += (basePath, className) -> l - l - }) - listToAddTo += Tuple2(apiPath, operation) - } - opMap.map(m => (m._1, m._2.toList)).toMap - } -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicGroovyGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicGroovyGenerator.scala deleted file mode 100644 index 635d20fa5c66..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicGroovyGenerator.scala +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -object BasicGroovyGenerator extends BasicGroovyGenerator { - def main(args: Array[String]) = generateClient(args) -} - -class BasicGroovyGenerator extends BasicJavaGenerator { - - // location of templates - override def templateDir = "Groovy" - - // where to write generated code - override def destinationDir = "generated-code/groovy/src/main/groovy" - - // template used for models - modelTemplateFiles += "model.mustache" -> ".groovy" - - // template used for models - apiTemplateFiles += "api.mustache" -> ".groovy" - - - // package for models - override def modelPackage: Option[String] = Some("com.wordnik.client.model") - - // package for api classes - override def apiPackage: Option[String] = Some("com.wordnik.client.api") - - // file suffix - override def fileSuffix = ".groovy" - - - override def supportingFiles = - List( - ("ApiUtils.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiUtils.groovy"), - ("build.gradle.mustache", "generated-code/groovy", "build.gradle")) - -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala deleted file mode 100644 index 397b6a78d4ef..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala +++ /dev/null @@ -1,251 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.model._ - -object BasicJavaGenerator extends BasicJavaGenerator { - def main(args: Array[String]) = generateClient(args) -} - -class BasicJavaGenerator extends BasicGenerator { - override def defaultIncludes = Set( - "double", - "int", - "long", - "short", - "char", - "float", - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float") - - /** - * We are using java objects instead of primitives to avoid showing default - * primitive values when the API returns missing data. For instance, having a - * {"count":0} != count is unknown. You can change this to use primitives if you - * desire, but update the default values as well or they'll be set to null in - * variable declarations. - */ - override def typeMapping = Map( - "Array" -> "List", - "array" -> "List", - "List" -> "List", - "boolean" -> "Boolean", - "string" -> "String", - "int" -> "Integer", - "float" -> "Float", - "number" -> "BigDecimal", - "long" -> "Long", - "short" -> "Short", - "char" -> "String", - "double" -> "Double", - "object" -> "Object", - "integer" -> "Integer") - - // location of templates - override def templateDir = "Java" - - // where to write generated code - override def destinationDir = "generated-code/java/src/main/java" - - // template used for models - modelTemplateFiles += "model.mustache" -> ".java" - - // template used for models - apiTemplateFiles += "api.mustache" -> ".java" - - override def reservedWords = Set("abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while") - - // import/require statements for specific datatypes - override def importMapping = Map( - "BigDecimal" -> "java.math.BigDecimal", - "UUID" -> "java.util.UUID", - "File" -> "java.io.File", - "Date" -> "java.util.Date", - "Timestamp" -> "java.sql.Timestamp", - "Array" -> "java.util.*", - "ArrayList" -> "java.util.*", - "List" -> "java.util.*", - "Set" -> "java.util.*", - "DateTime" -> "org.joda.time.*", - "LocalDateTime" -> "org.joda.time.*", - "LocalDate" -> "org.joda.time.*", - "LocalTime" -> "org.joda.time.*" - ) - - // package for models - override def modelPackage: Option[String] = Some("com.wordnik.client.model") - - // package for api classes - override def apiPackage: Option[String] = Some("com.wordnik.client.api") - - // file suffix - override def fileSuffix = ".java" - - override def toVarName(name: String): String = { - val paramName = name.replaceAll("[^a-zA-Z0-9_]","") - super.toVarName(paramName) - } - - override def toApiFilename(name: String): String = { - val paramName = name.replaceAll("[^a-zA-Z0-9_]","") - super.toApiFilename(paramName) - } - - override def toApiName(name: String): String = { - val paramName = name.replaceAll("[^a-zA-Z0-9_]","") - super.toApiName(paramName) - } - - // response classes - override def processResponseClass(responseClass: String): Option[String] = { - responseClass match { - case "void" => None - case e: String => Some(typeMapping.getOrElse(e, e.replaceAll("\\[", "<").replaceAll("\\]", ">"))) - } - } - - override def processResponseDeclaration(responseClass: String): Option[String] = { - responseClass match { - case "void" => None - case e: String => { - val ComplexTypeMatcher = "(.*)\\[(.*)\\].*".r - val t = e match { - case ComplexTypeMatcher(container, inner) => { - e.replaceAll(container, typeMapping.getOrElse(container, container)) - } - case _ => e - } - Some(typeMapping.getOrElse(t, t.replaceAll("\\[", "<").replaceAll("\\]", ">"))) - } - } - } - - override def toDeclaredType(dt: String): String = { - val declaredType = dt.indexOf("[") match { - case -1 => dt - case n: Int => { - if (dt.substring(0, n) == "Array") - "List" + dt.substring(n).replaceAll("\\[", "<").replaceAll("\\]", ">") - else if (dt.substring(0, n) == "Set") - "Set" + dt.substring(n).replaceAll("\\[", "<").replaceAll("\\]", ">") - else dt.replaceAll("\\[", "<").replaceAll("\\]", ">") - } - } - typeMapping.getOrElse(declaredType, declaredType) - } - - override def toDeclaration(obj: ModelProperty) = { - var declaredType = toDeclaredType(obj.`type`) - declaredType match { - case "Array" => declaredType = "List" - case e: String => e - } - - val defaultValue = toDefaultValue(declaredType, obj) - declaredType match { - case "List" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + declaredType + ", " + obj) - throw new Exception("no inner type defined") - } - } - } - declaredType += "<" + toDeclaredType(inner) + ">" - } - case "Set" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + declaredType + ", " + obj) - throw new Exception("no inner type defined") - } - } - } - declaredType += "<" + toDeclaredType(inner) + ">" - } - case _ => - } - (declaredType, defaultValue) - } - - /** - * you should override these params for generating the pom.xml and processing - * additional params - **/ - additionalParams ++= Map( - "artifactId" -> "java-client", - "artifactVersion" -> "1.0.0", - "groupId" -> "com.wordnik") - - /** - * we are defaulting to null values since the codegen uses java objects instead of primitives - * If you change to primitives, you can put in the appropriate values (0.0f, etc). - */ - override def toDefaultValue(dataType: String, obj: ModelProperty) = { - dataType match { - case "Boolean" => "null" - case "Integer" => "null" - case "Long" => "null" - case "Short" => "null" - case "Float" => "null" - case "Double" => "null" - case "List" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + dataType + ", " + obj) - throw new Exception("no inner type defined") - } - } - } - "new ArrayList<" + toDeclaredType(inner) + ">" + "()" - } - case _ => "null" - } - } - - override def escapeReservedWord(word: String) = { - if (reservedWords.contains(word)) - throw new Exception("reserved word " + "\"" + word + "\" not allowed") - else word - } - - // supporting classes - override def supportingFiles = - List( - ("apiInvoker.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiInvoker.java"), - ("JsonUtil.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "JsonUtil.java"), - ("apiException.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiException.java"), - ("pom.mustache", "generated-code/java", "pom.xml")) -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala deleted file mode 100644 index b8877b7b6a22..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala +++ /dev/null @@ -1,247 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.model._ - -object BasicObjcGenerator extends BasicObjcGenerator { - def main(args: Array[String]) = generateClient(args) -} - -class BasicObjcGenerator extends BasicGenerator { - override def defaultIncludes = Set( - "bool", - "int", - "NSString", - "NSObject", - "NSArray", - "NSNumber") - - override def languageSpecificPrimitives = Set( - "NSNumber", - "NSString", - "NSObject", - "bool") - - override def reservedWords = Set("void", "char", "short", "int", "void", "char", "short", "int", "long", "float", "double", "signed", "unsigned", "id", "const", "volatile", "in", "out", "inout", "bycopy", "byref", "oneway", "self", "super") - - def foundationClasses = Set( - "NSNumber", - "NSObject", - "NSString") - - override def typeMapping = Map( - "enum" -> "NSString", - "date" -> "SWGDate", - "Date" -> "SWGDate", - "boolean" -> "NSNumber", - "string" -> "NSString", - "integer" -> "NSNumber", - "int" -> "NSNumber", - "float" -> "NSNumber", - "long" -> "NSNumber", - "double" -> "NSNumber", - "Array" -> "NSArray", - "array" -> "NSArray", - "List" -> "NSArray", - "object" -> "NSObject") - - override def importMapping = Map( - "Date" -> "SWGDate") - - override def toModelFilename(name: String) = "SWG" + name - - // naming for the models - override def toModelName(name: String) = { - (typeMapping.keys ++ - foundationClasses ++ - importMapping.values ++ - defaultIncludes ++ - languageSpecificPrimitives - ).toSet.contains(name) match { - case true => name(0).toUpper + name.substring(1) - case _ => { - "SWG" + name(0).toUpper + name.substring(1) - } - } - } - - // objective c doesn't like variables starting with "new" - override def toVarName(name: String): String = { - val paramName = name.replaceAll("[^a-zA-Z0-9_]","") - if(paramName.startsWith("new") || reservedWords.contains(paramName)) { - escapeReservedWord(paramName) - } - else paramName - } - - // naming for the apis - override def toApiName(name: String) = "SWG" + name(0).toUpper + name.substring(1) + "Api" - - // location of templates - override def templateDir = "objc" - - // template used for models - modelTemplateFiles += "model-header.mustache" -> ".h" - modelTemplateFiles += "model-body.mustache" -> ".m" - - // template used for apis - apiTemplateFiles += "api-header.mustache" -> ".h" - apiTemplateFiles += "api-body.mustache" -> ".m" - - // package for models - override def invokerPackage: Option[String] = None - - // package for models - override def modelPackage: Option[String] = None - - // package for api classes - override def apiPackage: Option[String] = None - - // response classes - override def processResponseClass(responseClass: String): Option[String] = { - typeMapping.contains(responseClass) match { - case true => Some(typeMapping(responseClass)) - case false => { - responseClass match { - case "void" => None - case e: String => { - if(responseClass.toLowerCase.startsWith("array") || responseClass.toLowerCase.startsWith("list")) - Some("NSArray") - else - Some(toModelName(responseClass)) - } - } - } - } - } - - override def processApiMap(m: Map[String, AnyRef]): Map[String, AnyRef] = { - val mutable = scala.collection.mutable.Map() ++ m - mutable += "newline" -> "\n" - - mutable.map(k => { - k._1 match { - case e: String if (e == "allParams") => { - val sp = (mutable(e)).asInstanceOf[List[_]] - sp.size match { - case i: Int if(i > 0) => mutable += "hasParams" -> "true" - case _ => - } - } - case _ => - } - }) - mutable.toMap - } - - override def processResponseDeclaration(responseClass: String): Option[String] = { - processResponseClass(responseClass) match { - case Some("void") => Some("void") - case Some(e) => Some(e + "*") - case _ => Some(responseClass) - } - } - - override def toDeclaredType(dt: String): String = { - val declaredType = dt.indexOf("[") match { - case -1 => dt - case n: Int => "NSArray" - } - val t = typeMapping.getOrElse(declaredType, declaredType) - - (languageSpecificPrimitives.contains(t) && !foundationClasses.contains(t)) match { - case true => toModelName(t) - case _ => toModelName(t) + "*" // needs pointer - } - } - - override def toDeclaration(obj: ModelProperty) = { - var declaredType = toDeclaredType(obj.`type`) - declaredType.toLowerCase match { - case "list" => { - declaredType = "array" - } - case e: String => e - } - - val defaultValue = toDefaultValue(declaredType, obj) - declaredType match { - case "array" => { - val inner = { - obj.items match { - case Some(items) => { - if(items.ref != null) - items.ref - else - items.`type` - } - case _ => { - println("failed on " + obj) - throw new Exception("no inner type defined") - } - } - } - "NSArray" - } - case "set" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + obj) - throw new Exception("no inner type defined") - } - } - } - "NSArray" - } - case _ => - } - (declaredType, defaultValue) - } - - override def escapeReservedWord(word: String) = "_" + word - - override def toDefaultValue(properCase: String, obj: ModelProperty) = { - properCase match { - case "boolean" => "false" - case "int" => "0" - case "long" => "0L" - case "float" => "0.0f" - case "double" => "0.0" - case "List" => { - val inner = { - obj.items match { - case Some(items) => { - if(items.ref != null) - items.ref - else - items.`type` - } - case _ => { - println("failed on " + properCase + ", " + obj) - throw new Exception("no inner type defined") - } - } - } - "new ArrayList<" + inner + ">" + "()" - } - case _ => "null" - } - } -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicPHPGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicPHPGenerator.scala deleted file mode 100644 index 2d659a0d1338..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicPHPGenerator.scala +++ /dev/null @@ -1,160 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.model._ - -import java.io.File - -object BasicPHPGenerator extends BasicPHPGenerator { - def main(args: Array[String]) = generateClient(args) -} - -class BasicPHPGenerator extends BasicGenerator { - // template used for models - modelTemplateFiles += "model.mustache" -> ".php" - - // template used for models - apiTemplateFiles += "api.mustache" -> ".php" - - // location of templates - override def templateDir = "php" - - // where to write generated code - override def destinationDir = "generated-code/php" - - // package for models - override def modelPackage: Option[String] = Some("models") - - // package for apis - override def apiPackage: Option[String] = Some("") - - // file suffix - override def fileSuffix = ".php" - - // reserved words which need special quoting - // These will all be object properties, in which context we don't need - // to worry about escaping them for PHP. - override def reservedWords = Set() - - // import/require statements for specific datatypes - override def importMapping = Map() - - - // response classes - override def processResponseClass(responseClass: String): Option[String] = { - typeMapping.contains(responseClass) match { - case true => Some(typeMapping(responseClass)) - case false => { - responseClass match { - case "void" => None - case e: String => { - responseClass.startsWith("List") match { - case true => Some("array") - case false => Some(responseClass) - } - } - } - } - } - } - - - override def processResponseDeclaration(responseClass: String): Option[String] = { - typeMapping.contains(responseClass) match { - case true => Some(typeMapping(responseClass)) - case false => { - responseClass match { - case "void" => None - case e: String => { - responseClass.startsWith("List") match { - case true => { - val responseSubClass = responseClass.dropRight(1).substring(5) - typeMapping.contains(responseSubClass) match { - case true => Some("array[" + typeMapping(responseSubClass) + "]") - case false => Some("array[" + responseSubClass + "]") - } - } - case false => Some(responseClass) - } - } - } - } - } - } - override def typeMapping = Map( - "string" -> "string", - "str" -> "string", - "int" -> "int", - "float" -> "float", - "long" -> "int", - "double" -> "float", - "Array" -> "array", - "boolean" -> "bool", - "Date" -> "DateTime" - ) - - override def toDeclaredType(dt: String): String = { - val declaredType = typeMapping.getOrElse(dt, dt) - declaredType.startsWith("Array") match { - case true => { - val innerType = dt.dropRight(1).substring(6) - typeMapping.contains(innerType) match { - case true => "array[" + typeMapping(innerType) + "]" - case false => "array[" + innerType + "]" - } - } - case _ => declaredType - } - } - - override def toDeclaration(obj: ModelProperty) = { - var declaredType = toDeclaredType(obj.`type`) - - declaredType match { - case "Array" => declaredType = "array" - case e: String => { - e - } - } - - val defaultValue = toDefaultValue(declaredType, obj) - declaredType match { - case "array" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + declaredType + ", " + obj) - throw new Exception("no inner type defined") - } - } - } - declaredType += "[" + toDeclaredType(inner) + "]" - "array" - } - case _ => - } - (declaredType, defaultValue) - } - - // supporting classes - override def supportingFiles = List( - ("Swagger.mustache", destinationDir + File.separator + apiPackage.get, - "Swagger.php") - ) -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicPython3Generator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicPython3Generator.scala deleted file mode 100644 index df2c3205ac21..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicPython3Generator.scala +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import java.io.File - -object BasicPython3Generator extends BasicPython3Generator { - def main(args: Array[String]) = generateClient(args) -} - -class BasicPython3Generator extends BasicPythonGenerator { - - // location of templates - override def templateDir = "python3" - - // where to write generated code - override def destinationDir = "generated-code/python3" - - // Python3 erases int/long distinction - override def typeMapping = Map( - "string" -> "str", - "int" -> "int", - "float" -> "float", - "long" -> "int", - "double" -> "float", - "Array" -> "list", - "array" -> "list", - "boolean" -> "bool", - "Date" -> "datetime" - ) -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicPythonGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicPythonGenerator.scala deleted file mode 100644 index 3ee85250f4f7..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicPythonGenerator.scala +++ /dev/null @@ -1,166 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.model._ - -import java.io.File - -object BasicPythonGenerator extends BasicPythonGenerator { - def main(args: Array[String]) = generateClient(args) -} - -class BasicPythonGenerator extends BasicGenerator { - // template used for models - modelTemplateFiles += "model.mustache" -> ".py" - - // template used for models - apiTemplateFiles += "api.mustache" -> ".py" - - // location of templates - override def templateDir = "python" - - // where to write generated code - override def destinationDir = "generated-code/python" - - // package for models - override def modelPackage: Option[String] = Some("models") - - // package for apis - override def apiPackage = None - - // file suffix - override def fileSuffix = ".py" - - // reserved words which need special quoting - // These will all be object properties, in which context we don't need - // to worry about escaping them for Python. - override def reservedWords = Set() - - // import/require statements for specific datatypes - override def importMapping = Map() - - - // response classes - override def processResponseClass(responseClass: String): Option[String] = { - typeMapping.contains(responseClass) match { - case true => Some(typeMapping(responseClass)) - case false => { - responseClass match { - case "void" => None - case e: String => { - responseClass.startsWith("List") match { - case true => Some("list") - case false => Some(responseClass) - } - } - } - } - } - } - - - override def processResponseDeclaration(responseClass: String): Option[String] = { - typeMapping.contains(responseClass) match { - case true => Some(typeMapping(responseClass)) - case false => { - responseClass match { - case "void" => None - case e: String => { - responseClass.startsWith("List") match { - case true => { - val responseSubClass = responseClass.dropRight(1).substring(5) - typeMapping.contains(responseSubClass) match { - case true => Some("list[" + typeMapping(responseSubClass) + "]") - case false => Some("list[" + responseSubClass + "]") - } - } - case false => Some(responseClass) - } - } - } - } - } - } - override def typeMapping = Map( - "integer" -> "int", - "float" -> "float", - "long" -> "long", - "double" -> "float", - "Array" -> "list", - "boolean" -> "bool", - "string" -> "str", - "Date" -> "datetime" - ) - - override def toDeclaredType(dt: String): String = { - val declaredType = typeMapping.getOrElse(dt, dt) - declaredType.startsWith("Array") match { - case true => { - val innerType = dt.dropRight(1).substring(6) - typeMapping.contains(innerType) match { - case true => "list[" + typeMapping(innerType) + "]" - case false => "list[" + innerType + "]" - } - } - case _ => { - declaredType - } - } - } - - override def toDeclaration(obj: ModelProperty) = { - var declaredType = toDeclaredType(obj.`type`) - - declaredType match { - case "Array" => declaredType = "list" - case e: String => { - e - } - } - - val defaultValue = toDefaultValue(declaredType, obj) - declaredType match { - case "list" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + declaredType + ", " + obj) - throw new Exception("no inner type defined") - } - } - } - declaredType += "[" + toDeclaredType(inner) + "]" - "list" - } - case _ => - } - (declaredType, defaultValue) - } - - // escape keywords - override def escapeReservedWord(word: String) = "`" + word + "`" - - // supporting classes - override def supportingFiles = List( - ("__init__.mustache", destinationDir, "__init__.py"), - ("swagger.mustache", destinationDir + File.separator + apiPackage.getOrElse(""), - "swagger.py"), - ("__init__.mustache", destinationDir + File.separator + - modelPackage.getOrElse(""), "__init__.py")) -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicRubyGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicRubyGenerator.scala deleted file mode 100644 index 90fc9ceecc02..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicRubyGenerator.scala +++ /dev/null @@ -1,117 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.model._ - -import java.io.File - -object BasicRubyGenerator extends BasicRubyGenerator { - def main(args: Array[String]) = generateClient(args) -} - -class BasicRubyGenerator extends BasicGenerator { - - override def apiPackage: Option[String] = Some("lib") - - // location of templates - override def templateDir = "ruby" - - // template used for models - modelTemplateFiles += "model.mustache" -> ".rb" - - // template used for models - apiTemplateFiles += "api.mustache" -> ".rb" - - // where to write generated code - override def destinationDir = "generated-code/ruby" - - // file suffix - override def fileSuffix = ".rb" - - // package for models - override def modelPackage: Option[String] = Some("models") - - // response classes - override def processResponseClass(responseClass: String): Option[String] = { - responseClass match { - case "void" => None - case e: String => Some(e) - } - } - - override def toApiName(name: String) = { - var fixedName = name.replaceAll("(\\{|\\})","") - fixedName(0).toUpper + fixedName.substring(1) + "_api" - } - - override def toModelFilename(name: String) = name.toLowerCase.replaceAll("(\\{|\\})","") - override def toApiFilename(name: String) = name.toLowerCase.replaceAll("(\\{|\\})","") + "_api" - override def toVarName(name: String): String = toUnderscore(name) - - override def toMethodName(name: String): String = toUnderscore(name) - - def toUnderscore(name: String): String = { - val sb = new StringBuilder - for ((char) <- super.toVarName(name)) { - if (char.isUpper) sb.append("_").append(char.toLower) - else sb.append(char) - } - sb.toString - } - - override def toDeclaration(obj: ModelProperty) = { - var dataType = obj.`type`(0).toUpper + obj.`type`.substring(1) - - dataType match { - case "Array" => dataType = "List" - case e: String => e - } - - val defaultValue = toDefaultValue(dataType, obj) - dataType match { - case "List" => { - val inner = { - obj.items match { - case Some(items) => { - if(items.ref != null) - items.ref - else - items.`type` - } - case _ => { - println("failed on " + dataType + ", " + obj) - throw new Exception("no inner type defined") - } - } - } - dataType = "java.util.List[" + inner + "]" - } - case _ => - } - (dataType, defaultValue) - } - - // supporting classes - override def supportingFiles = List( - ("monkey.mustache", destinationDir + File.separator + apiPackage.get, "monkey.rb"), - ("swagger.mustache", destinationDir + File.separator + apiPackage.get, "swagger.rb"), - ("swagger" + File.separator + "configuration.mustache", destinationDir + File.separator + apiPackage.get, "swagger" + File.separator + "configuration.rb"), - ("swagger" + File.separator + "response.mustache", destinationDir + File.separator + apiPackage.get, "swagger" + File.separator + "response.rb"), - ("swagger" + File.separator + "version.mustache", destinationDir + File.separator + apiPackage.get, "swagger" + File.separator + "version.rb"), - ("swagger" + File.separator + "request.mustache", destinationDir + File.separator + apiPackage.get, "swagger" + File.separator + "request.rb")) -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicScalaGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicScalaGenerator.scala deleted file mode 100644 index e4850a615440..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicScalaGenerator.scala +++ /dev/null @@ -1,221 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.model._ - -object BasicScalaGenerator extends BasicScalaGenerator { - def main(args: Array[String]) = generateClient(args) -} - -class BasicScalaGenerator extends BasicGenerator { - override def defaultIncludes = Set( - "Int", - "String", - "Long", - "Short", - "Char", - "Byte", - "Float", - "Double", - "Boolean", - "AnyRef", - "Any") - - override def typeMapping = Map( - "array" -> "List", - "set" -> "Set", - "boolean" -> "Boolean", - "string" -> "String", - "int" -> "Int", - "long" -> "Long", - "float" -> "Float", - "byte" -> "Byte", - "short" -> "Short", - "char" -> "Char", - "long" -> "Long", - "double" -> "Double", - "object" -> "Any", - "file" -> "File") - - // template used for models - modelTemplateFiles += "model.mustache" -> ".scala" - - // template used for models - apiTemplateFiles += "api.mustache" -> ".scala" - - // location of templates - override def templateDir = "scala" - - // where to write generated code - override def destinationDir = "generated-code/scala/src/main/scala" - - // reserved words which need special quoting - override def reservedWords = - Set( - "abstract", - "case", - "catch", - "class", - "def", - "do", - "else", - "extends", - "false", - "final", - "finally", - "for", - "forSome", - "if", - "implicit", - "import", - "lazy", - "match", - "new", - "null", - "object", - "override", - "package", - "private", - "protected", - "return", - "sealed", - "super", - "this", - "throw", - "trait", - "try", - "true", - "type", - "val", - "var", - "while", - "with", - "yield") - - // import/require statements for specific datatypes - override def importMapping = Map( - "Date" -> "java.util.Date", - "File" -> "java.io.File" - ) - - // package for models - override def modelPackage: Option[String] = Some("com.wordnik.client.model") - - // package for api classes - override def apiPackage: Option[String] = Some("com.wordnik.client.api") - - // response classes--if you don't want a response class, override and set to None - override def processResponseClass(responseClass: String): Option[String] = { - responseClass match { - case "void" => None - case e: String => Some(typeMapping.getOrElse(e, e)) - } - } - - override def processResponseDeclaration(responseClass: String): Option[String] = { - responseClass match { - case "void" => None - case e: String => { - val ComplexTypeMatcher = "(.*)\\[(.*)\\].*".r - val t = e match { - case ComplexTypeMatcher(container, inner) => { - e.replaceAll(container, typeMapping.getOrElse(container.toLowerCase, container)) - } - case _ => e - } - Some(typeMapping.getOrElse(t, t)) - } - } - } - - override def toDeclaredType(dt: String): String = { - val declaredType = dt.indexOf("[") match { - case -1 => dt - case n: Int => { - if (dt.substring(0, n) == "Array") - "List" + dt.substring(n) - else if (dt.substring(0, n) == "Set") - "Set" + dt.substring(n) - else dt - } - } - typeMapping.getOrElse(declaredType, declaredType) - } - - override def toDeclaration(obj: ModelProperty): (String, String) = { - obj.`type` match { - case "Array" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + obj) - throw new Exception("no inner type defined") - } - } - } - val e = "List[%s]".format(toDeclaredType(inner)) - (e, toDefaultValue(inner, obj)) - } - case "List" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + obj) - throw new Exception("no inner type defined") - } - } - } - val e = "List[%s]".format(toDeclaredType(inner)) - (e, toDefaultValue(inner, obj)) - } - case "Set" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + obj) - throw new Exception("no inner type defined") - } - } - } - val e = "Set[%s]".format(toDeclaredType(inner)) - (e, toDefaultValue(inner, obj)) - } - case e: String => (toDeclaredType(e), toDefaultValue(e, obj)) - } - } - - // escape keywords - override def escapeReservedWord(word: String) = "`" + word + "`" - - /** - * you should override these params for generating the pom.xml and processing - * additional params - **/ - additionalParams ++= Map( - "artifactId" -> "scala-client", - "artifactVersion" -> "1.0.0", - "groupId" -> "com.wordnik") - - // supporting classes - override def supportingFiles = List( - ("apiInvoker.mustache", destinationDir + "/com/wordnik/client", "ApiInvoker.scala"), - ("pom.mustache", "generated-code/scala", "pom.xml")) -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala b/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala deleted file mode 100644 index 1c45e382c2fa..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala +++ /dev/null @@ -1,553 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.model._ -import com.wordnik.swagger.codegen.util.CoreUtils -import com.wordnik.swagger.codegen.language.CodegenConfig -import com.wordnik.swagger.codegen.spec.SwaggerSpec._ - -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.write - -import org.fusesource.scalate._ -import org.fusesource.scalate.layout.DefaultLayoutStrategy -import org.fusesource.scalate.mustache._ -import org.fusesource.scalate.support.ScalaCompiler - -import java.io.{ File, FileWriter, InputStream } - -import org.apache.commons.io.FileUtils - -import scala.io.Source -import scala.collection.mutable.{ HashMap, ListBuffer, HashSet } -import scala.collection.JavaConversions._ - -object Codegen { - val templates = new HashMap[String, (String, (TemplateEngine, Template))] -} - -class Codegen(config: CodegenConfig) { - implicit val formats = SwaggerSerializers.formats("1.2") - - def compileTemplate(templateFile: String, rootDir: Option[File] = None, engine: Option[TemplateEngine] = None): (String, (TemplateEngine, Template)) = { - val engine = new TemplateEngine(rootDir orElse Some(new File("."))) - val srcName = config.templateDir + "/" + templateFile - val srcStream = { - getClass.getClassLoader.getResourceAsStream(srcName) match { - case is: java.io.InputStream => is - case _ => { - val f = new java.io.File(srcName) - if (!f.exists) throw new Exception("Missing template: " + srcName) - else new java.io.FileInputStream(f) - } - } - } - val template = engine.compile( - TemplateSource.fromText(config.templateDir + File.separator + templateFile, - Source.fromInputStream(srcStream).mkString)) - (srcName, engine -> template) - } - - def rawAllowableValuesToString(v: AllowableValues) = { - v match { - case av: AllowableListValues => { - av - } - case av: AllowableRangeValues => { - av - } - case _ => None - } - } - - - def allowableValuesToString(v: AllowableValues) = { - v match { - case av: AllowableListValues => { - Some(av.values.mkString("LIST[", ",", "]")) - } - case av: AllowableRangeValues => { - Some("RANGE[" + av.min + "," + av.max + "]") - } - case _ => None - } - } - - def apiToMap(path: String, operation: Operation): Map[String, AnyRef] = { - var bodyParam: Option[String] = None - var queryParams = new ListBuffer[AnyRef] - val pathParams = new ListBuffer[AnyRef] - val headerParams = new ListBuffer[AnyRef] - val bodyParams = new ListBuffer[AnyRef] - val formParams = new ListBuffer[AnyRef] - var paramList = new ListBuffer[HashMap[String, AnyRef]] - var errorList = new ListBuffer[HashMap[String, AnyRef]] - var bodyParamRequired: Option[String] = Some("true") - - if (operation.responseMessages != null) { - operation.responseMessages.foreach(param => { - val params = new HashMap[String, AnyRef] - params += "code" -> param.code.toString() - params += "reason" -> param.message - if (!param.responseModel.isEmpty) - params += "responseModel" -> param.responseModel - params += "hasMore" -> "true" - errorList += params - }) - } - - if (operation.parameters != null) { - operation.parameters.foreach(param => { - val params = new HashMap[String, AnyRef] - params += (param.paramType + "Parameter") -> "true" - params += "type" -> param.paramType - params += "defaultValue" -> config.toDefaultValue(param.dataType, param.defaultValue.getOrElse("")) - params += "swaggerDataType" -> param.dataType - params += "description" -> param.description - params += "hasMore" -> "true" - params += "allowMultiple" -> param.allowMultiple.toString - - if(param.dataType.toLowerCase() == "file") params += "isFile" -> "true" - else params += "notFile" -> "true" - - val u = param.dataType.indexOf("[") match { - case -1 => config.toDeclaredType(param.dataType) - case n: Int => { - val ComplexTypeMatcher = "(.*)\\[(.*)\\].*".r - val ComplexTypeMatcher(container, basePart) = param.dataType - config.toDeclaredType(container + "[" + config.toDeclaredType(basePart) + "]") - } - } - - params += "dataType" -> u - params += "getter" -> config.toGetter(param.name, u) - params += "setter" -> config.toSetter(param.name, u) - - param.allowableValues match { - case a: AllowableValues => params += "allowableValues" -> allowableValuesToString(a) - case _ => - } - - if (param.required) { - params += "required" -> "true" - } else { - params += "optional" -> "true" - } - param.paramType match { - case "body" => { - params += "paramName" -> "body" - params += "baseName" -> "body" - if (!param.required) { - bodyParamRequired = None - } - bodyParam = Some("body") - bodyParams += params.clone - } - case "path" => { - params += "paramName" -> config.toVarName(param.name) - params += "baseName" -> param.name - params += "required" -> "true" - params -= "optional" - pathParams += params.clone - } - case "query" => { - params += "paramName" -> config.toVarName(param.name) - params += "baseName" -> param.name - queryParams += params.clone - } - case "header" => { - params += "paramName" -> config.toVarName(param.name) - params += "baseName" -> param.name - headerParams += params.clone - } - case "form" => { - params += "paramName" -> config.toVarName(param.name) - params += "baseName" -> param.name - formParams += params.clone - } - case x @ _ => throw new Exception("Unknown parameter type: " + x) - } - paramList += params - }) - } - - val requiredParams = new ListBuffer[HashMap[String, AnyRef]] - paramList.filter(p => p.contains("required") && p("required") == "true").foreach(param => { - requiredParams += (param.clone += "hasMore" -> "true") - }) - requiredParams.size match { - case 0 => - case _ => requiredParams.last.asInstanceOf[HashMap[String, String]] -= "hasMore" - } - - headerParams.size match { - case 0 => - case _ => headerParams.last.asInstanceOf[HashMap[String, String]] -= "hasMore" - } - - queryParams.size match { - case 0 => - case _ => { - queryParams.head.asInstanceOf[HashMap[String, String]] += "first" -> "true" - queryParams.last.asInstanceOf[HashMap[String, String]] -= "hasMore" - } - } - - pathParams.size match { - case 0 => - case _ => pathParams.last.asInstanceOf[HashMap[String, String]] -= "hasMore" - } - errorList.size match{ - case 0 => - case _ => errorList.last.asInstanceOf[HashMap[String, String]] -= "hasMore" - } - - val sp = { - val lb = new ListBuffer[AnyRef] - paramList.foreach(i => { - i += "secondaryParam" -> "true" - i("defaultValue") match { - case Some(e) => - case None => lb += i - } - }) - paramList.foreach(i => { - i("defaultValue") match { - case Some(e) => lb += i - case None => - } - }) - lb.toList - } - - paramList.size match { - case 0 => - case _ => { - sp.head.asInstanceOf[HashMap[String, String]] -= "secondaryParam" - sp.last.asInstanceOf[HashMap[String, String]] -= "hasMore" - } - } - - val writeMethods = Set("POST", "PUT", "PATCH") - val properties = - HashMap[String, AnyRef]( - "path" -> path, - "nickname" -> config.toMethodName(operation.nickname), - "summary" -> operation.summary, - "notes" -> operation.notes, - "deprecated" -> operation.`deprecated`, - "bodyParam" -> bodyParam, - "bodyParamRequired" -> bodyParamRequired, - "emptyBodyParam" -> (if (writeMethods contains operation.method.toUpperCase) "{}" else ""), - "allParams" -> sp, - "bodyParams" -> bodyParams.toList, - "pathParams" -> pathParams.toList, - "queryParams" -> queryParams.toList, - "headerParams" -> headerParams.toList, - "formParams" -> formParams.toList, - "requiredParams" -> requiredParams.toList, - "errorList" -> errorList, - "httpMethod" -> operation.method.toUpperCase, - "httpMethodLowerCase" -> operation.method.toLowerCase, - operation.method.toLowerCase -> "true") - if (0 < operation.consumes.length) { - val o = new ListBuffer[Map[String, String]] - for(i <- 0 until operation.consumes.length) { - val m = new HashMap[String, String] - if(i < (operation.consumes.length - 1)) - m += "hasMore" -> "true" - m += "mediaType" -> operation.consumes(i) - o += m.toMap - } - properties += "consumes" -> o.toList - } else { - properties += "consumes" -> List(Map("mediaType" -> "application/json")) - } - if (0 < operation.produces.length) { - val o = new ListBuffer[Map[String, String]] - for(i <- 0 until operation.produces.length) { - val m = new HashMap[String, String] - if((i + 1) < operation.produces.length) - m += "hasMore" -> "true" - m += "mediaType" -> operation.produces(i) - o += m.toMap - } - properties += "produces" -> o.toList - } else { - properties += "produces" -> List(Map("mediaType" -> "application/json")) - } - if (requiredParams.size > 0) properties += "requiredParamCount" -> requiredParams.size.toString - operation.responseClass.indexOf("[") match { - case -1 => { - val baseType = operation.responseClass - properties += "returnType" -> config.processResponseDeclaration(baseType) - properties += "returnBaseType" -> config.processResponseClass(baseType) - properties += "returnSimpleType" -> "true" - properties += "returnTypeIsPrimitive" -> { - (config.languageSpecificPrimitives.contains(baseType) || primitives.contains(baseType)) match { - case true => Some("true") - case _ => None - } - } - } - case n: Int => { - val ComplexTypeMatcher = ".*\\[(.*)\\].*".r - val ComplexTypeMatcher(basePart) = operation.responseClass - - properties += "returnType" -> config.processResponseDeclaration(operation.responseClass.replaceAll(basePart, config.processResponseClass(basePart).get)) - properties += "returnContainer" -> config.processResponseClass(operation.responseClass.substring(0, n)) - properties += "returnBaseType" -> config.processResponseClass(basePart) - properties += "returnTypeIsPrimitive" -> { - (config.languageSpecificPrimitives.contains(basePart) || primitives.contains(basePart)) match { - case true => Some("true") - case _ => None - } - } - } - } - config.processApiMap(properties.toMap) - } - - def modelToMap(className: String, model: Model): Map[String, AnyRef] = { - val data: HashMap[String, AnyRef] = - HashMap( - "classname" -> config.toModelName(className), - "className" -> config.toModelName(className), - "classVarName" -> config.toVarName(className), // suggested name of object created from this class - "modelPackage" -> config.modelPackage, - "description" -> model.description, - "modelJson" -> writeJson(model), - "newline" -> "\n") - - val l = new ListBuffer[AnyRef] - - val imports = new HashSet[AnyRef] - model.properties.map(prop => { - val propertyDocSchema = prop._2 - val dt = propertyDocSchema.`type` - - var baseType = dt - // import the object inside the container - if (propertyDocSchema.items != null && !config.typeMapping.contains(dt)) { - // import the container - imports += Map("import" -> dt) - propertyDocSchema.items match { - case Some(items) => baseType = items.ref.getOrElse(items.`type`) - case _ => - } - } - baseType = config.typeMapping.contains(baseType) match { - case true => config.typeMapping(baseType) - case false => { - // imports += Map("import" -> config.toDeclaredType(baseType)) - baseType - } - } - (config.defaultIncludes ++ config.languageSpecificPrimitives).toSet.contains(baseType) match { - case true => - case _ => { - imports += Map("import" -> baseType) - } - } - - val isList = (if (isListType(propertyDocSchema.`type`)) true else None) - val isMap = (if (isMapType(propertyDocSchema.`type`)) true else None) - val isNotContainer = if (!isListType(propertyDocSchema.`type`) && !isMapType(propertyDocSchema.`type`)) true else None - val isContainer = if (isListType(propertyDocSchema.`type`) || isMapType(propertyDocSchema.`type`)) true else None - - val properties = - HashMap( - "name" -> config.toVarName(prop._1), - "nameSingular" -> { - val name = config.toVarName(prop._1) - if (name.endsWith("s") && name.length > 1) name.substring(0, name.length - 1) else name - }, - "baseType" -> { - if (primitives.contains(baseType)) - baseType - else - config.modelPackage match { - case Some(p) => p + "." + baseType - case _ => baseType - } - }, - "baseTypeVarName" -> config.toVarName(baseType), - "baseName" -> prop._1, - "datatype" -> config.toDeclaration(propertyDocSchema)._1, - "defaultValue" -> config.toDeclaration(propertyDocSchema)._2, - "description" -> propertyDocSchema.description, - "notes" -> propertyDocSchema.description, - "allowableValues" -> rawAllowableValuesToString(propertyDocSchema.allowableValues), - (if(propertyDocSchema.required) { - data += "hasRequiredParams" -> "true" - "required" - } else "isNotRequired") -> "true", - "getter" -> config.toGetter(prop._1, config.toDeclaration(propertyDocSchema)._1), - "setter" -> config.toSetter(prop._1, config.toDeclaration(propertyDocSchema)._1), - "isList" -> isList, - "isMap" -> isMap, - "isContainer" -> isContainer, - "isNotContainer" -> isNotContainer, - "hasMore" -> "true") - (config.languageSpecificPrimitives.contains(baseType) || primitives.contains(baseType)) match { - case true => properties += "isPrimitiveType" -> "true" - case _ => properties += "complexType" -> config.toModelName(baseType) - } - l += properties - }) - if(l.size > 0) { - val last = l.last.asInstanceOf[HashMap[String, String]] - last.remove("hasMore") - } - data += "vars" -> l - data += "imports" -> imports.toSet - config.processModelMap(data.toMap) - } - - /** - * gets an input stream from resource or file - */ - def getInputStream(path: String): InputStream = { - getClass.getClassLoader.getResourceAsStream(path) match { - case is: InputStream => is - case _ => new java.io.FileInputStream(path) - } - } - - def writeJson(m: AnyRef): String = { - Option(System.getProperty("modelFormat")) match { - case Some(e) if e =="1.1" => write1_1(m) - case _ => pretty(render(parse(write(m)))) - } - } - - def write1_1(m: AnyRef): String = { - implicit val formats = SwaggerSerializers.formats("1.1") - write(m) - } - - def writeSupportingClasses2( - apiBundle: List[Map[String, AnyRef]], - modelsMap: List[Map[String, AnyRef]], - apiVersion: String): Seq[File] = { - - - - val b = new HashMap[String, HashMap[String, AnyRef]] - modelsMap.foreach(m => { - if(m.contains("models")) { - val f = m("models").asInstanceOf[List[Map[String, AnyRef]]] - - f.foreach(g => { - val e = new HashMap[String, AnyRef] - val model = g("model").asInstanceOf[Map[String, AnyRef]] - e ++= model - e += "hasMoreModels" -> "true" - - b += model("classVarName").toString -> e - }) - } - }) - val models = new ListBuffer[HashMap[String, AnyRef]] - - val keys = b.keys - var count = 0 - b.values.foreach(v => { - models += v - count += 1 - if(count != keys.size) { - v += "hasMoreModels" -> "true" - } - else { - v.remove("hasMoreModels") - } - }) - - val f = Map("model" -> models) - val rootDir: Option[File] = Some(new File(".")) - val engine = new TemplateEngine(rootDir orElse Some(new File("."))) - - val data = Map( - "invokerPackage" -> config.invokerPackage, - "package" -> config.packageName, - "modelPackage" -> config.modelPackage, - "apiPackage" -> config.apiPackage, - "apiInfo" -> Map("apis" -> apiBundle), - "models" -> f, - "apiVersion" -> apiVersion) ++ config.additionalParams - - val outputFiles = config.supportingFiles map { file => - val supportingFile = file._1 - val outputDir = file._2 - val destFile = file._3 - - val outputFile = new File(outputDir + File.separator + destFile) - val outputFolder = outputFile.getParent - new File(outputFolder).mkdirs - - if (supportingFile.endsWith(".mustache")) { - val output = { - val (resourceName, (_, template)) = compileTemplate(supportingFile, rootDir, Some(engine)) - engine.layout(resourceName, template, data.toMap) - } - val fw = new FileWriter(outputFile, false) - fw.write(output + "\n") - fw.close() - println("wrote " + outputFile.getPath()) - } else { - val file = new File(config.templateDir + File.separator + supportingFile) - if (file.isDirectory()) { - // copy the whole directory - FileUtils.copyDirectory(file, new File(outputDir)) - println("copied directory " + supportingFile) - } else { - val is = getInputStream(config.templateDir + File.separator + supportingFile) - val parentDir = outputFile.getParentFile() - if (parentDir != null && !parentDir.exists) { - println("making directory: " + parentDir.toString + ": " + parentDir.mkdirs) - } - FileUtils.copyInputStreamToFile(is, outputFile) - println("copied " + outputFile.getPath()) - is.close - } - } - outputFile - } - //a shutdown method will be added to scalate in an upcoming release - engine.compiler.shutdown() - outputFiles - } - - protected def isListType(dt: String) = isCollectionType(dt, "List") || isCollectionType(dt, "Array") || isCollectionType(dt, "Set") - - protected def isMapType(dt: String) = isCollectionType(dt, "Map") - - protected def isCollectionType(dt: String, str: String) = { - if (dt.equals(str)) - true - else - dt.indexOf("[") match { - case -1 => false - case n: Int => { - if (dt.substring(0, n) == str) { - true - } else false - } - } - } -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/PathUtil.scala b/src/main/scala/com/wordnik/swagger/codegen/PathUtil.scala deleted file mode 100644 index b00aa5018968..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/PathUtil.scala +++ /dev/null @@ -1,63 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -trait PathUtil { - def getResourcePath(host: String, fileMap: Option[String] = None) = { - fileMap match { - case Some(s) => s - case _ => host - } - } - - def getBasePath(host: String, basePath: String, fileMap: Option[String] = None) = { - fileMap match { - case Some(s) => { - // return the parent folder - val f = new java.io.File(s) - f.getParent - } - case _ => { - if(basePath != "") basePath - else host - } - } - } - - def toModelName(name: String) = { - if(name.length > 0) - name(0).toUpper + name.substring(1) - else "MISSING MODEL NAME" - } - - def toApiName(name: String) = { - name.replaceAll("\\{","").replaceAll("\\}", "") match { - case s: String if(s.length > 0) => s(0).toUpper + s.substring(1) + "Api" - case _ => "Api" - } - } - - def nameFromPath(apiPath: String) = { - apiPath.split("/")(1).split("\\.")(0).replaceAll("/", "") - } - - def apiNameFromPath(apiPath: String) = toApiName(nameFromPath(apiPath)) - - def resourceNameFromFullPath(apiPath: String) = { - apiPath.split("/")(1).split("\\.")(0).replaceAll("/", "") - } -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/ScalaAsyncClientGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/ScalaAsyncClientGenerator.scala deleted file mode 100644 index ea0d33951297..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/ScalaAsyncClientGenerator.scala +++ /dev/null @@ -1,503 +0,0 @@ -package com.wordnik.swagger.codegen - -import java.io.File - -import com.wordnik.swagger.codegen.language.CodegenConfig -import com.wordnik.swagger.codegen.model._ -import mojolly.inflector.InflectorImports._ -import org.rogach.scallop.ScallopConf - -import scala.collection.JavaConverters._ -import scala.collection.mutable.HashMap - -case class SwaggerApi( - clientName: String, - resourceUrl: String, - packageName: String, - apiTemplates: Map[String, String] = Map("api.mustache" -> ".scala"), - modelTemplates: Map[String, String] = Map("model.mustache" -> ".scala"), - apiKey: Option[String] = None, - baseUrl: Option[String] = None, - excludedApis: Set[String] = Set.empty, - excludedModels: Set[String] = Set.empty, - excludedModelPackages: Set[String] = Set.empty, - defaultImports: Map[String, String] = Map.empty) -case class SwaggerGenConfig( - api: SwaggerApi, - templateDir: File, - codeDir: File, - projectRoot: File, - defaultIncludes: Set[String] = Set.empty, - typeMapping: Map[String, String] = Map.empty, - defaultImports: Map[String, String] = Map.empty, - excludedModelPackages: Set[String] = Set.empty) -object AsycnClientGeneratorConf { - val appBanner: String = """ - | - | - | .--.--. - | / / '. - || : /`. / .---. __ ,-. - |; | |--` /. ./| ,----._,. ,----._,. ,' ,'/ /| - || : ;_ .-'-. ' | ,--.--. / / ' // / ' / ,---. ' | |' | - | \ \ `. /___/ \: |/ \| : | : | / \| | ,' - | `----. \.-'.. ' ' .--. .-. | | .\ | | .\ ./ / ' : / - | __ \ \ /___/ \: '\__\/: . . ; '; . ; '; . ' / | | ' - | / /`--' . \ ' .\ ," .--.; ' . . ' . . ' ; /; : | - |'--'. / \ \ ' \ / / ,. |`---`-'| |`---`-'| ' | / | , ; - | `--'---' \ \ |--; : .' .'__/\_: |.'__/\_: | : |---' - | \ \ | | , .-.| : :| : :\ \ / - | '---" `--`---' \ \ / \ \ / `----' - | `--`-' `--`-' - | - | Swagger Codegen, Reverb Technologies Inc. (c) 2009-2013 - | For more info, visit: https://developers.helloreverb.com/swagger/ - """.stripMargin -} -class AsycnClientGeneratorConf(arguments: Seq[String]) extends ScallopConf(arguments) { - - val name = opt[String](required = true, descr = "The name of the generated client.") - val `package` = opt[String](default = Some("com.wordnik.swagger.client.async"), descr = "The package for the generated code.") - val resourceUrl = trailArg[String](descr = "The url to use for fetching the swagger spec from. This can be a http(s) url or a file path.") - val baseUrl = opt[String](descr = "The url to use when you want to override the base url provided by the resource url json.") - val apiKey = opt[String](required = false, descr = "An optional api key to use when calling the swagger api") - val templateDir = opt[String](descr = "The directory that contains the templates for use in this generator", default = Some("asyncscala")) - val codeDir = opt[String](descr = "The directory to use as base for generating code files, this will contain the generated scala files.", default = Some("src/main/scala"), hidden = true) - val projectRoot = opt[String](descr = "The directory to use as project dir, this will receive the build files (*.sbt, *.pom)", default = Some(".")) - - mainOptions = Seq(resourceUrl, name) - - banner(""" - |Usage: scala-async.sh [OPTION] spec-url - | - |The scala-async tool generates a swagger api client, using async-http-client - |and stdlib futures. - | - |Options: - | - """.stripMargin) - - footer("\nFor more information, visit https://developers.helloreverb.com/swagger/") -} - -object ScalaAsyncClientGenerator extends App { - val appBanner: String = AsycnClientGeneratorConf.appBanner - - val opts = new AsycnClientGeneratorConf(if (args.nonEmpty) args else Array("--help")) - val rootDir = new File(opts.projectRoot()) - val codeDir = { - val cd = opts.codeDir() - if (cd.startsWith("/")) new File(cd) - else new File(rootDir, cd) - } - val resUrl = { - val r = opts.resourceUrl() - if (!r.startsWith("http") && !r.startsWith("file")) sys.props("fileMap") = r - r - } - val baseUrl = opts.baseUrl.get - val cfg = SwaggerGenConfig( - api = SwaggerApi(opts.name(), resUrl, opts.`package`(), apiKey = opts.apiKey.get, baseUrl = baseUrl), - templateDir = new File(opts.templateDir()), - codeDir = new File(rootDir, opts.codeDir()), - projectRoot = rootDir - ) - - val generator = new ScalaAsyncClientGenerator(cfg) - - val clientOpts = new ClientOpts() - val props = new HashMap[String, String] - if(resUrl.startsWith("http")) - clientOpts.uri = resUrl - else - props += "fileMap" -> resUrl - - props += "clientName" -> cfg.api.clientName.underscore.pascalize - props += "projectName" -> cfg.api.clientName.underscore.dasherize - - clientOpts.properties = props.toMap.asJava - - println(appBanner) - generator.generate(clientOpts) -} - -class AsyncClientCodegen(clientName: String, config: CodegenConfig, rootDir: Option[File] = None) extends Codegen(config) { -/* - override def writeSupportingClasses(apis: Map[(String, String), List[(String, Operation)]], - models: Map[String, Model], apiVersion: String): Seq[File] = { - - def apiListF(apis: Map[(String, String), List[(String, Operation)]]): List[Map[String, AnyRef]] = { - val apiList = new ListBuffer[Map[String, AnyRef]] - apis.map(a => { - apiList += Map( - "name" -> a._1._2, - "filename" -> config.toApiFilename(a._1._2), - "className" -> config.toApiName(a._1._2), - "basePath" -> a._1._1, - "operations" -> { - (for (t <- a._2) yield { Map("operation" -> t._2, "path" -> t._1) }).toList - }) - }) - apiList.toList - } - - def modelListF(models: Map[String, Model]): List[Map[String, AnyRef]] = { - val modelList = new ListBuffer[HashMap[String, AnyRef]] - models.foreach(m => { - val json = write(m._2) - modelList += HashMap( - "modelName" -> m._1, - "model" -> m._2, - "filename" -> config.toModelFilename(m._1), - "modelJson" -> json, - "hasMore" -> "true") - }) - modelList.size match { - case 0 => - case _ => modelList.last.asInstanceOf[HashMap[String, String]] -= "hasMore" - } - modelList.map(_.toMap).toList - } - - def dataF(apis: Map[(String, String), List[(String, Operation)]], - models: Map[String, Model]): Map[String, AnyRef] = - Map( - "clientName" -> clientName.underscore.pascalize, - "projectName" -> clientName.underscore.dasherize, - "package" -> config.packageName, - "modelPackage" -> config.modelPackage, - "apiPackage" -> config.apiPackage, - "apis" -> apiListF(apis), - "models" -> modelListF(models)) - - writeSupportingClasses(apis, models, apiVersion, rootDir, dataF) - } - - override def compileTemplate(templateFile: String, rootDir: Option[File] = None, engine: Option[TemplateEngine] = None): (String, (TemplateEngine, Template)) = { - val eng = engine getOrElse new TemplateEngine(rootDir orElse Some(new File("."))) - val rn = config.templateDir + File.separator + templateFile - val rrn = "asyncscala" + File.separator + templateFile - val resourceName = if (new File(rn).exists) rn else rrn - val is = getInputStream(resourceName) - if (is == null) - throw new Exception("Missing template: " + resourceName) - - val template = eng.compile(TemplateSource.fromText(resourceName,Source.fromInputStream(is).mkString)) - (resourceName, eng -> template) - } -*/ -} - -class ScalaAsyncClientGenerator(cfg: SwaggerGenConfig) extends BasicGenerator { - private[this] val pascalizedClientName = cfg.api.clientName.underscore.pascalize - - override val packageName: String = cfg.api.packageName - override val templateDir: String = cfg.templateDir.getPath - override val destinationDir: String = cfg.codeDir.getPath - override val fileSuffix: String = ".scala" - override val modelPackage: Option[String] = Some(packageName + ".model") - override val apiPackage: Option[String] = Some(packageName + ".apis") - - - override val reservedWords: Set[String] = - Set( - "abstract", - "case", - "catch", - "class", - "def", - "do", - "else", - "extends", - "false", - "final", - "finally", - "for", - "forSome", - "if", - "implicit", - "import", - "lazy", - "match", - "new", - "null", - "object", - "override", - "package", - "private", - "protected", - "return", - "sealed", - "super", - "this", - "throw", - "trait", - "try", - "true", - "type", - "val", - "var", - "while", - "with", - "yield") - override val importMapping = Map( - "Date" -> "java.util.Date", - "File" -> "java.io.File" - ) ++ cfg.defaultImports ++ cfg.api.defaultImports - override val typeMapping = Map( - "array" -> "List", - "boolean" -> "Boolean", - "string" -> "String", - "int" -> "Int", - "long" -> "Long", - "float" -> "Float", - "byte" -> "Byte", - "short" -> "Short", - "char" -> "Char", - "long" -> "Long", - "double" -> "Double", - "object" -> "Any", - "file" -> "File") ++ cfg.typeMapping - - override val defaultIncludes = Set( - "Int", - "String", - "Long", - "Short", - "Char", - "Byte", - "Float", - "Double", - "Boolean", - "AnyRef", - "Any") ++ cfg.defaultIncludes ++ cfg.api.excludedModels - - override def supportingFiles = List( - ("client.mustache", destinationDir + "/" + cfg.api.packageName.replace('.', '/'), (pascalizedClientName +".scala")), - ("sbt.mustache", cfg.projectRoot.getPath, "swagger-client.sbt") - ) - - modelTemplateFiles ++= cfg.api.modelTemplates - apiTemplateFiles ++= cfg.api.apiTemplates - - codegen = new AsyncClientCodegen(cfg.api.clientName, this, Some(cfg.projectRoot)) - - override def getBasePath(host: String, basePath: String, fileMap: Option[String]): String = - cfg.api.baseUrl.getOrElse(super.getBasePath(host, basePath, fileMap)) -/* - override def generateClient(args: Array[String]) = { - val host = cfg.api.resourceUrl - val authorization = { - val apiKey = cfg.api.apiKey - if(apiKey != None) - Some(ApiKeyValue("api_key", "query", apiKey.get)) - else - None - } - - val doc = { - try { - ResourceExtractor.fetchListing(getResourcePath(host, fileMap), authorization) - } catch { - case e: Exception => throw new Exception("unable to read from " + host, e) - } - } - - implicit val basePath = getBasePath(host, doc.basePath, fileMap) - - val apiReferences = doc.apis - if (apiReferences == null) - throw new Exception("No APIs specified by resource") - val apis = ApiExtractor.fetchApiListings(doc.swaggerVersion, basePath, apiReferences, authorization) - - new SwaggerSpecValidator(doc, apis).validate() - - val allModels = new mutable.HashMap[String, Model] - val operations = extractApiOperations(apis, allModels) - val operationMap = groupOperationsToFiles(operations) - - val modelMap = prepareModelMap(allModels.toMap) - - val modelFileContents = writeFiles(modelMap, modelTemplateFiles.toMap) - val modelFiles = new ListBuffer[File]() - - for((filename, contents) <- modelFileContents) { - val file = new java.io.File(filename) - modelFiles += file - file.getParentFile().mkdirs - val fw = new FileWriter(filename, false) - fw.write(contents + "\n") - fw.close() - } - - val apiBundle = prepareApiBundle(operationMap.toMap) - val apiInfo = writeFiles(apiBundle, apiTemplateFiles.toMap) - val apiFiles = new ListBuffer[File]() - - apiInfo.map(m => { - val filename = m._1 - val file = new java.io.File(filename) - apiFiles += file - file.getParentFile().mkdirs - - val fw = new FileWriter(filename, false) - fw.write(m._2 + "\n") - fw.close() - println("wrote api " + filename) - }) - - codegen.writeSupportingClasses2(apiBundle, allModels.toMap, doc.apiVersion) ++ - modelFiles ++ apiFiles - } - - - - override def extractApiOperations(apiListings: List[ApiListing], allModels: mutable.HashMap[String, Model] )(implicit basePath:String) = { - val output = new mutable.ListBuffer[(String, String, Operation)] - apiListings.foreach(apiDescription => { - val basePath = apiDescription.basePath - val resourcePath = apiDescription.resourcePath - if(apiDescription.apis != null) { - apiDescription.apis.foreach(api => { - for ((apiPath, operation) <- ApiExtractor.extractApiOperations(basePath, api)) { - output += ((basePath, apiPath, operation)) - } - }) - } - output.map(op => processApiOperation(op._2, op._3)) - allModels ++= CoreUtils.extractApiModels(apiDescription, defaultIncludes, typeMapping) - }) - output.toList - } - - override def toModelName(name: String) = toDeclaredType(name.pascalize) -*/ - override def toApiName(name: String) = { - name.replaceAll("\\{","").replaceAll("\\}", "") match { - case s: String if(s.length > 0) => s.underscore.pascalize + "Client" - case _ => "Client" - } - } - -// -// override def nameFromPath(apiPath: String) = resourceNameFromFullPath(apiPath) -// -// -// override def resourceNameFromFullPath(apiPath: String) = -// apiPath.split('/').head.split('.').head - - /** - * creates a map of models and properties needed to write source - */ -/* - override def prepareModelMap(models: Map[String, Model]): List[Map[String, AnyRef]] = { - for { - (name, schema) <- (models -- defaultIncludes).toList - if !(cfg.excludedModelPackages ++ cfg.api.excludedModelPackages).exists(schema.qualifiedType.startsWith) - } yield { - Map( - "name" -> toModelName(name), - "className" -> name, - "filename" -> toModelFilename(name), - "apis" -> None, - "models" -> List((name, schema)), - "package" -> modelPackage, - "invokerPackage" -> invokerPackage, - "outputDirectory" -> (destinationDir + File.separator + modelPackage.getOrElse("").replaceAll("\\.", File.separator)), - "newline" -> "\n") - } - } - - override def prepareApiBundle(apiMap: Map[(String, String), List[(String, Operation)]] ): List[Map[String, AnyRef]] = { - for { - ((basePath, name), operationList) <- apiMap.toList - className = toApiName(name) - } yield { - Map( - "baseName" -> name, - "filename" -> toApiFilename(name), - "name" -> toApiName(name), - "className" -> className, - "basePath" -> basePath, - "package" -> apiPackage, - "invokerPackage" -> invokerPackage, - "apis" -> Map(className -> operationList.toList), - "models" -> None, - "outputDirectory" -> (destinationDir + File.separator + apiPackage.getOrElse("").replaceAll("\\.", File.separator)), - "newline" -> "\n") - } - } - - def bundleToSource(bundle:List[Map[String, AnyRef]], templates: Map[String, String]): List[(String, String)] = { - bundle.foldLeft(List.empty[(String, String)]) { (acc, m) => - templates.foldLeft(acc) { (out, tem) => - val (file, suffix) = tem - (m("outputDirectory").toString + File.separator + m("filename").toString + suffix) -> codegen.generateSource(m, file) :: acc - } - } - } - - def generateAndWrite(bundle: Map[String, AnyRef], templateFile: String) = { - val output = codegen.generateSource(bundle, templateFile) - val outputDir = new File(bundle("outputDirectory").asInstanceOf[String]) - outputDir.mkdirs - - val filename = outputDir + File.separator + bundle("filename") - val fw = new FileWriter(filename, false) - fw.write(output + "\n") - fw.close() - println("wrote " + filename) - } -*/ - - // response classes--if you don't want a response class, override and set to None - override def processResponseClass(responseClass: String): Option[String] = { - responseClass match { - case "void" => None //Some("Unit") - case e: String => Some(toDeclaredType(e)) - } - } - - override def processResponseDeclaration(responseClass: String): Option[String] = { - responseClass match { - case "void" => None //Some("Unit") - case e: String => Some(toDeclaredType(e)) - } - } - - override def toDeclaredType(dt: String): String = { - val declaredType = (dt.indexOf("[")) match { - case -1 => dt - case n: Int => { - if (dt.substring(0, n).toLowerCase == "array") { - val dtt = dt.substring(n + 1, dt.length - 1) - "List[%s]".format(typeMapping.getOrElse(dtt, dtt)) - } else dt - } - } - typeMapping.getOrElse(declaredType, declaredType) - } - - override def toDeclaration(obj: ModelProperty): (String, String) = { - obj.`type` match { - case "Array" | "array" => makeContainerType(obj, "List") - case "Set" | "set" => makeContainerType(obj, "Set") - case e: String => (toDeclaredType(e), toDefaultValue(e, obj)) - } - } - - private def makeContainerType(obj: ModelProperty, container: String): (String, String) = { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => throw new Exception("no inner type defined") - } - } - val e = "%s[%s]" format (container, toDeclaredType(inner)) - (e, toDefaultValue(inner, obj)) - } - - // escape keywords - override def escapeReservedWord(word: String) = "`" + word + "`" - -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/SpecConverter.scala b/src/main/scala/com/wordnik/swagger/codegen/SpecConverter.scala deleted file mode 100644 index 8c69aca47e69..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/SpecConverter.scala +++ /dev/null @@ -1,71 +0,0 @@ -package com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.util.{ ResourceExtractor, ApiExtractor } -import com.wordnik.swagger.codegen.model._ - -import java.io.File - -import org.json4s._ -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.{ read, write } - -object SpecConverter { - def main(args: Array[String]) = { - implicit val formats = SwaggerSerializers.formats("1.2") - - if(args == null || args.length < 2) { - println("Usage: SpecConverter {host} {outputDir}\nIf no API key is required, use an empty string") - sys.exit(0) - } - - val url = args(0) - val key = None - val outputDir = new File(args(1)) - - if(!outputDir.exists) outputDir.mkdir - - val resourcePath = url.split("/").last - val resourceListing = ResourceExtractor.fetchListing(url, key) - - resourceListing.swaggerVersion match { - case "1.1" => - case e: String => { - println("unsupported swagger version %s".format(e)) - sys.exit(0) - } - } - - val updatedListing = { - val apis = (for(api <- resourceListing.apis) yield { - val path = if(api.path.startsWith("/" + resourcePath)) { - api.path.substring(resourcePath.length + 1) - } - else api.path - api.copy(path = path.replace(".{format}","")) - }).toList - resourceListing.copy(apis = apis, swaggerVersion = "1.2") - } - writeToFile(outputDir + File.separator + "api-docs", write(updatedListing)) - - val listings = ApiExtractor.fetchApiListings(resourceListing.swaggerVersion, resourceListing.basePath, resourceListing.apis, key) - - listings.foreach(listing => { - val apis = (for(api <- listing.apis) yield { - api.copy(path = api.path.replace(".{format}", "")) - }) - val filename = listing.resourcePath.replace("/","") - val updatedApi = listing.copy(swaggerVersion = "1.2", apis = apis) - writeToFile(outputDir + File.separator + filename, write(updatedApi)) - }) - } - - def writeToFile(p: String, s: String) { - val pw = new java.io.PrintWriter(new File(p)) - try { - println("writing file %s".format(p)) - pw.write(s) - } finally { - pw.close() - } - } -} \ No newline at end of file diff --git a/src/main/scala/com/wordnik/swagger/codegen/SwaggerDocGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/SwaggerDocGenerator.scala deleted file mode 100644 index 3c1eae075ef9..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/SwaggerDocGenerator.scala +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen - -import com.wordnik.swagger.codegen.spec.SwaggerSpec -import com.wordnik.swagger.codegen.model._ - -import scala.collection.mutable.{ HashMap, ListBuffer } - -object SwaggerDocGenerator extends SwaggerDocGenerator { - def main(args: Array[String]) = generateClient(args) -} - -class SwaggerDocGenerator extends BasicGenerator { - override def templateDir = "src/main/resources/swagger-static" - - val outputFolder = "samples/swagger-static-docs" - - // where to write generated code - override def destinationDir = outputFolder + "/docs" - - // template used for apis - apiTemplateFiles += "operation.mustache" -> ".html" - - modelTemplateFiles += "model.mustache" -> ".html" - - override def toDeclaration(obj: ModelProperty): (String, String) = { - obj.`type` match { - case "Array" => { - val inner = { - obj.items match { - case Some(items) => items.ref.getOrElse(items.`type`) - case _ => { - println("failed on " + obj) - throw new Exception("no inner type defined") - } - } - } - val e = "List[%s]" format toDeclaredType(inner) - (e, toDefaultValue(inner, obj)) - } - case e: String => (toDeclaredType(e), toDefaultValue(e, obj)) - } - } - - override def processApiMap(m: Map[String, AnyRef]): Map[String, AnyRef] = { - val mutable = scala.collection.mutable.Map() ++ m - mutable.map(k => { - k._1 match { - case "allParams" => { - val paramList = k._2.asInstanceOf[List[_]] - paramList.foreach(param => { - val map = param.asInstanceOf[scala.collection.mutable.HashMap[String, AnyRef]] - if(map.contains("dataType")){ - val ComplexTypeMatcher = ".*\\[(.*)\\].*".r - val v = map("dataType") match { - case ComplexTypeMatcher(v) => v - case _ => map("dataType").asInstanceOf[String] - } - if(SwaggerSpec.primitives.contains(v)) { - map += "simpleType" -> v - } - else { - map += "complexType" -> v - } - } - }) - } - case _ => - } - }) - mutable.toMap - } - - // package for models - override def modelPackage: Option[String] = Some("models") - - // package for api classes - override def apiPackage: Option[String] = Some("operations") - - override def supportingFiles = List( - ("package.mustache", outputFolder, "package.json"), - ("main.mustache", outputFolder, "main.js"), - ("assets/css/bootstrap-responsive.css", destinationDir + "/assets/css", "bootstrap-responsive.css"), - ("assets/css/bootstrap.css", destinationDir + "/assets/css", "bootstrap.css"), - ("assets/css/style.css", destinationDir + "/assets/css", "style.css"), - ("assets/images/logo.png", destinationDir + "/assets/images", "logo.png"), - ("assets/js/bootstrap.js", destinationDir + "/assets/js", "bootstrap.js"), - ("assets/js/jquery-1.8.3.min.js", destinationDir + "/assets/js", "jquery-1.8.3.min.js"), - ("assets/js/main.js", destinationDir + "/assets/js", "main.js"), - ("index.mustache", destinationDir, "index.html") - ) -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/language/CodegenConfig.scala b/src/main/scala/com/wordnik/swagger/codegen/language/CodegenConfig.scala deleted file mode 100644 index 022929949f94..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/language/CodegenConfig.scala +++ /dev/null @@ -1,156 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.language - -import com.wordnik.swagger.codegen.model._ - -import scala.collection.mutable.{ HashMap, HashSet } - -abstract class CodegenConfig { - /* - * abstract methods - */ - def packageName: String - def templateDir: String - def destinationDir: String - def toModelName(name: String): String - def toApiName(name: String): String - - def toModelFilename(name: String) = name - def toApiFilename(name: String) = toApiName(name) - def apiNameFromPath(apiPath: String): String - def processApiMap(m: Map[String, AnyRef]): Map[String, AnyRef] = m - def processModelMap(m: Map[String, AnyRef]): Map[String, AnyRef] = m - - val apiTemplateFiles = new HashMap[String, String]() - val modelTemplateFiles = new HashMap[String, String]() - val additionalParams = new HashMap[String, String] - - def defaultIncludes = Set[String]() - def languageSpecificPrimitives = Set[String]() - def typeMapping = Map[String, String]() - - // optional configs - def invokerPackage: Option[String] = None - def apiPackage: Option[String] = None - def modelPackage: Option[String] = None - - def reservedWords: Set[String] = Set() - - // swagger primitive types - def importMapping: Map[String, String] = Map() - def escapeReservedWord(word: String) = word - - // only process these apis (by name) - val apisToProcess = new HashSet[String] - - // only process these models - val modelsToProcess = new HashSet[String] - - // method name from operation.nickname - def toMethodName(name: String): String = name - - // override if you want to do something special on processing - // def processOperation(apiPath: String, op: DocumentationOperation) = {} - def processOperation(apiPath: String, op: Operation) = {} - - def processResponseClass(responseClass: String): Option[String] = Some(responseClass) - - def processApiOperation(apiPath: String, op: Operation) = {} - def processResponseDeclaration(responseClass: String): Option[String] = { - responseClass match { - case "void" => None - case e: String => Some(toDeclaredType(e)) - } - } - - def supportingFiles = List(): List[(String, String, String)] - - // mapping for datatypes - def toDeclaration(property: ModelProperty) = { - var declaredType = toDeclaredType(property.`type`) - val defaultValue = toDefaultValue(declaredType, property) - (declaredType, defaultValue) - } - - def toDeclaredType(dataType: String): String = { - typeMapping.getOrElse(dataType, dataType) - } - - def toGetter(name: String, datatype: String) = { - val base = datatype match { - case "boolean" => "is" - case _ => "get" - } - base + { - if (name.length > 0) name(0).toUpper + name.substring(1) - else "" - } - } - - def toSetter(name: String, datatype: String) = { - val base = datatype match { - case _ => "set" - } - base + { - if (name.length > 0) name(0).toUpper + name.substring(1) - else "" - } - } - - def toVarName(name: String): String = { - name match { - case _ if (reservedWords.contains(name)) => escapeReservedWord(name) - case _ => name - } - } - - def toDefaultValue(datatype: String, v: String): Option[String] = { - if (v != "" && v != null) { - datatype match { - case "int" => Some(v) - case "long" => Some(v) - case "double" => Some(v) - case x if x == "string" || x == "String" => { - v match { - case e: String => Some("\"" + v + "\"") - case _ => None - } - } - case _ => None - } - } else None - } - - def toDefaultValue(dataType: String, obj: ModelProperty) = { - dataType match { - case "int" => "0" - case "long" => "0L" - case "float" => "0f" - case "double" => "0.0" - case e: String if (Set("List").contains(e)) => { - val inner = - obj.items.map(i => i.ref.getOrElse(i.`type`)).getOrElse({ - println("failed on " + dataType + ", " + obj) - throw new Exception("no inner type defined") - }) - "List.empty[" + toDeclaredType(inner) + "]" - } - case _ => "_" - } - } -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/model/AuthorizationModels.scala b/src/main/scala/com/wordnik/swagger/codegen/model/AuthorizationModels.scala deleted file mode 100644 index 9cc369d82391..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/model/AuthorizationModels.scala +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.model - -trait AuthorizationType { - def `type`: String -} -case class OAuth( - scopes: List[String], - grantTypes: List[GrantType]) extends AuthorizationType { - override def `type` = "oauth2" -} -case class ApiKey(keyname: String, passAs: String = "header") extends AuthorizationType { - override def `type` = "apiKey" -} - -trait GrantType { - def `type`: String -} -case class ImplicitGrant( - loginEndpoint: LoginEndpoint, - tokenName: String) extends GrantType { - def `type` = "implicit" -} -case class AuthorizationCodeGrant( - tokenRequestEndpoint: TokenRequestEndpoint, - tokenEndpoint: TokenEndpoint) extends GrantType { - def `type` = "authorization_code" -} - -trait AuthorizationValue -case class ApiKeyValue(keyName: String, passAs: String, value: String) extends AuthorizationValue - diff --git a/src/main/scala/com/wordnik/swagger/codegen/model/ClientOpts.scala b/src/main/scala/com/wordnik/swagger/codegen/model/ClientOpts.scala deleted file mode 100644 index e95cd6ad1ba3..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/model/ClientOpts.scala +++ /dev/null @@ -1,23 +0,0 @@ -package com.wordnik.swagger.codegen.model - -import scala.beans.BeanProperty -import scala.collection.JavaConverters._ - -class ClientOpts( - @BeanProperty var uri: String, - @BeanProperty var auth: Option[ApiKeyValue], - @BeanProperty var properties: java.util.Map[String, String]) { - def this() = this(null, None, new java.util.HashMap[String, String]()) - - @BeanProperty var outputDirectory: String = _ - - override def toString() = { - val sb = new StringBuilder() - sb.append("ClientOpts: {\n") - sb.append(" uri: ").append(uri).append(",") - sb.append(" auth: ").append(auth).append(",") - sb.append(properties.asScala.mkString(" ", ",", "\n")) - sb.append("}") - sb.toString - } -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/model/LegacySerializers.scala b/src/main/scala/com/wordnik/swagger/codegen/model/LegacySerializers.scala deleted file mode 100644 index fc3127b73bee..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/model/LegacySerializers.scala +++ /dev/null @@ -1,351 +0,0 @@ -package com.wordnik.swagger.codegen.model.legacy - -import com.wordnik.swagger.codegen.model._ -import com.wordnik.swagger.codegen.spec.ValidationMessage - -import org.json4s._ -import org.json4s.JsonDSL._ -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.{read, write} - -import scala.collection.mutable.{ListBuffer, LinkedHashMap} - -object LegacySerializers { - import ValidationMessage._ - - val formats = DefaultFormats + - new ModelSerializer + - new ModelPropertySerializer + - new ModelRefSerializer + - new AllowableValuesSerializer + - new ParameterSerializer + - new OperationSerializer + - new ResponseMessageSerializer + - new ApiDescriptionSerializer + - new ApiListingReferenceSerializer + - new ResourceListingSerializer + - new ApiListingSerializer - - class ApiListingSerializer extends CustomSerializer[ApiListing](formats => ({ - case json => - implicit val fmts: Formats = formats - ApiListing( - (json \ "apiVersion").extractOrElse(""), - (json \ "swaggerVersion").extractOrElse(""), - (json \ "basePath").extractOrElse(""), - (json \ "resourcePath").extractOrElse(""), - List.empty, - List.empty, - List.empty, - List.empty, - (json \ "apis").extract[List[ApiDescription]], - (json \ "models").extractOpt[Map[String, Model]], - (json \ "description").extractOpt[String], - 0 - ) - }, { - case x: ApiListing => - implicit val fmts = formats - ("apiVersion" -> x.apiVersion) ~ - ("swaggerVersion" -> x.swaggerVersion) ~ - ("basePath" -> x.basePath) ~ - ("apis" -> { - x.apis match { - case e: List[ApiDescription] if (e.size > 0) => Extraction.decompose(e) - case _ => JNothing - } - }) ~ - ("models" -> { - x.models match { - case e: Map[String, Model] if (e.size > 0) => Extraction.decompose(e) - case _ => JNothing - } - }) - } - )) - - class ResourceListingSerializer extends CustomSerializer[ResourceListing](formats => ({ - case json => - implicit val fmts: Formats = formats - ResourceListing( - (json \ "apiVersion").extractOrElse(""), - (json \ "swaggerVersion").extractOrElse(""), - (json \ "basePath").extractOrElse(""), - (json \ "apis").extract[List[ApiListingReference]] - ) - }, { - case x: ResourceListing => - implicit val fmts = formats - ("apiVersion" -> x.apiVersion) ~ - ("swaggerVersion" -> x.swaggerVersion) ~ - ("basePath" -> x.basePath) ~ - ("apis" -> { - x.apis match { - case e: List[ApiListingReference] if (e.size > 0) => Extraction.decompose(e) - case _ => JNothing - } - }) - } - )) - - class ApiListingReferenceSerializer extends CustomSerializer[ApiListingReference](formats => ({ - case json => - implicit val fmts: Formats = formats - ApiListingReference( - (json \ "path").extractOrElse(""), - (json \ "description").extractOpt[String] - ) - }, { - case x: ApiListingReference => - implicit val fmts = formats - ("path" -> x.path) ~ - ("description" -> x.description) - } - )) - - class ApiDescriptionSerializer extends CustomSerializer[ApiDescription](formats => ({ - case json => - implicit val fmts: Formats = formats - ApiDescription( - (json \ "path").extractOrElse(""), - (json \ "description").extractOpt[String], - (json \ "operations").extract[List[Operation]] - ) - }, { - case x: ApiDescription => - implicit val fmts = formats - ("path" -> x.path) ~ - ("description" -> x.description) ~ - ("operations" -> { - x.operations match { - case e:List[Operation] if(e.size > 0) => Extraction.decompose(e) - case _ => JNothing - } - }) - } - )) - - class ResponseMessageSerializer extends CustomSerializer[ResponseMessage](formats => ({ - case json => - implicit val fmts: Formats = formats - ResponseMessage( - (json \ "code").extractOrElse(0), - (json \ "reason").extractOrElse("") - ) - }, { - case x: ResponseMessage => - implicit val fmts = formats - ("code" -> x.code) ~ - ("message" -> x.message) - } - )) - - class OperationSerializer extends CustomSerializer[Operation](formats => ({ - case json => - implicit val fmts: Formats = formats - val authorizations = (json \ "authorizations").extractOpt[Map[String, AuthorizationType]] match { - case Some(m) => m.values.toList - case _ => List.empty - } - Operation( - (json \ "httpMethod").extractOrElse( - (json \ "method").extractOrElse("") - ), - (json \ "summary").extract[String], - (json \ "notes").extractOrElse(""), - (json \ "responseClass").extractOrElse(""), - (json \ "nickname").extractOrElse(""), - (json \ "position").extractOrElse(0), - (json \ "produces").extract[List[String]], - (json \ "consumes").extract[List[String]], - (json \ "protocols").extract[List[String]], - authorizations, - (json \ "parameters").extract[List[Parameter]], - (json \ "errorResponses").extract[List[ResponseMessage]], - (json \ "deprecated").extractOpt[String] - ) - }, { - case x: Operation => - implicit val fmts = formats - ("method" -> x.method) ~ - ("summary" -> x.summary) ~ - ("notes" -> x.notes) ~ - ("responseClass" -> x.responseClass) ~ - ("nickname" -> x.nickname) ~ - ("parameters" -> Extraction.decompose(x.parameters)) ~ - ("responseMessages" -> { - x.responseMessages match { - case e: List[ResponseMessage] if(e.size > 0) => Extraction.decompose(e) - case _ => JNothing - } - }) ~ - ("deprecated" -> x.`deprecated`) - } - )) - - class ParameterSerializer extends CustomSerializer[Parameter](formats => ({ - case json => - implicit val fmts: Formats = formats - Parameter( - (json \ "name").extractOrElse(""), - (json \ "description").extractOpt[String], - (json \ "defaultValue") match { - case e:JInt => Some(e.num.toString) - case e:JBool => Some(e.value.toString) - case e:JString => Some(e.s) - case e:JDouble => Some(e.num.toString) - case _ => None - }, - (json \ "required") match { - case e:JString => e.s.toBoolean - case e:JBool => e.value - case _ => false - }, - (json \ "allowMultiple").extractOrElse(false), - (json \ "dataType").extractOrElse(""), - (json \ "allowableValues").extract[AllowableValues], - (json \ "paramType").extractOrElse("") - ) - }, { - case x: Parameter => - implicit val fmts = formats - ("name" -> x.name) ~ - ("description" -> x.description) ~ - ("defaultValue" -> x.defaultValue) ~ - ("required" -> x.required) ~ - ("allowMultiple" -> x.allowMultiple) ~ - ("dataType" -> x.dataType) ~ - ("allowableValues" -> { - x.allowableValues match { - case AnyAllowableValues => JNothing // don't serialize when not a concrete type - case e:AllowableValues => Extraction.decompose(x.allowableValues) - case _ => JNothing - } - }) ~ - ("paramType" -> x.paramType) - } - )) - - class ModelSerializer extends CustomSerializer[Model](formats => ({ - case json => - implicit val fmts: Formats = formats - val output = new LinkedHashMap[String, ModelProperty] - val properties = (json \ "properties") match { - case JObject(entries) => { - entries.map({ - case (key, value) => output += key -> value.extract[ModelProperty] - }) - } - case _ => - } - - Model( - (json \ "id").extractOrElse(""), - (json \ "name").extractOrElse(""), - (json \ "id").extractOrElse(""), - output, - (json \ "description").extractOpt[String] - ) - }, { - case x: Model => - implicit val fmts = formats - ("id" -> x.id) ~ - ("name" -> x.name) ~ - ("properties" -> { - x.properties match { - case e: LinkedHashMap[String, ModelProperty] => Extraction.decompose(e.toMap) - case _ => JNothing - } - }) - } - )) - - class ModelPropertySerializer extends CustomSerializer[ModelProperty] (formats => ({ - case json => - implicit val fmts: Formats = formats - - ModelProperty( - `type` = (json \ "type").extractOrElse(""), - `qualifiedType` = (json \ "type").extractOrElse(""), - required = (json \ "required") match { - case e:JString => e.s.toBoolean - case e:JBool => e.value - case _ => false - }, - description = (json \ "description").extractOpt[String], - allowableValues = (json \ "allowableValues").extract[AllowableValues], - items = { - (json \ "items").extractOpt[ModelRef] match { - case Some(e: ModelRef) if(e.`type` != null || e.ref != None) => Some(e) - case _ => None - } - } - ) - }, { - case x: ModelProperty => - implicit val fmts = formats - ("type" -> x.`type`) ~ - ("required" -> x.required) ~ - ("description" -> x.description) ~ - ("allowableValues" -> { - x.allowableValues match { - case AnyAllowableValues => JNothing // don't serialize when not a concrete type - case e:AllowableValues => Extraction.decompose(x.allowableValues) - case _ => JNothing - } - }) ~ - ("items" -> Extraction.decompose(x.items)) - } - )) - - class ModelRefSerializer extends CustomSerializer[ModelRef](formats => ({ - case json => - implicit val fmts: Formats = formats - ModelRef( - (json \ "type").extractOrElse(null: String), - (json \ "$ref").extractOpt[String] - ) - }, { - case x: ModelRef => - implicit val fmts = formats - ("type" -> { - x.`type` match { - case e:String => Some(e) - case _ => None - } - }) ~ - ("$ref" -> x.ref) - } - )) - - class AllowableValuesSerializer extends CustomSerializer[AllowableValues](formats => ({ - case json => - implicit val fmts: Formats = formats - json \ "valueType" match { - case JString(x) if x.equalsIgnoreCase("list") => { - val output = new ListBuffer[String] - val properties = (json \ "values") match { - case JArray(entries) => entries.map { - case e:JInt => output += e.num.toString - case e:JBool => output += e.value.toString - case e:JString => output += e.s - case e:JDouble => output += e.num.toString - case _ => - } - case _ => - } - AllowableListValues(output.toList) - } - case JString(x) if x.equalsIgnoreCase("range") => - AllowableRangeValues((json \ "min").extract[String], (json \ "max").extract[String]) - case _ => AnyAllowableValues - } - }, { - case AllowableListValues(values, "LIST") => - implicit val fmts = formats - ("valueType" -> "LIST") ~ ("values" -> Extraction.decompose(values)) - case AllowableRangeValues(min, max) => - ("valueType" -> "RANGE") ~ ("min" -> min) ~ ("max" -> max) - } - )) -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/model/SwaggerModelSerializer.scala b/src/main/scala/com/wordnik/swagger/codegen/model/SwaggerModelSerializer.scala deleted file mode 100644 index 8694bb49b9c2..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/model/SwaggerModelSerializer.scala +++ /dev/null @@ -1,634 +0,0 @@ -package com.wordnik.swagger.codegen.model - -import com.wordnik.swagger.codegen.spec.ValidationMessage -import com.wordnik.swagger.util.ValidationException - -import legacy.LegacySerializers - -import org.json4s._ -import org.json4s.JsonDSL._ -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.{read, write} - -import scala.collection.mutable.{ListBuffer, LinkedHashMap} - - - -object SwaggerSerializers { - import ValidationMessage._ - - val jsonSchemaTypeMap = Map( - // simple types - ("integer", "int32") -> "int", - ("integer", "int64") -> "long", - ("number", "float") -> "float", - ("number", "double") -> "double", - ("number", null) -> "BigDecimal", - ("string", "byte") -> "byte", - ("string", "date") -> "Date", - ("string", "date-time") -> "Date", - ("string", "uuid") -> "UUID", - - // containers - ("array", "") -> "Array", - ("set", "") -> "Set" - ) - - def toJsonSchema(name: String, `type`: String): JObject = { - `type` match { - case "int" => (name -> "integer") ~ ("format" -> "int32") - case "long" => (name -> "integer") ~ ("format" -> "int64") - case "float" => (name -> "number") ~ ("format" -> "float") - case "double" => (name -> "number") ~ ("format" -> "double") - case "string" => (name -> "string") ~ ("format" -> JNothing) - case "byte" => (name -> "string") ~ ("format" -> "byte") - case "boolean" => (name -> "boolean") ~ ("format" -> JNothing) - case "Date" => (name -> "string") ~ ("format" -> "date-time") - case "date" => (name -> "string") ~ ("format" -> "date") - case "date-time" => (name -> "string") ~ ("format" -> "date-time") - case "Array" => (name -> "array") - case _ => { - val ComplexTypeMatcher = "([a-zA-Z]*)\\[([a-zA-Z\\.\\-]*)\\].*".r - `type` match { - case ComplexTypeMatcher(container, value) => - toJsonSchemaContainer(container) ~ { - ("items" -> {if(isSimpleType(value)) - toJsonSchema("type", value) - else - toJsonSchema("$ref", value)}) - } - case _ => (name -> `type`) ~ ("format" -> JNothing) - } - } - } - } - - def toJsonSchemaContainer(name: String): JObject = { - name match { - case "List" => ("type" -> "array") ~ ("format" -> JNothing) - case "Array" => ("type" -> "array") ~ ("format" -> JNothing) - case "Set" => ("type" -> "array") ~ ("uniqueItems" -> true) - case _ => ("type" -> JNothing) - } - } - - def isSimpleType(name: String) = { - Set("int", "long", "float", "double", "string", "byte", "boolean", "Date", "date", "date-time", "array", "set").contains(name) - } - - def formats(version: String) = { - version match { - case "1.1" => LegacySerializers.formats - case "1.2" => { - DefaultFormats + - new ModelSerializer + - new ModelPropertySerializer + - new ModelRefSerializer + - new AllowableValuesSerializer + - new ParameterSerializer + - new OperationSerializer + - new ResponseMessageSerializer + - new ApiDescriptionSerializer + - new ApiListingReferenceSerializer + - new ResourceListingSerializer + - new ApiListingSerializer - } - case _ => { - val error = ValidationError("ResourceListing", "swaggerVersion", SwaggerValidator.ERROR) - throw new ValidationException(400, "'%s' is not a valid Swagger version".format(version), List(error)) - } - } - } - - class ApiListingSerializer extends CustomSerializer[ApiListing](implicit formats => ({ - case json => - val authorizations = (json \ "authorizations").extractOpt[Map[String, AuthorizationType]] match { - case Some(m) => m.values.toList - case _ => List.empty - } - - val swaggerVersion = (json \ "swaggerVersion") match { - case e: JInt => e.num.toString - case e: JBool => e.value.toString - case e: JString => e.s - case e: JDouble => e.num.toString - case _ => "" - } - - ApiListing( - (json \ "apiVersion").extractOrElse(""), - swaggerVersion, - (json \ "basePath").extractOrElse(""), - (json \ "resourcePath").extractOrElse(""), - (json \ "produces").extract[List[String]], - (json \ "consumes").extract[List[String]], - (json \ "protocols").extract[List[String]], - authorizations, - (json \ "apis").extract[List[ApiDescription]], - (json \ "models").extractOpt[Map[String, Model]], - (json \ "description").extractOpt[String], - (json \ "position").extractOrElse(0) - ) - }, { - case x: ApiListing => - ("apiVersion" -> x.apiVersion) ~ - ("resourcePath" -> x.resourcePath) ~ - ("swaggerVersion" -> x.swaggerVersion) ~ - ("basePath" -> x.basePath) ~ - ("apis" -> { - x.apis match { - case e: List[ApiDescription] if (e.size > 0) => Extraction.decompose(e) - case _ => JNothing - } - }) ~ - ("models" -> { - x.models match { - case Some(e) if (e.size > 0) => Extraction.decompose(e) - case _ => JNothing - } - }) - } - )) - - class ResourceListingSerializer extends CustomSerializer[ResourceListing](implicit formats => ({ - case json => - - val apis = (json \ "apis").extract[List[ApiListingReference]] - - val swaggerVersion = (json \ "swaggerVersion") match { - case e: JInt => e.num.toString - case e: JBool => e.value.toString - case e: JString => e.s - case e: JDouble => e.num.toString - case _ => "" - } - - ResourceListing( - (json \ "apiVersion").extractOrElse(""), - swaggerVersion, - "", - apis.filter(a => a.path != "" && a.path != null) - ) - }, { - case x: ResourceListing => - ("apiVersion" -> x.apiVersion) ~ - ("swaggerVersion" -> x.swaggerVersion) ~ - ("apis" -> { - x.apis match { - case e: List[ApiListingReference] if (e.size > 0) => Extraction.decompose(e) - case _ => JNothing - } - }) - } - )) - - class ApiListingReferenceSerializer extends CustomSerializer[ApiListingReference](implicit formats => ({ - case json => - val path = (json \ "path").extractOrElse({ - (json \ "resourcePath").extractOrElse("") - }) - - ApiListingReference( - path, - (json \ "description").extractOpt[String] - ) - }, { - case x: ApiListingReference => - ("path" -> x.path) ~ - ("description" -> x.description) - } - )) - - class ApiDescriptionSerializer extends CustomSerializer[ApiDescription](implicit formats => ({ - case json => - - ApiDescription( - (json \ "path").extractOrElse(""), - (json \ "description").extractOpt[String], - (json \ "operations").extract[List[Operation]] - ) - }, { - case x: ApiDescription => - ("path" -> x.path) ~ - ("description" -> x.description) ~ - ("operations" -> { - x.operations match { - case e:List[Operation] if(e.size > 0) => Extraction.decompose(e) - case _ => JNothing - } - }) - } - )) - - class ResponseMessageSerializer extends CustomSerializer[ResponseMessage](implicit formats => ({ - case json => - val responseClass = (json \ "responseModel") match { - case e: JObject => { - val inner = { - (e \ "items" \"type").extractOrElse({ - (e \ "items" \ "$ref").extract[String] - }) - } - Option("%s[%s]".format((e \ "type").extract[String], inner)) - } - case _ => (json \ "responseModel").extractOpt[String] - } - - ResponseMessage( - (json \ "code").extractOrElse(0), - (json \ "message").extractOrElse(""), - (json \ "responseModel").extractOpt[String] - ) - }, { - case x: ResponseMessage => - ("code" -> x.code) ~ - ("message" -> x.message) ~ - ("responseModel" -> x.responseModel) - } - )) - - class OperationSerializer extends CustomSerializer[Operation](implicit formats => ({ - case json => - - val authorizations = (json \ "authorizations").extractOpt[Map[String, AuthorizationType]] match { - case Some(m) => m.values.toList - case _ => List.empty - } - val t = SwaggerSerializers.jsonSchemaTypeMap.getOrElse( - ((json \ "type").extractOrElse(""), (json \ "format").extractOrElse("")) - , (json \ "type").extractOrElse("")) - - val inner = { - val items = new scala.collection.mutable.HashSet[String] - val map = new scala.collection.mutable.HashMap[String, String] - (json \ "items") match { - case JObject(e) => { - for(a <- e) { - a._2 match { - case e: JString => map += a._1 -> e.s - case _ => - } - } - val `type` = map.getOrElse("type", "") - val format = map.getOrElse("format", "") - if(map.contains("$ref")) { - Some(map("$ref")) - } - else - Option(jsonSchemaTypeMap.getOrElse((`type`,format), `type`)) - } - case _ => None - } - } - val responseClass = inner match { - case Some(a) => "%s[%s]".format(t, a) - case _ => t - } - - Operation( - (json \ "httpMethod").extractOrElse( - (json \ "method").extractOrElse("") - ), - (json \ "summary").extract[String], - (json \ "notes").extractOrElse(""), - responseClass, - (json \ "nickname").extractOrElse(""), - (json \ "position").extractOrElse(0), - (json \ "produces").extract[List[String]], - (json \ "consumes").extract[List[String]], - (json \ "protocols").extract[List[String]], - authorizations, - (json \ "parameters").extract[List[Parameter]], - (json \ "responseMessages").extract[List[ResponseMessage]], - (json \ "deprecated").extractOpt[String] - ) - }, { - case x: Operation => - - val ComplexTypeMatcher = "([a-zA-Z]*)\\[([a-zA-Z\\.\\-]*)\\].*".r - val output = x.responseClass match { - case ComplexTypeMatcher(container, value) => - toJsonSchemaContainer(container) ~ { - ("items" -> {if(isSimpleType(value)) - toJsonSchema("type", value) - else - toJsonSchema("$ref", value)}) - } - case _ => toJsonSchema("type", x.responseClass) ~ ("format" -> JNothing) - } - - ("method" -> x.method) ~ - ("summary" -> x.summary) ~ - ("notes" -> x.notes) ~ - output ~ - ("nickname" -> x.nickname) ~ - ("parameters" -> Extraction.decompose(x.parameters)) ~ - ("responseMessages" -> { - x.responseMessages match { - case e: List[ResponseMessage] if(e.size > 0) => Extraction.decompose(e) - case _ => JNothing - } - }) ~ - ("deprecated" -> x.`deprecated`) - } - )) - - class ParameterSerializer extends CustomSerializer[Parameter](formats => ({ - case json => - implicit val fmts: Formats = formats - - val output = new ListBuffer[String] - (json \ "enum") match { - case JArray(entries) => entries.map { - case e: JInt => output += e.num.toString - case e: JBool => output += e.value.toString - case e: JString => output += e.s - case e: JDouble => output += e.num.toString - case _ => - } - case _ => - } - val allowableValues = { - if(output.size > 0) AllowableListValues(output.toList) - else { - val min = (json \ "min") match { - case e: JObject => e.extract[String] - case e: JString => e.s - case e: JInt => e.num.toString - case e: JDouble => e.num.toString - case _ => "" - } - val max = (json \ "max") match { - case e: JObject => e.extract[String] - case e: JString => e.s - case e: JInt => e.num.toString - case e: JDouble => e.num.toString - case _ => "" - } - if(min != "" && max != "") - AllowableRangeValues(min, max) - else - AnyAllowableValues - } - } - - val t = SwaggerSerializers.jsonSchemaTypeMap.getOrElse( - ((json \ "type").extractOrElse(""), (json \ "format").extractOrElse("")) - , (json \ "type").extractOrElse("")) - - val inner = { - val items = new scala.collection.mutable.HashSet[String] - val map = new scala.collection.mutable.HashMap[String, String] - (json \ "items") match { - case JObject(e) => { - for(a <- e) { - a._2 match { - case e: JString => map += a._1 -> e.s - case _ => - } - } - val `type` = map.getOrElse("type", "") - val format = map.getOrElse("format", "") - if(map.contains("$ref")) { - Some(map("$ref")) - } - else - Option(jsonSchemaTypeMap.getOrElse((`type`,format), `type`)) - } - case _ => None - } - } - val `type` = inner match { - case Some(a) => "%s[%s]".format(t, a) - case _ => t - } - Parameter( - name = (json \ "name").extractOrElse(""), - description = (json \ "description").extractOpt[String], - defaultValue = (json \ "defaultValue") match { - case e:JInt => Some(e.num.toString) - case e:JBool => Some(e.value.toString) - case e:JString => Some(e.s) - case e:JDouble => Some(e.num.toString) - case _ => None - }, - required = (json \ "required") match { - case e:JString => e.s.toBoolean - case e:JBool => e.value - case _ => false - }, - allowMultiple = (json \ "allowMultiple").extractOrElse(false), - dataType = `type`, - allowableValues = allowableValues, - paramType = (json \ "paramType").extractOrElse("") - ) - }, { - case x: Parameter => - implicit val fmts = formats - val output = ("name" -> x.name) ~ - ("description" -> x.description) ~ - ("defaultValue" -> x.defaultValue) ~ - ("required" -> x.required) ~ - ("allowMultiple" -> x.allowMultiple) ~ - toJsonSchema("type", x.dataType) ~ - ("paramType" -> x.paramType) - - x.allowableValues match { - case AllowableListValues(values, "LIST") => - output ~ ("enum" -> Extraction.decompose(values)) - case AllowableRangeValues(min, max) => - output ~ ("minimum" -> min) ~ ("maximum" -> max) - case _ => output - } - } - )) - - class ModelSerializer extends CustomSerializer[Model](implicit formats => ({ - case json => - val output = new LinkedHashMap[String, ModelProperty] - val required = (json \ "required").extract[Set[String]] - json \ "properties" match { - case JObject(entries) => { - entries.map({ - case (key, value) => { - val prop = value.extract[ModelProperty] - if(required.contains(key)) - output += key -> prop.copy(required = true) - else - output += key -> prop - } - }) - } - case _ => - } - - Model( - (json \ "id").extractOrElse(""), - (json \ "name").extractOrElse(""), - (json \ "qualifiedType").extractOrElse((json \ "id").extractOrElse("")), - output, - (json \ "description").extractOpt[String] - ) - }, { - case x: Model => - val required: List[String] = (for((name, prop) <- x.properties) yield { - if(prop.required) Some(name) - else None - }).flatten.toList - - ("id" -> x.id) ~ - ("name" -> x.name) ~ - ("required" -> (required.size match { - case 0 => JNothing - case _ => Extraction.decompose(required) - })) ~ - ("properties" -> { - (x.properties: @unchecked) match { - case e: LinkedHashMap[String, ModelProperty] => Extraction.decompose(e.toMap) - case _ => JNothing - } - }) - } - )) - - class ModelPropertySerializer extends CustomSerializer[ModelProperty] (implicit formats => ({ - case json => - val `type` = (json \ "$ref") match { - case e: JString => e.s - case _ => { - // convert the jsonschema types into swagger types. Note, this logic will move elsewhere soon - val t = SwaggerSerializers.jsonSchemaTypeMap.getOrElse( - ((json \ "type").extractOrElse(""), (json \ "format").extractOrElse("")) - , (json \ "type").extractOrElse("")) - val isUnique = (json \ "uniqueItems") match { - case e: JBool => e.value - case e: JString => e.s.toBoolean - case _ => false - } - if(t == "Array" && isUnique) "Set" - else t - } - } - - val output = new ListBuffer[String] - json \ "enum" match { - case JArray(entries) => entries.map { - case e: JInt => output += e.num.toString - case e: JBool => output += e.value.toString - case e: JString => output += e.s - case e: JDouble => output += e.num.toString - case _ => - } - case _ => - } - val allowableValues = { - if(output.size > 0) AllowableListValues(output.toList) - else { - val min = (json \ "min") match { - case e: JObject => e.extract[String] - case _ => "" - } - val max = (json \ "max") match { - case e: JObject => e.extract[String] - case _ => "" - } - if(min != "" && max != "") - AllowableRangeValues(min, max) - else - AnyAllowableValues - } - } - ModelProperty( - `type` = `type`, - `qualifiedType` = (json \ "qualifiedType").extractOpt[String].getOrElse(`type`), - required = (json \ "required") match { - case e:JString => e.s.toBoolean - case e:JBool => e.value - case _ => false - }, - description = (json \ "description").extractOpt[String], - allowableValues = allowableValues, - items = { - (json \ "items").extractOpt[ModelRef] match { - case Some(e: ModelRef) if(e.`type` != null || e.ref != None) => Some(e) - case _ => None - } - } - ) - }, { - case x: ModelProperty => - val output = toJsonSchema("type", x.`type`) ~ - ("description" -> x.description) ~ - ("items" -> Extraction.decompose(x.items)) - - x.allowableValues match { - case AllowableListValues(values, "LIST") => - output ~ ("enum" -> Extraction.decompose(values)) - case AllowableRangeValues(min, max) => - output ~ ("minimum" -> min) ~ ("maximum" -> max) - case _ => output - } - } - )) - - class ModelRefSerializer extends CustomSerializer[ModelRef](implicit formats => ({ - case json => - - val `type` = (json \ "type") match { - case e: JString => e.s - case _ => "" - } - val format = (json \ "format") match { - case e: JString => e.s - case _ => "" - } - val jsonSchemaType = jsonSchemaTypeMap.getOrElse((`type`, format), `type`) - - ModelRef( - jsonSchemaType match { - case e: String if(e != "") => e - case _ => null - }, - (json \ "$ref").extractOpt[String] - ) - }, { - case x: ModelRef => - ("type" -> { - x.`type` match { - case e:String => Some(e) - case _ => None - } - }) ~ - ("$ref" -> x.ref) - } - )) - - class AllowableValuesSerializer extends CustomSerializer[AllowableValues](implicit formats => ({ - case json => - json \ "valueType" match { - case JString(x) if x.equalsIgnoreCase("list") => { - val output = new ListBuffer[String] - val properties = (json \ "values") match { - case JArray(entries) => entries.map { - case e:JInt => output += e.num.toString - case e:JBool => output += e.value.toString - case e:JString => output += e.s - case e:JDouble => output += e.num.toString - case _ => - } - case _ => - } - AllowableListValues(output.toList) - } - case JString(x) if x.equalsIgnoreCase("range") => - AllowableRangeValues((json \ "min").extract[String], (json \ "max").extract[String]) - case _ => AnyAllowableValues - } - }, { - case AllowableListValues(values, "LIST") => - ("valueType" -> "LIST") ~ ("values" -> Extraction.decompose(values)) - case AllowableRangeValues(min, max) => - ("valueType" -> "RANGE") ~ ("min" -> min) ~ ("max" -> max) - } - )) -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/model/SwaggerModels.scala b/src/main/scala/com/wordnik/swagger/codegen/model/SwaggerModels.scala deleted file mode 100644 index 420e2620a250..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/model/SwaggerModels.scala +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.model - -import scala.collection.mutable.LinkedHashMap - -case class ResourceListing( - apiVersion: String, - swaggerVersion: String, - basePath: String, - apis: List[ApiListingReference] = List(), - authorizations: List[AuthorizationType] = List(), - info: Option[ApiInfo] = None) - -case class ApiInfo( - title: String, - description: String, - termsOfServiceUrl: String, - contact: String, - license: String, - licenseUrl: String) - -case class LoginEndpoint(url: String) -case class TokenRequestEndpoint(url: String, clientIdName: String, clientSecretName: String) -case class TokenEndpoint(url: String, tokenName: String) - -case class ApiListingReference(path:String, description: Option[String], position: Int = 0) - -trait AllowableValues -case object AnyAllowableValues extends AllowableValues -case class AllowableListValues (values: List[String] = List(), valueType: String = "LIST") extends AllowableValues -case class AllowableRangeValues(min: String, max: String) extends AllowableValues - -case class Model( - var id: String, - var name: String, - qualifiedType: String, - var properties: LinkedHashMap[String, ModelProperty], - description: Option[String] = None, - baseModel: Option[String] = None, - discriminator: Option[String] = None) - -case class ModelProperty( - var `type`: String, - qualifiedType: String, - position: Int = 0, - required: Boolean = false, - description: Option[String] = None, - allowableValues: AllowableValues = AnyAllowableValues, - var items: Option[ModelRef] = None) - -case class ModelRef( - `type`: String, - ref: Option[String] = None, - qualifiedType: Option[String] = None) - -case class ApiListing ( - apiVersion: String, - swaggerVersion: String, - basePath: String, - var resourcePath: String, - var produces: List[String] = List.empty, - var consumes: List[String] = List.empty, - var protocols: List[String] = List.empty, - var authorizations: List[AuthorizationType] = List.empty, - apis: List[ApiDescription] = List(), - models: Option[Map[String, Model]] = None, - description: Option[String] = None, - position: Int = 0) - -case class ApiDescription ( - path: String, - description: Option[String], - operations: List[Operation] = List()) - -case class Operation ( - method: String, - summary: String, - notes: String, - var responseClass: String, - nickname: String, - position: Int, - var produces: List[String] = List.empty, - var consumes: List[String] = List.empty, - var protocols: List[String] = List.empty, - var authorizations: List[AuthorizationType] = List.empty, - parameters: List[Parameter] = List.empty, - responseMessages: List[ResponseMessage] = List.empty, - `deprecated`: Option[String] = None) - -case class Parameter ( - name: String, - description: Option[String], - defaultValue: Option[String], - required: Boolean, - allowMultiple: Boolean, - var dataType: String, - allowableValues: AllowableValues = AnyAllowableValues, - paramType: String, - paramAccess: Option[String] = None) - -case class ResponseMessage ( - code: Int, - message: String, - responseModel: Option[String] = None) diff --git a/src/main/scala/com/wordnik/swagger/codegen/model/SwaggerValidator.scala b/src/main/scala/com/wordnik/swagger/codegen/model/SwaggerValidator.scala deleted file mode 100644 index be0e636d9d96..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/model/SwaggerValidator.scala +++ /dev/null @@ -1,103 +0,0 @@ -package com.wordnik.swagger.codegen.model - -import scala.collection.mutable.ListBuffer - -case class ValidationError ( - path: String, - message: String, - severity: String -) - -object SwaggerValidator { - val ERROR = "ERROR" - val WARNING = "WARNING" - - def validate (resource: ResourceListing): List[ValidationError] = { - val errors = new ListBuffer[ValidationError] - - if(resource.apiVersion == "") - errors += ValidationError("resourceListing", "apiVersion is required", ERROR) - if(resource.swaggerVersion == "") - errors += ValidationError("resourceListing", "apiVersion is required", ERROR) - for(api <- resource.apis) - validate(api, errors, "resourceListing") - errors.toList - } - - def validate(ref: ApiListingReference, errors: ListBuffer[ValidationError], parent: String): Unit = { - if(ref.path == "") - errors += ValidationError(parent + ":[api]", "path is required", ERROR) - } - - def validate(api: ApiListing, errors: ListBuffer[ValidationError]): Unit = { - if(api.swaggerVersion == "") - errors += ValidationError("apiDeclaration", "swaggerVersion is required", ERROR) - if(api.apiVersion == "") - errors += ValidationError("apiDeclaration", "apiVersion is required", ERROR) - if(api.basePath == "") - errors += ValidationError("apiDeclaration", "basePath is required", ERROR) - if(api.resourcePath == "") - errors += ValidationError("apiDeclaration", "resourcePath is required", ERROR) - - val name = { - if(api.resourcePath == "") "[unknown]" - else api.resourcePath - } - for(a <- api.apis) { - validate(a, errors, name) - } - - api.models match { - case Some(m) => for((name, model) <- m) { - validate(model, errors, name) - } - case None => - } - } - - def validate(model: Model, errors: ListBuffer[ValidationError], parent: String): Unit = { - if(model.id == "") - errors += ValidationError(parent + ":[model]", "id is required", ERROR) - } - - def validate(desc: ApiDescription, errors: ListBuffer[ValidationError], parent: String): Unit = { - if(desc.path == "") - errors += ValidationError(parent + ":[api]", "path is required", ERROR) - for(op <- desc.operations) - validate(op, errors, parent + ":" + desc.path) - } - - def validate(op: Operation, errors: ListBuffer[ValidationError], parent: String): Unit = { - if(op.method == "") - errors += ValidationError(parent + ":[operation]", "method is required", ERROR) - if(op.nickname == "") - errors += ValidationError(parent + ":" + op.method, "nickname is recommended", WARNING) - if(op.responseClass == "") - errors += ValidationError(parent + ":" + op.method, "responseClass is required", ERROR) - for(resp <- op.responseMessages) - validate(resp, errors, parent) - for(param <- op.parameters) - validate(param, errors, parent) - } - - def validate(param: Parameter, errors: ListBuffer[ValidationError], parent: String): Unit = { - val name = if(param.name == "") - "[unknown]" - else - param.name - - if(param.name == "") - errors += ValidationError(parent + ":[parameter]", "name is required", ERROR) - if(param.paramType == "") - errors += ValidationError(parent + name, "paramType is required", ERROR) - if(param.dataType == "") - errors += ValidationError(parent + name, "type is required", ERROR) - } - - def validate(resp: ResponseMessage, errors: ListBuffer[ValidationError], parent: String): Unit = { - if(resp.code == 0) - errors += ValidationError(parent + ":[responseMessage]", "code is required", ERROR) - if(resp.message == 0) - errors += ValidationError(parent + ":[responseMessage]", "message is required", ERROR) - } -} \ No newline at end of file diff --git a/src/main/scala/com/wordnik/swagger/codegen/spec/SwaggerSpecValidator.scala b/src/main/scala/com/wordnik/swagger/codegen/spec/SwaggerSpecValidator.scala deleted file mode 100644 index a0a746284b0a..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/spec/SwaggerSpecValidator.scala +++ /dev/null @@ -1,446 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.spec - -import com.wordnik.swagger.codegen.model._ -import com.wordnik.swagger.codegen.PathUtil -import com.wordnik.swagger.codegen.spec.SwaggerSpec._ -import com.wordnik.swagger.codegen.util.CoreUtils - -import java.util.logging.Logger -import String.format - -import scala.collection.mutable.ListBuffer -import scala.collection.JavaConversions._ - -import org.fusesource.scalate.{ TemplateSource, TemplateEngine } -import java.io.{ FileWriter, File } -import scala.io.Source -import scala.collection.mutable.HashSet -import scala.collection.immutable.HashMap - -class SwaggerSpecValidator(private val doc: ResourceListing, - private val apis: List[ApiListing], - private val fix: Boolean = true) extends PathUtil { - - import ValidationMessage._ - - private val validationMessages = ListBuffer.empty[ValidationMessage] - - private val LOGGER = Logger.getLogger(classOf[SwaggerSpecValidator].getName) - - def validate() { - checkRootProperties() - - apis.foreach(api => { - fixSubDoc(api) - - api.models match { - case Some(models) => { - fixReturnModels(models.toMap, apis) - fixInputDataTypes(models.toMap, apis) - fixModels(models.toMap) - } - case None => LOGGER.warning("No models found for listing: " + api.resourcePath) - } - }) - - validateResponseModels(apis) - println("----------") - println(this) - } - - def validateResponseModels(subDocs: List[ApiListing]) = { - val validModelNames = CoreUtils.extractAllModels(subDocs).map(m => m._1).toSet - val requiredModels = new HashSet[String] - subDocs.foreach(subDoc => { - if (subDoc.apis != null) { - subDoc.apis.foreach(api => { - api.operations.foreach(op => { - requiredModels += { - val responseClass = op.responseClass - responseClass.indexOf("[") match { - case i: Int if (i > 0) => { - CoreUtils.extractBasePartFromType(responseClass) - } - case _ => responseClass - } - } - }) - }) - } - }) - val missingModels = requiredModels.toSet -- (validModelNames ++ primitives) - - if (missingModels.size > 0) println("missing models: " + missingModels) - } - - def generateReport(host: String, outputFilename: Option[String]) { - outputFilename match { - case Some(o) => { - val rootDir = new java.io.File(".") - val engine = new TemplateEngine(Some(rootDir)) - val templateLocation = "validator" + File.separator + "index.mustache" - val template = engine.compile( - TemplateSource.fromText(templateLocation, Source.fromInputStream(getClass.getClassLoader.getResourceAsStream(templateLocation)).mkString)) - val output = engine.layout(templateLocation, template, HashMap( - "messages" -> validationMessages, - "host" -> host, - "basePath" -> doc.basePath, - "swaggerVersion" -> doc.swaggerVersion, - "apiVersion" -> doc.apiVersion)) - val fw = new FileWriter(o, false) - fw.write(output + "\n") - fw.close() - println("wrote " + o) - - } - - case None => - println("Output file location not passed as program argument") - } - - } - - /** - * Checks the swagger.version, basePath and api.version which is - * expected to be present in root resource listing - * - */ - private def checkRootProperties() { - doc.swaggerVersion match { - case e: String => println("swagger version: " + e) - case _ => !!(doc, RESOURCE_LISTING, "Properties", "Missing swagger version") - } - doc.basePath match { - case e: String => println("basePath: " + e) - case _ => !!(doc, RESOURCE_LISTING, "Properties", "Missing base path") - } - doc.apiVersion match { - case e: String => println("api version: " + e) - case _ => !!(doc, RESOURCE_LISTING, "Properties", "Missing api version", WARNING) - } - } - - /** - * this is here because sub documents don't have the same resourcePath as declared in - * the main resource listing - */ - private def fixSubDoc(api: ApiListing) = { - if (api.resourcePath.indexOf(".{format}") == -1) { - doc.apis.foreach(op => { - if (op.path.indexOf(".{format}") > 0 && op.path.replaceAll(".\\{format\\}", "") == api.resourcePath) { - if (fix) { - api.resourcePath = api.resourcePath + ".{format}" - } - } - }) - } - } - - /** - * this is here because models don't have the proper references to types - */ - private def fixModels(models: Map[String, Model]) = { - val validModelNames = models.map(_._1).toSet - LOGGER.finest("all valid models: " + validModelNames) - for ((name, model) <- models) { - // id of model - getUpdatedType(validModelNames, model.id) match { - case Some(updatedType) => { - if (!model.id.equals(updatedType)) { - !!(model, MODEL, model.id, format("Invalid id. Best guess: %s", updatedType)) - LOGGER.finest("updated " + model.id + " to " + updatedType) - if (fix) model.id = updatedType - } - } - case None => { - LOGGER.finest("can't find type for " + model.name + ", type " + model.id) - !!(model, MODEL, model.name, format("Missing type (%s)", model.id)) - } - } - - model.properties.foreach(prop => { - val subObjectName = prop._1 - val subObject = prop._2 - - if (containers.contains(subObject.`type`)) { - // process the sub object - subObject.items match { - case Some(item) => { - getUpdatedType(validModelNames, item.ref.getOrElse(null)) match { - case Some(updatedType) => { - if (!item.ref.get.equals(updatedType)) { - !!(model, MODEL_PROPERTY, format("%s->%s: %s", model.id, subObjectName, subObject.`type`), format("Invalid ref (%s). Best guess: %s", item.ref, updatedType)) - LOGGER.finest("updated subObject.items.ref " + item.ref + " to " + updatedType) - if (fix) { - subObject.items = Some(ModelRef(null, Some(updatedType))) - } - } - } - case None => - } - } - case _ => - } - } else if (containers.contains(subObject.`type`)) { - // process the sub object - if (subObject.items != null && subObject.items != None && subObject.items.get.ref != null){ - subObject.items match { - case Some(item) => { - getUpdatedType(validModelNames, item.ref.getOrElse(null)) match { - case Some(updatedType) => { - if (!item.ref.equals(updatedType)) { - !!(model, MODEL_PROPERTY, format("%s->%s: %s", model.id, subObjectName, subObject.`type`), format("Invalid ref (%s). Best guess: %s", item.ref, updatedType)) - LOGGER.finest("updated subObject.items.ref " + item.ref + " to " + updatedType) - if (fix) subObject.items = Some(ModelRef(null, Some(updatedType))) - } - } - case None => { - !!(model, MODEL_PROPERTY, format("%s->%s: %s", model.id, subObjectName, subObject.`type`), format("Invalid ref (%s).", item.ref)) - LOGGER.finest("didn't know what to do with " + item.ref) - } - } - } - case _ => - } - } - else if (subObject.items != null && subObject.items != None && subObject.items.get.`type` != null) { - subObject.items match { - case Some(item) => { - getUpdatedType(validModelNames, item.`type`) match { - case Some(updatedType) => { - if (!item.`type`.equals(updatedType)) { - !!(model, MODEL_PROPERTY, format("%s->%s: %s", model.id, subObjectName, subObject.`type`), format("Invalid type (%s). Best guess: %s", item.`type`, updatedType)) - LOGGER.finest("updated subObject.items.type" + item.`type` + " to " + updatedType) - if (fix) subObject.items = Some(ModelRef(`type` = updatedType)) - } - } - case None => { - println("nothing found for " + subObject) - !!(model, MODEL_PROPERTY, format("%s->%s: %s", model.id, subObjectName, subObject.`type`), format("Invalid ref (%s).", item.ref)) - LOGGER.finest("didn't know what to do with " + item.ref) - } - } - } - case _ => - } - } - } else { - getUpdatedType(validModelNames, subObject.`type`) match { - case Some(updatedType) => { - if (!subObject.`type`.equals(updatedType)) { - !!(model, MODEL_PROPERTY, format("%s->%s: %s", model.id, subObjectName, subObject.`type`), format("Invalid type (%s). Best guess: %s", subObject.`type`, updatedType)) - LOGGER.finest("updated subObject.getType " + subObject.`type` + " to " + updatedType) - if (fix) subObject.`type` = updatedType - } - } - case None => - } - } - }) - // remove params with invalid names (Pos???) - model.properties = model.properties.filter(prop => { - if (prop._1.indexOf("$") == -1) true - else { - !!(model, MODEL, model.id, format("Invalid property %s. Removing it", prop._1)) - LOGGER.finest("removing invalid property " + prop._1) - if (fix) false else true - } - }) - } - } - - /** - * this is here because input params in operations don't match primitives or model names - */ - private def fixInputDataTypes(models: Map[String, Model], a: List[ApiListing]) = { - val validModelNames = models.map(m => m._1).toSet - - // List[ApiListing] - a.foreach(listing => { - if (listing.apis != null) { - listing.apis.foreach(api => { - // List[ApiDescription] - api.operations.foreach(op => { - // List[Operation] - val modelNames = new ListBuffer[String] - if(op.parameters != null) { - op.parameters.foreach(p => { - val dataType = p.dataType - - p.paramType match { - case "body" => { - getUpdatedType(validModelNames, dataType) match { - case Some(updatedName) => { - if (!p.dataType.equals(updatedName)) { - // LOGGER.finest("--> updated " + dataType + " to " + updatedName) - !!(p, OPERATION_PARAM, format("%s.%s(body: %s)", apiNameFromPath(api.path), op.nickname, p.dataType), format("Invalid data type %s. Best guess: %s", p.dataType, updatedName)) - if (fix) p.dataType = updatedName - } - } - case _ => LOGGER.finest("rats!") // leave it alone - } - } - case "path" => { - getUpdatedType(validModelNames, dataType) match { - case Some(updatedName) => { - // LOGGER.finest("--> updated " + dataType + " to " + updatedName) - !!(p, OPERATION_PARAM, format("%s.%s(path_%s: %s)", apiNameFromPath(api.path), op.nickname, p.name, p.dataType), format("Invalid data type %s. Best guess: %s", p.dataType, updatedName)) - if (fix) p.dataType = updatedName - } - case _ => // leave it alone - } - } - case "query" => { - getUpdatedType(validModelNames, dataType) match { - case Some(updatedName) => { - // LOGGER.finest("--> updated " + dataType + " to " + updatedName) - !!(p, OPERATION_PARAM, format("%s.%s(query_%s: %s)", apiNameFromPath(api.path), op.nickname, p.name, p.dataType), format("Invalid %s. Best guess: %s", p.dataType, updatedName)) - if (fix) p.dataType = updatedName - } - case _ => // leave it alone - } - } - case _ => - } - - }) - } - }) - }) - } - }) - } - - /** - * this is here because the return types are inconsistent from the swagger-core-1.02-SNAPSHOT - */ - private def fixReturnModels(models: Map[String, Model], a: List[ApiListing]) = { - val validModelNames = models.map(m => m._1).toSet - - // List[ApiListing] - a.foreach(listing => { - if (listing.apis != null) { - listing.apis.foreach(api => { - // List[ApiDescription] - api.operations.foreach(op => { - // List[Operation] - val responseClass = op.responseClass - if (responseClass != null) { - getUpdatedType(validModelNames, responseClass) match { - case Some(updatedName) => { - if (!responseClass.equals(updatedName)) { - LOGGER.finest("--> updated " + responseClass + " to " + updatedName) - !!(op, OPERATION, format("%s.%s(): %s", apiNameFromPath(api.path), op.nickname, op.responseClass), format("Invalid response class. Best guess: %s", updatedName)) - if (fix) op.responseClass = updatedName - } - } - case _ => { - } // leave it alone - } - } - }) - }) - } - }) - } - - private def getUpdatedType(validModelNames: Set[String], name: String): Option[String] = { - if(name == null) return None - - if (validModelNames.contains(name)) { - Some(name) - } else if (name.indexOf("[") > 0) { - // it's a complex value - val ComplexTypeMatcher = ".*\\[(.*)\\].*".r - val ComplexTypeMatcher(basePart) = name - - getUpdatedType(validModelNames, basePart) match { - case Some(updatedPart) => { - Some(name.replaceAll(java.util.regex.Pattern.quote(basePart), updatedPart)) - } - case _ => None - } - } else if (name.indexOf(".") > 0) { - val basePart = name.split("\\.").last - getUpdatedType(validModelNames, basePart) match { - case Some(updatedPart) => { - Some(updatedPart) - } - case _ => { - None - } - } - } else if (!primitives.contains(name)) { - val pc = name - if (validModelNames.contains(pc)) { - Some(pc) - } else if (pc == "Ok") { - Some("void") - } else if (pc == "Long") { - Some("long") - } else if (pc == "Double") { - Some("double") - } else if (pc == "Float") { - Some("float") - } else if (pc == "Boolean") { - Some("boolean") - } else if (pc == "Integer") { - Some("int") - } else if (pc == "Byte") { - Some("byte") - } else { - None - } - } else { - None - } - } - - def !!(element: AnyRef, elementType: String, elementId: String, message: String, level: String = ERROR) { - validationMessages += new ValidationMessage(element, elementType, elementId, message, level) - } - - override def toString = { - val out = new StringBuilder - for (v <- validationMessages) { - out.append(v) - out.append('\n') - } - - out.toString() - } -} - -class ValidationMessage(val element: AnyRef, val elementType: String, val elementId: String, val message: String, val level: String) { - override def toString = level + ": " + elementType + " - " + elementId + " | " + message -} - -object ValidationMessage { - val WARNING = "Warning" - val ERROR = "Error" - - val RESOURCE_LISTING = "Root Resources Listing" - val RESOURCE = "Resource" - val OPERATION = "Operation" - val OPERATION_PARAM = "Operation Parameter" - val MODEL = "Model" - val MODEL_PROPERTY = "Model Property" - - val validationMessages = ListBuffer.empty[ValidationMessage] -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/spec/Validator.scala b/src/main/scala/com/wordnik/swagger/codegen/spec/Validator.scala deleted file mode 100644 index 0bd79167b5dc..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/spec/Validator.scala +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.spec - -import com.wordnik.swagger.codegen.util.{CoreUtils, ApiExtractor, ResourceExtractor} -import com.wordnik.swagger.codegen.PathUtil -import com.wordnik.swagger.codegen.model._ - -import scala.collection.JavaConversions._ - -object Validator extends PathUtil { - def main(args: Array[String]) { - if(args.length == 0) { - throw new RuntimeException("Need url to Resource Listing as argument. You can also specify VM Argument -DfileMap=/path/to/resourceListing") - } - val host = args(0) - val fileMap = Option(sys.props("fileMap")) - - val authorization = { - Option (System.getProperty("header")) match { - case Some(e) => { - // this is ugly and will be replaced with proper arg parsing like in ScalaAsyncClientGenerator soon - val authInfo = e.split(":") - Some(ApiKeyValue(authInfo(0), "header", authInfo(1))) - } - case _ => { - if (args.length > 1) { - Some(ApiKeyValue("api_key", "query", args(1))) - } - else None - } - } - } - - val outputFilename = { - if (args.length > 2) Some(args(2)) - else None - } - val doc = { - try { - ResourceExtractor.fetchListing(getResourcePath(host, fileMap), authorization) - } catch { - case e: Exception => throw new Exception("unable to read from " + host, e) - } - } - - val basePath = getBasePath(host, doc.basePath, fileMap) - val apis = ApiExtractor.fetchApiListings(doc.swaggerVersion, basePath, doc.apis, authorization) - val swaggerSpecValidator = new SwaggerSpecValidator(doc, apis, false) - swaggerSpecValidator.validate() - swaggerSpecValidator.generateReport(host, outputFilename) - - System.exit(0) - } -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/util/ApiExtractor.scala b/src/main/scala/com/wordnik/swagger/codegen/util/ApiExtractor.scala deleted file mode 100644 index 51abd235453e..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/util/ApiExtractor.scala +++ /dev/null @@ -1,75 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.util - -import com.wordnik.swagger.codegen.model._ - -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.read - -import java.net.URL -import java.io.InputStream - -import scala.io._ -import scala.collection.mutable.{ ListBuffer, HashMap, HashSet } - -object ApiExtractor extends RemoteUrl { - def fetchApiListings(version: String, basePath: String, apis: List[ApiListingReference], authorization: Option[AuthorizationValue] = None): List[ApiListing] = { - implicit val formats = SwaggerSerializers.formats(version) - (for (api <- apis) yield { - try{ - val json = (basePath.startsWith("http")) match { - case true => { - val path = if(api.path.startsWith("http")) api.path - else basePath + api.path - urlToString(path.replaceAll(".\\{format\\}", ".json"), authorization) - } - case false => Source.fromFile((basePath + api.path).replaceAll(".\\{format\\}", ".json")).mkString - } - Some(parse(json).extract[ApiListing]) - } - catch { - case e: java.io.FileNotFoundException => { - println("WARNING! Unable to read API " + basePath + api.path) - None - } - case e: Throwable => { - println("WARNING! Unable to read API " + basePath + api.path) - e.printStackTrace() - None - } - } - }).flatten.toList - } - - def extractApiOperations(version: String, basePath: String, references: List[ApiListingReference], authorization: Option[AuthorizationValue] = None) = { - implicit val formats = SwaggerSerializers.formats(version) - for (api <- references) yield { - val json = basePath.startsWith("http") match { - case true => { - urlToString((basePath + api.path).replaceAll(".\\{format\\}", ".json"), authorization) - } - case false => Source.fromFile((basePath + api.path).replaceAll(".\\{format\\}", ".json")).mkString - } - parse(json).extract[ApiListing] - } - } - - def extractApiOperations(basePath: String, apiDescription: ApiDescription): List[(String, Operation)] = { - (for(op <- apiDescription.operations) yield (apiDescription.path, op)).toList - } -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/util/CoreUtils.scala b/src/main/scala/com/wordnik/swagger/codegen/util/CoreUtils.scala deleted file mode 100644 index 7a47d4b0a385..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/util/CoreUtils.scala +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.util - -import com.wordnik.swagger.codegen.model._ - -import scala.collection.mutable.{ HashSet, ListBuffer, HashMap } -import scala.collection.JavaConversions._ -import com.wordnik.swagger.codegen.spec.SwaggerSpec._ - -import scala.io.Source -import scala.collection.mutable -import scala.annotation.tailrec - -object CoreUtils { - def extractAllModels(apis: List[ApiListing], excludes: Set[String] = Set.empty, typeMapping: Map[String, String] = Map.empty): Map[String, Model] = { - apis.foldLeft(Map.empty[String, Model]) { (acc, api) => - acc ++ api.models.getOrElse(Map.empty[String, Model]) ++ extractApiModels(api, excludes, typeMapping) - } - } - - def extractModelNames(op: Operation): Set[String] = { -// // POST, PUT, DELETE body - val modelNames = Set(op.responseClass) ++ op.parameters.filter(_.paramType == "body").map(_.dataType) ++ op.responseMessages.filter(!_.responseModel.isEmpty).map(_.responseModel.get) - modelNames map extractBasePartFromType - } - - def extractBasePartFromType(datatype: String): String = { - val ComplexTypeMatcher = ".*\\[(.*)\\].*".r - datatype match { - case ComplexTypeMatcher(basePart) => basePart - case _ => datatype - } - } - - def extractApiModels(sd: ApiListing, excludes: Set[String] = Set.empty, typeMapping: Map[String, String] = Map.empty): Map[String, Model] = { - - def declNm(nm: String) = - typeMapping.foldLeft(nm)((n, kv) => ("\\b"+kv._1+"\\b").r.replaceAllIn(n, kv._2)) - val modelObjects = sd.models.map(_.foldLeft(Map.empty[String, Model])(_ + _)) getOrElse Map.empty - // return types - val modelNames = sd.apis.foldLeft(Set.empty[String]) { (acc, api) => - api.operations.foldLeft(acc){ _ ++ extractModelNames(_) } - } - - // extract all base model names, strip away Containers like List[] and primitives - val baseNames = (modelNames filterNot primitives.contains) map extractBasePartFromType - // get complex models from base - val requiredModels = modelObjects.filter(obj => baseNames.contains(obj._1)) - // look inside top-level models - val sn = subNames(requiredModels.toMap, modelObjects, Set.empty, typeMapping) - val subModels = modelObjects.filter(obj => sn.contains(obj._1)) - val ex = excludes ++ primitives - - for { - (k, v) <- requiredModels ++ subModels - if (!ex.contains(k)) - } yield k -> v.copy(properties = v.properties.map(kv => kv._1 -> kv._2.copy(`type` = declNm(kv._2.`type`)))) - } - - def subNames(requiredModels: Map[String, Model], allModels: Map[String, Model], acc: Set[String] = Set.empty, typeMapping: Map[String, String]): Set[String] = { - requiredModels.foldLeft(acc) { case (subNames, (_, m)) => - recurseModel(m.properties.toList, allModels, subNames + typeMapping.getOrElse(m.id, m.id), typeMapping) - } - } - - @tailrec def recurseModel(properties: List[(String, ModelProperty)], allModels: Map[String, Model], subNames: Set[String], typeMapping: Map[String, String]): Set[String] = { - properties match { - case Nil => - subNames - case (_, subObject) :: rest => - val nm = subObject.`type` - def declNm(nm: String) = - typeMapping.foldLeft(nm)((n, kv) => ("\\b"+kv._1+"\\b").r.replaceAllIn(n, kv._2)) - - val propertyName = if (containers.contains(nm)) { - subObject.items flatMap (si => Option(si.ref.getOrElse(si.`type`)).map(declNm)) orElse Option(declNm(nm)) - } else Option(declNm(nm)) - - if (propertyName.isDefined && !subNames.contains(propertyName.get)) { - val prop = propertyName.get - if (allModels.contains(prop)) { - val newSubnames = this.subNames(Map(prop -> allModels(prop)), allModels, subNames + prop, typeMapping) - recurseModel(rest, allModels, newSubnames, typeMapping) - } else { - val newSubnames = subNames + prop - recurseModel(rest, allModels, newSubnames, typeMapping) - } - } else recurseModel(rest, allModels, subNames, typeMapping) - } - } -} diff --git a/src/main/scala/com/wordnik/swagger/codegen/util/RemoteUrl.scala b/src/main/scala/com/wordnik/swagger/codegen/util/RemoteUrl.scala deleted file mode 100644 index e82752754920..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/util/RemoteUrl.scala +++ /dev/null @@ -1,46 +0,0 @@ -package com.wordnik.swagger.codegen.util - -import com.wordnik.swagger.codegen.model._ - -import java.net._ -import java.io.InputStream - -import scala.io.Source - -trait RemoteUrl { - def urlToString(url: String, authorization: Option [AuthorizationValue]): String = { - var is: InputStream = null - try{ - val conn: URLConnection = authorization match { - case Some(auth: ApiKeyValue) => { - if(auth.passAs == "header") { - val connection = new URL(url).openConnection() - connection.setRequestProperty(auth.keyName, auth.value) - connection - } - else if(auth.passAs == "query") { - new URL(url + "?%s=%s".format(URLEncoder.encode(auth.keyName, "UTF-8"), URLEncoder.encode(auth.value, "UTF-8"))).openConnection() - } - else { - new URL(url).openConnection() - } - } - case None => new URL(url).openConnection() - } - is = conn.getInputStream() - Source.fromInputStream(is).mkString - } - catch { - case e: javax.net.ssl.SSLProtocolException => { - println("there is a problem with the target SSL certificate") - println("**** you may want to run with -Djsse.enableSNIExtension=false\n\n") - e.printStackTrace - throw e - } - case e: Exception => e.printStackTrace; throw e; - } - finally { - if(is != null) is.close() - } - } -} \ No newline at end of file diff --git a/src/main/scala/com/wordnik/swagger/codegen/util/ResourceExtractor.scala b/src/main/scala/com/wordnik/swagger/codegen/util/ResourceExtractor.scala deleted file mode 100644 index 391ec6413ab8..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/util/ResourceExtractor.scala +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.util - -import com.wordnik.swagger.codegen.model._ - -import org.json4s._ -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.read - -import scala.io._ - -object ResourceExtractor extends RemoteUrl { - def fetchListing(path: String, authorization: Option[AuthorizationValue] = None): ResourceListing = { - val json = path.startsWith("http") match { - case true => urlToString(path, authorization) - case false => Source.fromFile(path).mkString - } - - implicit val formats = { - val jval = parse(json) - - val version = (jval \ "swaggerVersion") match { - case e: JInt => e.num.toString - case e: JBool => e.value.toString - case e: JString => e.s - case e: JDouble => e.num.toString - case _ => "" - } - SwaggerSerializers.formats(version) - } - parse(json).extract[ResourceListing] - } -} \ No newline at end of file diff --git a/src/main/scala/com/wordnik/swagger/codegen/util/ValidationException.scala b/src/main/scala/com/wordnik/swagger/codegen/util/ValidationException.scala deleted file mode 100644 index c92c2c67b7a6..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/util/ValidationException.scala +++ /dev/null @@ -1,24 +0,0 @@ -package com.wordnik.swagger.util - -import com.wordnik.swagger.codegen.model._ - -import scala.collection.JavaConverters._ -import scala.beans.BeanProperty - -class ValidationException(code:Int, msg:String, errors: List[ValidationError]) extends Exception(msg:String) { - val messages: java.util.List[ValidationMessage] = ( - for(e <- errors) yield ({ - val m = new ValidationMessage() - m.path = e.path - m.message = e.message - m.severity = e.severity - m - }) - ).toList.asJava -} - -class ValidationMessage() { - @BeanProperty var path: String = _ - @BeanProperty var message: String = _ - @BeanProperty var severity: String = _ -} \ No newline at end of file diff --git a/src/test/resources/petstore-1.1/pet.json b/src/test/resources/petstore-1.1/pet.json deleted file mode 100644 index 7bea7c375e91..000000000000 --- a/src/test/resources/petstore-1.1/pet.json +++ /dev/null @@ -1,227 +0,0 @@ -{ - "apiVersion":"0.2", - "swaggerVersion":"1.1", - "basePath":"http://petstore.swagger.wordnik.com/api", - "resourcePath":"/pet", - "apis":[ - { - "path":"/pet.{format}/{petId}", - "description":"Operations about pets", - "operations":[ - { - "httpMethod":"GET", - "summary":"Find pet by ID", - "notes":"Returns a pet based on ID", - "responseClass":"Pet", - "nickname":"getPetById", - "parameters":[ - { - "name":"petId", - "description":"ID of pet that needs to be fetched", - "paramType":"path", - "required":true, - "allowMultiple":false, - "dataType":"string" - } - ], - "errorResponses":[ - { - "code":400, - "reason":"Invalid ID supplied" - }, - { - "code":404, - "reason":"Pet not found" - } - ] - } - ] - }, - { - "path":"/pet.{format}", - "description":"Operations about pets", - "operations":[ - { - "httpMethod":"POST", - "summary":"Add a new pet to the store", - "responseClass":"void", - "nickname":"addPet", - "parameters":[ - { - "description":"Pet object that needs to be added to the store", - "paramType":"body", - "required":true, - "allowMultiple":false, - "dataType":"Pet" - } - ], - "errorResponses":[ - { - "code":405, - "reason":"Invalid input" - } - ] - }, - { - "httpMethod":"PUT", - "summary":"Update an existing pet", - "responseClass":"void", - "nickname":"updatePet", - "parameters":[ - { - "description":"Pet object that needs to be updated in the store", - "paramType":"body", - "required":true, - "allowMultiple":false, - "dataType":"Pet" - } - ], - "errorResponses":[ - { - "code":400, - "reason":"Invalid ID supplied" - }, - { - "code":404, - "reason":"Pet not found" - }, - { - "code":405, - "reason":"Validation exception" - } - ] - } - ] - }, - { - "path":"/pet.{format}/findByStatus", - "description":"Operations about pets", - "operations":[ - { - "httpMethod":"GET", - "summary":"Finds Pets by status", - "notes":"Multiple status values can be provided with comma seperated strings", - "responseClass":"List[Pet]", - "nickname":"findPetsByStatus", - "parameters":[ - { - "name":"status", - "description":"Status values that need to be considered for filter", - "paramType":"query", - "defaultValue":"available", - "allowableValues":{ - "valueType":"LIST", - "values":[ - "available", - "pending", - "sold" - ] - }, - "required":true, - "allowMultiple":true, - "dataType":"string" - } - ], - "errorResponses":[ - { - "code":400, - "reason":"Invalid status value" - } - ] - } - ] - }, - { - "path":"/pet.{format}/findByTags", - "description":"Operations about pets", - "operations":[ - { - "httpMethod":"GET", - "summary":"Finds Pets by tags", - "notes":"Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", - "deprecated":true, - "responseClass":"List[Pet]", - "nickname":"findPetsByTags", - "parameters":[ - { - "name":"tags", - "description":"Tags to filter by", - "paramType":"query", - "required":true, - "allowMultiple":true, - "dataType":"string" - } - ], - "errorResponses":[ - { - "code":400, - "reason":"Invalid tag value" - } - ] - } - ] - } - ], - "models":{ - "Category":{ - "id":"Category", - "properties":{ - "id":{ - "type":"long" - }, - "name":{ - "type":"string" - } - } - }, - "Pet":{ - "id":"Pet", - "properties":{ - "tags":{ - "items":{ - "$ref":"Tag" - }, - "type":"Array" - }, - "id":{ - "type":"long" - }, - "category":{ - "type":"Category" - }, - "status":{ - "allowableValues":{ - "valueType":"LIST", - "values":[ - "available", - "pending", - "sold" - ] - }, - "description":"pet status in the store", - "type":"string" - }, - "name":{ - "type":"string" - }, - "photoUrls":{ - "items":{ - "type":"string" - }, - "type":"Array" - } - } - }, - "Tag":{ - "id":"Tag", - "properties":{ - "id":{ - "type":"long" - }, - "name":{ - "type":"string" - } - } - } - } -} \ No newline at end of file diff --git a/src/test/resources/petstore-1.1/resources.json b/src/test/resources/petstore-1.1/resources.json deleted file mode 100644 index 977096ab5b89..000000000000 --- a/src/test/resources/petstore-1.1/resources.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "apiVersion":"0.2", - "swaggerVersion":"1.1", - "basePath":"http://petstore.swagger.wordnik.com/api", - "apis":[ - { - "path":"/store.{format}", - "description":"Operations about store" - }, - { - "path":"/pet.{format}", - "description":"Operations about pets" - }, - { - "path":"/user.{format}", - "description":"Operations about user" - } - ] -} \ No newline at end of file diff --git a/src/test/resources/petstore-1.1/store.json b/src/test/resources/petstore-1.1/store.json deleted file mode 100644 index 0c31f64c10c6..000000000000 --- a/src/test/resources/petstore-1.1/store.json +++ /dev/null @@ -1,127 +0,0 @@ -{ - "apiVersion":"0.2", - "swaggerVersion":"1.1", - "basePath":"http://petstore.swagger.wordnik.com/api", - "resourcePath":"/store", - "apis":[ - { - "path":"/store.{format}/order/{orderId}", - "description":"Operations about store", - "operations":[ - { - "httpMethod":"GET", - "summary":"Find purchase order by ID", - "notes":"For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors", - "responseClass":"Order", - "nickname":"getOrderById", - "parameters":[ - { - "name":"orderId", - "description":"ID of pet that needs to be fetched", - "paramType":"path", - "required":true, - "allowMultiple":false, - "dataType":"string" - } - ], - "errorResponses":[ - { - "code":400, - "reason":"Invalid ID supplied" - }, - { - "code":404, - "reason":"Order not found" - } - ] - }, - { - "httpMethod":"DELETE", - "summary":"Delete purchase order by ID", - "notes":"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "responseClass":"void", - "nickname":"deleteOrder", - "parameters":[ - { - "name":"orderId", - "description":"ID of the order that needs to be deleted", - "paramType":"path", - "required":true, - "allowMultiple":false, - "dataType":"string" - } - ], - "errorResponses":[ - { - "code":400, - "reason":"Invalid ID supplied" - }, - { - "code":404, - "reason":"Order not found" - } - ] - } - ] - }, - { - "path":"/store.{format}/order", - "description":"Operations about store", - "operations":[ - { - "httpMethod":"POST", - "summary":"Place an order for a pet", - "responseClass":"void", - "nickname":"placeOrder", - "parameters":[ - { - "description":"order placed for purchasing the pet", - "paramType":"body", - "required":true, - "allowMultiple":false, - "dataType":"Order" - } - ], - "errorResponses":[ - { - "code":400, - "reason":"Invalid order" - } - ] - } - ] - } - ], - "models":{ - "Order":{ - "id":"Order", - "properties":{ - "id":{ - "type":"long" - }, - "petId":{ - "type":"long" - }, - "status":{ - "allowableValues":{ - "valueType":"LIST", - "values":[ - "placed", - " approved", - " delivered" - ], - "valueType":"LIST" - }, - "description":"Order Status", - "type":"string" - }, - "quantity":{ - "type":"int" - }, - "shipDate":{ - "type":"Date" - } - } - } - } -} \ No newline at end of file diff --git a/src/test/resources/petstore-1.1/user.json b/src/test/resources/petstore-1.1/user.json deleted file mode 100644 index 1fbd05d88457..000000000000 --- a/src/test/resources/petstore-1.1/user.json +++ /dev/null @@ -1,254 +0,0 @@ -{ - "apiVersion":"0.2", - "swaggerVersion":"1.1", - "basePath":"http://petstore.swagger.wordnik.com/api", - "resourcePath":"/user", - "apis":[ - { - "path":"/user.{format}/createWithArray", - "description":"Operations about user", - "operations":[ - { - "httpMethod":"POST", - "summary":"Creates list of users with given input array", - "responseClass":"void", - "nickname":"createUsersWithArrayInput", - "parameters":[ - { - "description":"List of user object", - "paramType":"body", - "required":true, - "allowMultiple":false, - "dataType":"Array[User]" - } - ] - } - ] - }, - { - "path":"/user.{format}", - "description":"Operations about user", - "operations":[ - { - "httpMethod":"POST", - "summary":"Create user", - "notes":"This can only be done by the logged in user.", - "responseClass":"void", - "nickname":"createUser", - "parameters":[ - { - "description":"Created user object", - "paramType":"body", - "required":true, - "allowMultiple":false, - "dataType":"User" - } - ] - } - ] - }, - { - "path":"/user.{format}/createWithList", - "description":"Operations about user", - "operations":[ - { - "httpMethod":"POST", - "summary":"Creates list of users with given list input", - "responseClass":"void", - "nickname":"createUsersWithListInput", - "parameters":[ - { - "description":"List of user object", - "paramType":"body", - "required":true, - "allowMultiple":false, - "dataType":"List[User]" - } - ] - } - ] - }, - { - "path":"/user.{format}/{username}", - "description":"Operations about user", - "operations":[ - { - "httpMethod":"PUT", - "summary":"Updated user", - "notes":"This can only be done by the logged in user.", - "responseClass":"void", - "nickname":"updateUser", - "parameters":[ - { - "name":"username", - "description":"name that need to be deleted", - "paramType":"path", - "required":true, - "allowMultiple":false, - "dataType":"string" - }, - { - "description":"Updated user object", - "paramType":"body", - "required":true, - "allowMultiple":false, - "dataType":"User" - } - ], - "errorResponses":[ - { - "code":400, - "reason":"Invalid username supplied" - }, - { - "code":404, - "reason":"User not found" - } - ] - }, - { - "httpMethod":"DELETE", - "summary":"Delete user", - "notes":"This can only be done by the logged in user.", - "responseClass":"void", - "nickname":"deleteUser", - "parameters":[ - { - "name":"username", - "description":"The name that needs to be deleted", - "paramType":"path", - "required":true, - "allowMultiple":false, - "dataType":"string" - } - ], - "errorResponses":[ - { - "code":400, - "reason":"Invalid username supplied" - }, - { - "code":404, - "reason":"User not found" - } - ] - }, - { - "httpMethod":"GET", - "summary":"Get user by user name", - "responseClass":"User", - "nickname":"getUserByName", - "parameters":[ - { - "name":"username", - "description":"The name that needs to be fetched. Use user1 for testing.", - "paramType":"path", - "required":true, - "allowMultiple":false, - "dataType":"string" - } - ], - "errorResponses":[ - { - "code":400, - "reason":"Invalid username supplied" - }, - { - "code":404, - "reason":"User not found" - } - ] - } - ] - }, - { - "path":"/user.{format}/login", - "description":"Operations about user", - "operations":[ - { - "httpMethod":"GET", - "summary":"Logs user into the system", - "responseClass":"string", - "nickname":"loginUser", - "parameters":[ - { - "name":"username", - "description":"The user name for login", - "paramType":"query", - "required":true, - "allowMultiple":false, - "dataType":"string" - }, - { - "name":"password", - "description":"The password for login in clear text", - "paramType":"query", - "required":true, - "allowMultiple":false, - "dataType":"string" - } - ], - "errorResponses":[ - { - "code":400, - "reason":"Invalid username and password combination" - } - ] - } - ] - }, - { - "path":"/user.{format}/logout", - "description":"Operations about user", - "operations":[ - { - "httpMethod":"GET", - "summary":"Logs out current logged in user session", - "responseClass":"void", - "nickname":"logoutUser" - } - ] - } - ], - "models":{ - "User":{ - "id":"User", - "properties":{ - "id":{ - "type":"long" - }, - "lastName":{ - "type":"string" - }, - "phone":{ - "type":"string" - }, - "username":{ - "type":"string" - }, - "email":{ - "type":"string" - }, - "userStatus":{ - "allowableValues":{ - "valueType":"LIST", - "values":[ - "1-registered", - "2-active", - "3-closed" - ], - "valueType":"LIST" - }, - "description":"User Status", - "type":"int" - }, - "firstName":{ - "type":"string" - }, - "password":{ - "type":"string" - } - } - } - } -} \ No newline at end of file diff --git a/src/test/scala/BasicCSharpGeneratorTest.scala b/src/test/scala/BasicCSharpGeneratorTest.scala deleted file mode 100644 index 586046302cc5..000000000000 --- a/src/test/scala/BasicCSharpGeneratorTest.scala +++ /dev/null @@ -1,48 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.model._ -import com.wordnik.swagger.codegen.{BasicCSharpGenerator, PathUtil} -import com.wordnik.swagger.codegen.util._ -import com.wordnik.swagger.codegen.language._ - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.beans.BeanProperty - -@RunWith(classOf[JUnitRunner]) -class BasicCSharpGeneratorTest extends FlatSpec with Matchers { - val config = new BasicCSharpGenerator - - behavior of "BasicCSharpGenerator" - /* - * A response of type "void" will turn into a declaration of None - * for the template generator - */ - it should "perserve the name date" in { - config.toVarName("date") should be ("date") - } - - /* - * arrays look nice - */ - it should "process a string array" in { - config.processResponseDeclaration("array[string]") should be (Some("List")) - } -} diff --git a/src/test/scala/BasicGeneratorTest.scala b/src/test/scala/BasicGeneratorTest.scala deleted file mode 100644 index c1ebee6e1cb6..000000000000 --- a/src/test/scala/BasicGeneratorTest.scala +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicGenerator -import com.wordnik.swagger.codegen.util._ -import com.wordnik.swagger.codegen.model._ - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.collection.mutable.{LinkedHashMap, HashMap} - -@RunWith(classOf[JUnitRunner]) -class BasicGeneratorTest extends FlatSpec with Matchers { - class SampleGenerator extends BasicGenerator { - modelTemplateFiles += "model.mustache" -> ".test" - override def typeMapping = Map( - "string" -> "String", - "int" -> "Int", - "float" -> "Float", - "long" -> "Long", - "double" -> "Double", - "object" -> "Any") - } - - behavior of "BasicGenerator" - - it should "get operations" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.1/resources.json") - - val subDocs = ApiExtractor.fetchApiListings(resourceListing.swaggerVersion, "src/test/resources/petstore-1.1", resourceListing.apis) - val allModels = new HashMap[String, Model] - - implicit val basePath = "http://localhost:8080/api" - val generator = new SampleGenerator - val ops = generator.extractApiOperations(subDocs, allModels) - - allModels.size should be (5) - ops.size should be (16) - - val operations = ops.map(op => (op._2, op._3)).toMap - - (operations.keys.toSet & - Set("/pet.{format}/findByTags", "/user.{format}/createWithArray", "/user.{format}/createWithList", - "/store.{format}/order", "/user.{format}", "/pet.{format}/findByStatus", "/user.{format}/{username}", - "/user.{format}/logout", "/user.{format}/login", "/pet.{format}/{petId}", "/store.{format}/order/{orderId}", - "/pet.{format}")).size should be (12) - - // pick apart the /store/order api - val orderApi = operations("/store.{format}/order") - - orderApi.method should be ("POST") - orderApi.summary should be ("Place an order for a pet") - orderApi.responseClass should be ("void") - orderApi.nickname should be ("placeOrder") - orderApi.parameters.size should be (1) - orderApi.responseMessages.size should be (1) - } - - it should "verify ops are grouped by path correctly" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.1/resources.json") - val subDocs = ApiExtractor.fetchApiListings(resourceListing.swaggerVersion, "src/test/resources/petstore-1.1", resourceListing.apis) - val allModels = new HashMap[String, Model]() - - implicit val basePath = "http://localhost:8080/api" - val generator = new SampleGenerator - val ops = generator.extractApiOperations(subDocs, allModels) - val apiMap = generator.groupOperationsToFiles(ops) - - // verify all apis are there - (apiMap.keys.map(m => m._2).toSet & Set("user", "pet", "store")).size should be (3) - - // inspect the store apis - val orderApis = apiMap("http://petstore.swagger.wordnik.com/api","store").groupBy(_._1).toMap - val orderOperations = orderApis("/store.{format}/order/{orderId}").map(m => m._2) - - // 2 operations - orderOperations.size should be (2) - (orderOperations.map(m => m.method).toSet & Set("GET", "DELETE")).size should be (2) - (orderOperations.map(m => m.nickname).toSet & Set("getOrderById", "deleteOrder")).size should be (2) - } - - it should "create a model map" in { - implicit val basePath = "http://localhost:8080/api" - val generator = new SampleGenerator - val model = sampleModel - - val bundle = generator.prepareModelMap(Map(model.id -> model)).head - - // inspect properties - bundle("name") should be ("SampleObject") - bundle("className") should be ("SampleObject") - bundle("invokerPackage") should be (Some("com.wordnik.client.common")) - bundle("package") should be (Some("com.wordnik.client.model")) - - // inspect models - val modelList = bundle("models").asInstanceOf[List[Map[String, AnyRef]]] - modelList.size should be (1) - - val m = modelList.head("model").asInstanceOf[Map[String, AnyRef]] - m("classVarName") should be ("SampleObject") - } - - it should "create a model file" in { - implicit val basePath = "http://localhost:8080/api" - val generator = new SampleGenerator - - val model = sampleModel - val modelMap = (generator.prepareModelMap(Map(model.id -> model))) - - val modelFileContents = generator.writeFiles(modelMap, generator.modelTemplateFiles.toMap).toMap - val name = modelFileContents.keys.filter(_.endsWith("SampleObject.test")).head - - val fileContents = modelFileContents(name) - fileContents.indexOf("case class SampleObject") should not be (-1) - fileContents.indexOf("longValue: Long") should not be (-1) - fileContents.indexOf("intValue: Int") should not be (-1) - fileContents.indexOf("doubleValue: Double") should not be (-1) - fileContents.indexOf("stringValue: String") should not be (-1) - fileContents.indexOf("floatValue: Float") should not be (-1) - } - - def sampleModel = { - Model( - "SampleObject", - "SampleObject", - "SampleObject", - LinkedHashMap( - "stringValue" -> ModelProperty("string", "java.lang.String"), - "intValue" -> ModelProperty("int", "int"), - "longValue" -> ModelProperty("long", "long"), - "floatValue" -> ModelProperty("float", "float"), - "doubleValue" -> ModelProperty("double", "double")), - Some("a sample object")) - } -} - diff --git a/src/test/scala/BasicJavaGeneratorTest.scala b/src/test/scala/BasicJavaGeneratorTest.scala deleted file mode 100644 index f6cb0a27025c..000000000000 --- a/src/test/scala/BasicJavaGeneratorTest.scala +++ /dev/null @@ -1,204 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.model._ -import com.wordnik.swagger.codegen.{BasicJavaGenerator, PathUtil} -import com.wordnik.swagger.codegen.util._ -import com.wordnik.swagger.codegen.language._ - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.beans.BeanProperty - -@RunWith(classOf[JUnitRunner]) -class BasicJavaGeneratorTest extends FlatSpec with Matchers { - val config = new BasicJavaGenerator - - behavior of "BasicJavaGenerator" - /* - * A response of type "void" will turn into a declaration of None - * for the template generator - */ - it should "process a response declaration" in { - config.processResponseDeclaration("void") should be (None) - } - - /* - * swagger strings are turned into scala Strings - */ - it should "process a string response" in { - config.processResponseDeclaration("string") should be (Some("String")) - } - - /* - * arrays look nice - */ - it should "process a string array" in { - config.processResponseDeclaration("array[String]") should be (Some("List")) - } - - it should "process an upper-case string array" in { - config.processResponseDeclaration("Array[String]") should be (Some("List")) - } - - /* - * swagger int is turned into scala Int - */ - it should "process an unmapped response type" in { - config.processResponseDeclaration("int") should be (Some("Integer")) - } - - /* - * returns the invoker package from the config - */ - it should "get the invoker package" in { - config.invokerPackage should be (Some("com.wordnik.client.common")) - } - - /* - * returns the api package - */ - it should "get the api package" in { - config.apiPackage should be (Some("com.wordnik.client.api")) - } - - /* - * returns the model package - */ - it should "get the model package" in { - config.modelPackage should be (Some("com.wordnik.client.model")) - } - - /* - * types are mapped between swagger types and language-specific - * types - */ - it should "convert to a declared type" in { - config.toDeclaredType("string") should be ("String") - config.toDeclaredType("int") should be ("Integer") - config.toDeclaredType("float") should be ("Float") - config.toDeclaredType("long") should be ("Long") - config.toDeclaredType("double") should be ("Double") - config.toDeclaredType("object") should be ("Object") - } - - /* - * declarations are used in models, and types need to be - * mapped appropriately - */ - it should "convert a string a declaration" in { - val expected = Map( - "string" -> ("String", "null"), - "int" -> ("Integer", "null"), - "float" -> ("Float", "null"), - "long" -> ("Long", "null"), - "double" -> ("Double", "null"), - "object" -> ("Object", "null")) - expected.map(e => { - val model = ModelProperty(e._1, "nothing") - config.toDeclaration(model) should be (e._2) - }) - } - - /* - * codegen should honor special imports to avoid generating - * classes - */ - it should "honor the import mapping" in { - config.importMapping("Date") should be ("java.util.Date") - config.importMapping("DateTime") should be ("org.joda.time.*") - config.importMapping("Timestamp") should be ("java.sql.Timestamp") - config.importMapping("Set") should be ("java.util.*") - } - - /* - * fail on reserved words (java doesn't allow quoting) - */ - it should "quote a reserved var name" in { - val thrown = intercept[Exception] { - config.toVarName("package") - } - thrown should not be (null) - } - - /* - * support list declarations with string inner value and the correct default value - */ - it should "create a declaration with a List of strings" in { - val property = ModelProperty( - `type` = "Array", - qualifiedType = "nothing", - items=Some(ModelRef(`type`= "string"))) - val m = config.toDeclaration(property) - m._1 should be ("List") - m._2 should be ("new ArrayList()") - } - - /* - * support list declarations with int inner value and the correct default value - */ - it should "create a declaration with a List of ints" in { - val property = ModelProperty( - `type` = "Array", - qualifiedType = "nothing", - items=Some(ModelRef(`type`= "int"))) - val m = config.toDeclaration(property) - m._1 should be ("List") - m._2 should be ("new ArrayList()") - } - - /* - * support list declarations with float inner value and the correct default value - */ - it should "create a declaration with a List of floats" in { - val property = ModelProperty( - `type` = "Array", - qualifiedType = "nothing", - items=Some(ModelRef(`type`= "float"))) - val m = config.toDeclaration(property) - m._1 should be ("List") - m._2 should be ("new ArrayList()") - } - - /* - * support list declarations with double inner value and the correct default value - */ - it should "create a declaration with a List of doubles" in { - val property = ModelProperty( - `type` = "Array", - qualifiedType = "nothing", - items=Some(ModelRef(`type`= "double"))) - val m = config.toDeclaration(property) - m._1 should be ("List") - m._2 should be ("new ArrayList()") - } - - /* - * support list declarations with complex inner value and the correct default value - */ - it should "create a declaration with a List of complex objects" in { - val property = ModelProperty( - `type` = "Array", - qualifiedType = "nothing", - items=Some(ModelRef(`type`= "User"))) - val m = config.toDeclaration(property) - m._1 should be ("List") - m._2 should be ("new ArrayList()") - } -} diff --git a/src/test/scala/BasicScalaGeneratorTest.scala b/src/test/scala/BasicScalaGeneratorTest.scala deleted file mode 100644 index 2c3d52514da8..000000000000 --- a/src/test/scala/BasicScalaGeneratorTest.scala +++ /dev/null @@ -1,296 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.model._ -import com.wordnik.swagger.codegen.{BasicScalaGenerator, Codegen, PathUtil} -import com.wordnik.swagger.codegen.util._ -import com.wordnik.swagger.codegen.language._ - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.collection.mutable.HashMap - -@RunWith(classOf[JUnitRunner]) -class BasicScalaGeneratorTest extends FlatSpec with Matchers { - val config = new BasicScalaGenerator - - behavior of "BasicScalaGenerator" - /* - * A response of type "void" will turn into a declaration of None - * for the template generator - */ - it should "process a response declaration" in { - config.processResponseDeclaration("void") should be (None) - } - - /* - * swagger strings are turned into scala Strings - */ - it should "process a string response" in { - config.processResponseDeclaration("string") should be (Some("String")) - } - - /* - * arrays look nice - */ - it should "process a string array" in { - config.processResponseDeclaration("array[String]") should be (Some("List[String]")) - } - - /* - * swagger int is turned into scala Int - */ - it should "process an unmapped response type" in { - config.processResponseDeclaration("int") should be (Some("Int")) - } - - /* - * returns the invoker package from the config - */ - it should "get the invoker package" in { - config.invokerPackage should be (Some("com.wordnik.client.common")) - } - - /* - * returns the api package - */ - it should "get the api package" in { - config.apiPackage should be (Some("com.wordnik.client.api")) - } - - /* - * returns the model package - */ - it should "get the model package" in { - config.modelPackage should be (Some("com.wordnik.client.model")) - } - - /* - * types are mapped between swagger types and language-specific - * types - */ - it should "convert to a declared type" in { - config.toDeclaredType("boolean") should be ("Boolean") - config.toDeclaredType("string") should be ("String") - config.toDeclaredType("int") should be ("Int") - config.toDeclaredType("float") should be ("Float") - config.toDeclaredType("long") should be ("Long") - config.toDeclaredType("double") should be ("Double") - config.toDeclaredType("object") should be ("Any") - } - - /* - * declarations are used in models, and types need to be - * mapped appropriately - */ - it should "convert a string a declaration" in { - val expected = Map("string" -> ("String", "_"), - "int" -> ("Int", "0"), - "float" -> ("Float", "0f"), - "long" -> ("Long", "0L"), - "double" -> ("Double", "0.0"), - "object" -> ("Any", "_")) - expected.map(e => { - val model = ModelProperty(e._1, "nothing") - config.toDeclaration(model) should be (e._2) - }) - } - - /* - * codegen should honor special imports to avoid generating - * classes - */ - it should "honor the import mapping" in { - config.importMapping("Date") should be ("java.util.Date") - } - - /* - * single tick reserved words - */ - it should "quote a reserved var name" in { - config.toVarName("package") should be ("`package`") - } - - /* - * support list declarations with string inner value and the correct default value - */ - it should "create a declaration with a List of strings" in { - val property = ModelProperty( - `type` = "Array", - qualifiedType = "nothing", - items=Some(ModelRef(`type`= "string"))) - val m = config.toDeclaration(property) - m._1 should be ("List[String]") - m._2 should be ("_") - } - - /* - * support list declarations with int inner value and the correct default value - */ - it should "create a declaration with a List of ints" in { - val property = ModelProperty( - `type` = "Array", - qualifiedType = "nothing", - items=Some(ModelRef(`type`= "int"))) - val m = config.toDeclaration(property) - m._1 should be ("List[Int]") - m._2 should be ("0") - } - - /* - * support list declarations with float inner value and the correct default value - */ - it should "create a declaration with a List of floats" in { - val property = ModelProperty( - `type` = "Array", - qualifiedType = "nothing", - items=Some(ModelRef(`type`= "float"))) - val m = config.toDeclaration(property) - m._1 should be ("List[Float]") - m._2 should be ("0f") - } - - /* - * support list declarations with double inner value and the correct default value - */ - it should "create a declaration with a List of doubles" in { - val property = ModelProperty( - `type` = "Array", - qualifiedType = "nothing", - items=Some(ModelRef(`type`= "double"))) - val m = config.toDeclaration(property) - m._1 should be ("List[Double]") - m._2 should be ("0.0") - } - - /* - * support list declarations with complex inner value and the correct default value - */ - it should "create a declaration with a List of complex objects" in { - val property = ModelProperty( - `type` = "Array", - qualifiedType = "Array", - items = Some(ModelRef(`type`= "User"))) - val m = config.toDeclaration(property) - m._1 should be ("List[User]") - m._2 should be ("_") - } - - it should "verify an api map with query params" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.1/resources.json", None) - val apis = ApiExtractor.extractApiOperations(resourceListing.swaggerVersion, "src/test/resources/petstore-1.1", resourceListing.apis) - val codegen = new Codegen(config) - val petApi = apis.filter(doc => doc.resourcePath == "/pet").head - - val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByTags").head - val operation = endpoint.operations.filter(op => op.method == "GET").head - val m = codegen.apiToMap("http://my.api.com/api", operation) - - m("path") should be ("http://my.api.com/api") - m("bodyParams").asInstanceOf[List[_]].size should be (0) - m("httpMethod") should be ("GET") - - // Pet => NIKPet - m("returnBaseType") should be (Some("Pet")) - m("returnType") should be (Some("List[Pet]")) - m("returnTypeIsPrimitive") should be (None) - m("pathParams").asInstanceOf[List[_]].size should be (0) - m("returnContainer") should be (Some("List")) - m("requiredParamCount") should be ("1") - - val queryParams = m("queryParams").asInstanceOf[List[_]] - queryParams.size should be (1) - - val queryParam = queryParams.head.asInstanceOf[HashMap[String, _]] - queryParam("type") should be ("query") - queryParam("dataType") should be ("String") - queryParam("required") should be ("true") - queryParam("paramName") should be ("tags") - queryParam("swaggerDataType") should be ("string") - queryParam("allowMultiple") should be ("true") - queryParam("defaultValue") should be (None) - } - - it should "verify an api map with query params with default values" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.1/resources.json", None) - val apis = ApiExtractor.extractApiOperations(resourceListing.swaggerVersion, "src/test/resources/petstore-1.1", resourceListing.apis) - val codegen = new Codegen(config) - val petApi = apis.filter(doc => doc.resourcePath == "/pet").head - - val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByStatus").head - val operation = endpoint.operations.filter(op => op.method == "GET").head - val m = codegen.apiToMap("http://my.api.com/api", operation) - - m("path") should be ("http://my.api.com/api") - m("bodyParams").asInstanceOf[List[_]].size should be (0) - m("httpMethod") should be ("GET") - - // Pet => Pet - m("returnBaseType") should be (Some("Pet")) - - // problem here - m("returnType") should be (Some("List[Pet]")) - m("returnTypeIsPrimitive") should be (None) - m("pathParams").asInstanceOf[List[_]].size should be (0) - m("returnContainer") should be (Some("List")) - m("requiredParamCount") should be ("1") - - val queryParams = m("queryParams").asInstanceOf[List[_]] - queryParams.size should be (1) - - val queryParam = queryParams.head.asInstanceOf[HashMap[String, _]] - queryParam("type") should be ("query") - queryParam("dataType") should be ("String") - queryParam("required") should be ("true") - queryParam("paramName") should be ("status") - queryParam("swaggerDataType") should be ("string") - queryParam("allowMultiple") should be ("true") - queryParam("defaultValue") should be (Some("\"available\"")) - queryParam("allowableValues") should be (Some("LIST[available,pending,sold]")) - } - - it should "create an api file" in { - implicit val basePath = "http://localhost:8080/api" - val codegen = new Codegen(config) - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.1/resources.json", None) - - val apis = ApiExtractor.extractApiOperations(resourceListing.swaggerVersion, "src/test/resources/petstore-1.1", resourceListing.apis) - val petApi = apis.filter(doc => doc.resourcePath == "/pet").head - - val endpoint = petApi.apis.filter(api => api.path == "/pet.{format}/findByTags").head - val operation = endpoint.operations.filter(op => op.method == "GET").head - val m = codegen.apiToMap("http://my.api.com/api", operation) - - val allModels = new HashMap[String, Model] - val operations = config.extractApiOperations(List(petApi), allModels) - - val operationMap = config.groupOperationsToFiles(operations) - - val apiBundle = config.prepareApiBundle(operationMap.toMap) - val apiInfo = config.writeFiles(apiBundle, config.apiTemplateFiles.toMap) - - apiInfo.size should be (1) - val file = apiInfo.head - - // verify the filename is set - // file._1.indexOf("""PetApi.scala""") should not be (-1) - // verify the default value for status exists - // file._2.indexOf("""(status: String= "available")""") should not be (-1) - } -} diff --git a/src/test/scala/CodegenConfigTest.scala b/src/test/scala/CodegenConfigTest.scala deleted file mode 100644 index 730662606395..000000000000 --- a/src/test/scala/CodegenConfigTest.scala +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.util._ -import com.wordnik.swagger.codegen.language._ -import com.wordnik.swagger.codegen.PathUtil - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.beans.BeanProperty - -@RunWith(classOf[JUnitRunner]) -class CodegenConfigTest extends FlatSpec with Matchers { - class SampleCodegenConfig extends CodegenConfig with PathUtil { - override def packageName = "com.test" - override def templateDir = "src/test/resources/sampleConfigTemplates" - override def destinationDir = { - val tmpFile = java.io.File.createTempFile("test",".tmp") - tmpFile.delete; tmpFile.mkdir - tmpFile.deleteOnExit - tmpFile.toString - } - override def escapeReservedWord(word: String) = "`" + word + "`" - override def typeMapping = Map("int" -> "integer") - override def invokerPackage = Some("com.wordnik.something") - override def apiPackage: Option[String] = Some("com.wordnik.api") - override def modelPackage = Some("com.wordnik.models") - override def reservedWords = Set("special") - override def importMapping = super.importMapping ++ Map("User" -> "com.mypackage.User") - } - - val config = new SampleCodegenConfig - - behavior of "PathUtil" - /* - * We will take an api in the spec and create an API name from it - */ - it should "convert an api name" in { - config.toApiName("fun") should be ("FunApi") - } - - /* - * We need to generate an API name from the resource path, - * i.e. /foo will follow rules to become FooApi - */ - it should "convert a path" in { - config.apiNameFromPath("/foo/bar/cats/dogs") should be ("FooApi") - } - - behavior of "CodegenConfig" - /* - * A response of type "void" will turn into a declaration of None - * for the template generator - */ - it should "process a response declaration" in { - config.processResponseDeclaration("void") should be (None) - } - - /* - * if a response declaration is valid as-is, it will be - * unchanged - */ - it should "process an unchanged response" in { - config.processResponseDeclaration("string") should be (Some("string")) - } - - /* - * if a typeMapping is configured, the response type declaration - * from a method should be translated - */ - it should "process an mapped response type" in { - config.processResponseDeclaration("int") should be (Some("integer")) - } - - /* - * returns the invoker package from the config - */ - it should "get the invoker package" in { - config.invokerPackage should be (Some("com.wordnik.something")) - } - - /* - * returns the api package - */ - it should "get the api package" in { - config.apiPackage should be (Some("com.wordnik.api")) - } - - /* - * returns the model package - */ - it should "get the model package" in { - config.modelPackage should be (Some("com.wordnik.models")) - } - - /* - * types are mapped between swagger types and language-specific - * types - */ - it should "convert to a declared type" in { - config.toDeclaredType("int") should be ("integer") - } - - /* - * codegen should honor special imports to avoid generating - * classes - */ - it should "honor the import mapping" in { - config.importMapping("User") should be ("com.mypackage.User") - } - - /* - * reserved words should be treated appropriately by the config, - * either by quoting or manipulating them with a prefix/suffix - */ - it should "quote a reserved var name" in { - config.toVarName("special") should be ("`special`") - } -} diff --git a/src/test/scala/CodegenTest.scala b/src/test/scala/CodegenTest.scala deleted file mode 100644 index b41ad4caa683..000000000000 --- a/src/test/scala/CodegenTest.scala +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.Codegen -import com.wordnik.swagger.codegen.BasicJavaGenerator -import com.wordnik.swagger.codegen.model._ - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.beans.BeanProperty -import scala.collection.mutable.{ HashMap, LinkedHashMap } - -@RunWith(classOf[JUnitRunner]) -class CodegenTest extends FlatSpec with Matchers { - - val subject = new Codegen(new BasicJavaGenerator) - - val testOp = new Operation("GET", - "List All Contacts", - "", - "Array[ContactData]", - "listContacts", - 0, - List.empty, - List.empty, - List.empty, - List.empty, - //query param - List(new Parameter("Name", Some("name"), Some("null"), false, false, "String", AnyAllowableValues, "query", None)), - List.empty, - None) - - val testModel = new Model("Contact", - "Contact", - "Contact", - //required field - LinkedHashMap("Name" -> new ModelProperty("String", "String", 0, true, None, AnyAllowableValues, None)), - None, - None, - None) - - behavior of "Codegen" - /* - * A return specified as "Array" should map to "List" - */ - it should "recognize the returnContainer as a List" in { - val map = subject.apiToMap("/contacts", testOp) - map("returnContainer") should be (Some("List")) - } - - /* - * Field first on the query param should be true - */ - it should "have a first field on first query param and should be true" in { - val map = subject.apiToMap("/contacts", testOp) - map("queryParams").asInstanceOf[List[HashMap[String, String]]].head("first") should be ("true") - } - - /* - * Field hasRequiredParams should be true - */ - it should "have a hasRequiredParams field and should be true" in { - val map = subject.modelToMap("Contact", testModel) - map("hasRequiredParams") should be ("true") - } -} - diff --git a/src/test/scala/PathUtilTest.scala b/src/test/scala/PathUtilTest.scala deleted file mode 100644 index e2ea481ffef0..000000000000 --- a/src/test/scala/PathUtilTest.scala +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 com.wordnik.swagger.codegen.BasicScalaGenerator -import com.wordnik.swagger.codegen.PathUtil - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -@RunWith(classOf[JUnitRunner]) -class PathUtilTest extends FlatSpec with Matchers { - val config = new BasicScalaGenerator - - behavior of "PathUtil" - /* - * We will take an api in the spec and create an API name from it - */ - it should "convert an api name" in { - config.toApiName("fun") should be ("FunApi") - } - - /* - * We need to generate an API name from the resource path, - * i.e. /foo will follow rules to become FooApi - */ - it should "convert a path" in { - config.apiNameFromPath("/foo/bar/cats/dogs") should be ("FooApi") - } - - /** - * since swagger-spec 1.2 doesn't support `basePath` in the Resource Listing, - * ensure the base path is extracted from the input host - **/ - it should "get determine the basePath implicitly" in { - sys.props -= "fileMap" - new PathUtilImpl().getBasePath("http://foo.com/api-docs", "") should be ("http://foo.com/api-docs") - } -} - -class PathUtilImpl extends PathUtil diff --git a/src/test/scala/swaggerSpec1_1/CoreUtilsTest.scala b/src/test/scala/swaggerSpec1_1/CoreUtilsTest.scala deleted file mode 100644 index 8afc39a491ab..000000000000 --- a/src/test/scala/swaggerSpec1_1/CoreUtilsTest.scala +++ /dev/null @@ -1,267 +0,0 @@ -package swaggerSpec1_1 - -import com.wordnik.swagger.codegen.util.CoreUtils - -import com.wordnik.swagger.codegen.model._ -import com.wordnik.swagger.codegen.util._ - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.read - -import scala.collection.mutable.LinkedHashMap - -@RunWith(classOf[JUnitRunner]) -class CoreUtilsTest extends FlatSpec with Matchers { - sys.props += "fileMap" -> "src/test/resources/petstore-1.1" - - behavior of "CoreUtils" - - it should "verify models are extracted" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.1/resources.json") - val apis = ApiExtractor.extractApiOperations(resourceListing.swaggerVersion, "src/test/resources/petstore-1.1", resourceListing.apis) - - val cu = CoreUtils.extractAllModels(apis) - cu.size should be (5) - - (cu.keys.toSet & Set("User", "Tag", "Pet", "Category", "Order")).size should be (5) - } - - it should "verify operation names" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.1/resources.json") - val apis = ApiExtractor.extractApiOperations(resourceListing.swaggerVersion, "src/test/resources/petstore-1.1", resourceListing.apis) - - val petApi = apis.filter(api => api.resourcePath == "/pet").head - val eps = petApi.apis.map(api => (api.path, api)).toMap - val ops = eps("/pet.{format}").operations.map(ep => (ep.nickname, ep)).toMap - - ops.size should be (2) - - (ops.keys.toSet & Set("addPet", "updatePet")).size should be (2) - } - - it should "find required models" in { - val apis = CoreUtilsTest.sampleApis1 - val models = CoreUtils.extractApiModels(apis.head) - models.size should be (5) - } - - it should "find required models from a nested list" in { - val apis = CoreUtilsTest.sampleApis2 - val models = CoreUtils.extractApiModels(apis.head) - models.size should be (5) - } -} - -object CoreUtilsTest { - implicit val formats = SwaggerSerializers.formats("1.1") - - def sampleApis1 = { - parse(""" -[ - { - "apiVersion": "0.2", - "swaggerVersion": "1.1", - "basePath": "http://api.helloreverb.com/api", - "resourcePath": "/mysteries", - "apis": [ - { - "path": "/mysteries.{format}/{petId}", - "description": "As the name suggests", - "operations": [ - { - "httpMethod": "GET", - "summary": "You find amazing htings here", - "responseClass": "DeepMystery", - "nickname": "getMysteryById", - "parameters": [ - { - "name": "id", - "description": "ID of mystery", - "paramType": "path", - "required": true, - "allowMultiple": false, - "dataType": "string" - } - ] - } - ] - } - ], - "models": { - "MysteryList": { - "id": "MysteryList", - "properties": { - "id": { - "type": "long" - }, - "mysteries": { - "items":{ - "$ref":"Mystery1" - }, - "type":"Array" - } - } - }, - "DeepMystery": { - "id": "DeepMystery", - "properties": { - "id": { - "type": "Mystery1" - }, - "name": { - "type": "string" - } - } - }, - "Mystery1": { - "id": "Mystery1", - "properties": { - "mystery2": { - "type": "Mystery2" - }, - "name": { - "type": "string" - } - } - }, - "Mystery2": { - "id": "Mystery2", - "properties": { - "mystery3": { - "type": "Mystery3" - }, - "name": { - "type": "string" - } - } - }, - "Mystery3": { - "id": "Mystery3", - "properties": { - "mystery4": { - "type": "Mystery4" - }, - "name": { - "type": "string" - } - } - }, - "Mystery4": { - "id": "Mystery4", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - } - } - } - } -] - """).extract[List[ApiListing]] - } - - def sampleApis2 = { - parse(""" -[ - { - "apiVersion": "0.2", - "swaggerVersion": "1.1", - "basePath": "http://api.helloreverb.com/api", - "resourcePath": "/mysteries", - "apis": [ - { - "path": "/mysteries.{format}/{petId}", - "description": "As the name suggests", - "operations": [ - { - "httpMethod": "GET", - "summary": "You find amazing htings here", - "responseClass": "MysteryList", - "nickname": "getMysteryById", - "parameters": [ - { - "name": "id", - "description": "ID of mystery", - "paramType": "path", - "required": true, - "allowMultiple": false, - "dataType": "string" - } - ] - } - ] - } - ], - "models": { - "MysteryList": { - "id": "MysteryList", - "properties": { - "id": { - "type": "long" - }, - "mystery1": { - "type":"Mystery1" - } - } - }, - "Mystery1": { - "id": "Mystery1", - "properties": { - "mystery2": { - "type": "Mystery2" - }, - "name": { - "type": "string" - } - } - }, - "Mystery2": { - "id": "Mystery2", - "properties": { - "mystery3List": { - "items": { - "$ref": "Mystery3" - }, - "type": "List" - }, - "name": { - "type": "string" - } - } - }, - "Mystery3": { - "id": "Mystery3", - "properties": { - "mystery4": { - "type": "Mystery4" - }, - "name": { - "type": "string" - } - } - }, - "Mystery4": { - "id": "Mystery4", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - } - } - } - } -] - """).extract[List[ApiListing]] - } -} \ No newline at end of file diff --git a/src/test/scala/swaggerSpec1_1/ModelSerializerValidations.scala b/src/test/scala/swaggerSpec1_1/ModelSerializerValidations.scala deleted file mode 100644 index f04d031d4b77..000000000000 --- a/src/test/scala/swaggerSpec1_1/ModelSerializerValidations.scala +++ /dev/null @@ -1,552 +0,0 @@ -package swaggerSpec1_1 - -import com.wordnik.swagger.codegen.model._ - -import org.json4s._ -import org.json4s.JsonDSL._ -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.{read, write} - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.collection.mutable.{ LinkedHashMap, ListBuffer } - -@RunWith(classOf[JUnitRunner]) -class ResourceListingValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "fail resource listing without base path" in { - val jsonString = """ - { - "apiVersion":"1.2.3", - "swaggerVersion":"1.1" - } - """ - val listing = parse(jsonString).extract[ResourceListing] - val errors = SwaggerValidator.validate(listing) - // errors.size should be (1) - } - - it should "fail resource listing without apiVersion" in { - val jsonString = """ - { - "basePath": "http://foo.com", - "swaggerVersion":"1.1" - } - """ - val listing = parse(jsonString).extract[ResourceListing] - val errors = SwaggerValidator.validate(listing) - errors.size should be (1) - } - - it should "fail with missing paths in a ResourceListing" in { - val jsonString = """ - { - "apiVersion":"1.2.3", - "swaggerVersion":"1.1", - "basePath":"http://foo/bar", - "apis":[ - { - "description":"path ab apis" - },{ - "path":"/c", - "description":"path c apis" - } - ] - } - """ - parse(jsonString).extract[ResourceListing] match { - case e: ResourceListing => { - e.apis.size should be (2) - val errors = SwaggerValidator.validate(e) - errors.size should be (1) - } - case _ => fail("didn't parse the underlying apis") - } - } -} - -@RunWith(classOf[JUnitRunner]) -class ApiListingReferenceValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize an ApiListingReference" in { - val jsonString = """ - { - "description":"the description" - } - """ - parse(jsonString).extract[ApiListingReference] match { - case p: ApiListingReference => { - p.description should be (Some("the description")) - val errors = new ListBuffer[ValidationError] - SwaggerValidator.validate(p, errors, "") - errors.size should be (1) - } - case _ => fail("wrong type returned, should be ApiListingReference") - } - } - - it should "serialize an ApiListingReference" in { - val l = ApiListingReference("/foo/bar", Some("the description")) - write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ApiDescriptionValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "fail to deserialize an ApiDescription with path, method, return type" in { - val jsonString = """ - { - "description":"the description", - "operations":[ - { - "summary":"the summary", - "notes":"the notes", - "nickname":"getMeSomeStrings", - "parameters":[ - { - "name":"id", - "description":"the id", - "defaultValue":"-1", - "required":false, - "allowMultiple":true, - "dataType":"string", - "allowableValues":{ - "valueType":"LIST", - "values":["a","b","c"] - }, - "paramType":"query" - } - ] - } - ] - } - """ - parse(jsonString).extract[ApiDescription] match { - case p: ApiDescription => { - val errors = new ListBuffer[ValidationError] - SwaggerValidator.validate(p, errors, "") - errors.size should be (3) - } - case _ => fail("wrong type returned, should be ApiDescription") - } - } -} - -@RunWith(classOf[JUnitRunner]) -class OperationValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "fail to deserialize an Operation with missing param type" in { - val jsonString = """ - { - "httpMethod":"GET", - "summary":"the summary", - "notes":"the notes", - "responseClass":"string", - "nickname":"getMeSomeStrings", - "parameters":[ - { - "name":"id", - "description":"the id", - "defaultValue":"-1", - "required":false, - "allowMultiple":true, - "dataType":"string", - "allowableValues":{ - "valueType":"LIST", - "values":["a","b","c"] - } - } - ] - } - """ - val json = parse(jsonString) - json.extract[Operation] match { - case op: Operation => { - val errors = new ListBuffer[ValidationError] - SwaggerValidator.validate(op, errors, "") - errors.size should be (1) - } - case _ => fail("wrong type returned, should be Operation") - } - } - - it should "serialize an operation" in { - val op = Operation( - "get", - "the summary", - "the notes", - "string", - "getMeSomeStrings", - 0, - List.empty, - List.empty, - List.empty, - List.empty, - List(Parameter("id", Some("the id"), Some("-1"), false, true, "string", AllowableListValues(List("a","b","c")), "query")) - ) - write(op) should be ("""{"method":"get","summary":"the summary","notes":"the notes","responseClass":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"dataType":"string","allowableValues":{"valueType":"LIST","values":["a","b","c"]},"paramType":"query"}]}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ResponseMessageValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize an ResponseMessage" in { - val jsonString = """ - { - "code":101, - "reason":"the message" - } - """ - val json = parse(jsonString) - json.extract[ResponseMessage] match { - case p: ResponseMessage => { - p.code should be (101) - p.message should be ("the message") - } - case _ => fail("wrong type returned, should be ResponseMessage") - } - } - - it should "serialize an operation" in { - val l = ResponseMessage(101, "the message") - write(l) should be ("""{"code":101,"message":"the message"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ParameterValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize another param" in { - val jsonString = """ - { - "name":"includeDuplicates", - "defaultValue":"false", - "description":"Show duplicate examples from different sources", - "required":"false", - "allowableValues":{ - "values":[ - false, - true - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - } - """ - val json = parse(jsonString) - json.extract[Parameter] match { - case p: Parameter => { - p.name should be ("includeDuplicates") - p.description should be (Some("Show duplicate examples from different sources")) - p.defaultValue should be (Some("false")) - p.required should be (false) - p.allowMultiple should be (false) - p.dataType should be ("string") - p.paramType should be ("query") - } - case _ => fail("wrong type returned, should be Parameter") - } - } - - it should "deserialize a parameter" in { - val jsonString = """ - { - "name":"name", - "description":"description", - "defaultValue":"tony", - "required":false, - "allowMultiple":true, - "dataType":"string", - "paramType":"query" - } - """ - val json = parse(jsonString) - json.extract[Parameter] match { - case p: Parameter => { - p.name should be ("name") - p.description should be (Some("description")) - p.defaultValue should be (Some("tony")) - p.required should be (false) - p.allowMultiple should be (true) - p.dataType should be ("string") - p.paramType should be ("query") - } - case _ => fail("wrong type returned, should be Parameter") - } - } - - it should "serialize a parameter" in { - val l = Parameter("name", Some("description"), Some("tony"), false, true, "string", AnyAllowableValues, "query") - write(l) should be ("""{"name":"name","description":"description","defaultValue":"tony","required":false,"allowMultiple":true,"dataType":"string","paramType":"query"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize a model" in { - val jsonString = """ - { - "id":"Foo", - "name":"Bar", - "properties": { - "id": { - "type":"string", - "required":true, - "description":"id" - }, - "name": { - "type":"string", - "required":false, - "description":"name" - }, - "tags": { - "type":"Array", - "items": { - "type":"string" - } - } - }, - "description":"nice model" - } - """ - val json = parse(jsonString) - json.extract[Model] match { - case model: Model => { - model.id should be ("Foo") - model.name should be ("Bar") - model.properties should not be (null) - model.properties.size should be (3) - model.description should be (Some("nice model")) - model.properties("id") match { - case e: ModelProperty => { - e.`type` should be ("string") - e.required should be (true) - e.description should be (Some("id")) - } - case _ => fail("missing property id") - } - model.properties("name") match { - case e: ModelProperty => { - e.`type` should be ("string") - e.required should be (false) - e.description should be (Some("name")) - } - case _ => fail("missing property name") - } - - model.properties("tags") match { - case e: ModelProperty => { - e.`type` should be ("Array") - e.required should be (false) - e.items match { - case Some(items) => items.`type` should be ("string") - case _ => fail("didn't find ref for Array") - } - } - case _ => fail("missing property name") - } - } - case _ => fail("expected type Model") - } - } - - it should "serialize a model" in { - val ref = Model("Foo", "Bar", "Bar", (LinkedHashMap("s" -> ModelProperty("string", "string", 0, true, Some("a string"))))) - write(ref) should be ("""{"id":"Foo","name":"Bar","properties":{"s":{"type":"string","required":true,"description":"a string"}}}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelRefValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize a model ref" in { - val jsonString = """ - { - "$ref":"Foo", - "type":"Bar" - } - """ - val json = parse(jsonString) - json.extract[ModelRef] match { - case p: ModelRef => { - p.ref should be (Some("Foo")) - p.`type` should be ("Bar") - } - case _ => fail("expected type ModelRef") - } - } - - it should "serialize a model ref" in { - val ref = ModelRef("Foo", Some("Bar")) - write(ref) should be ("""{"type":"Foo","$ref":"Bar"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelPropertyValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize a model property with allowable values and ref" in { - val jsonString = """ - { - "type":"string", - "required":false, - "description":"nice", - "allowableValues": { - "valueType":"LIST", - "values":["1","2","3"] - }, - "items":{ - "type":"Foo", - "$ref":"Bar" - } - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (false) - p.description should be (Some("nice")) - p.allowableValues match { - case e: AllowableListValues => e.values should be (List("1","2","3")) - case _ => fail("expected allowable values") - } - p.items match { - case Some(e: ModelRef) => { - e.`type` should be ("Foo") - e.ref should be (Some("Bar")) - } - case _ => fail("expected type ModelProperty") - } - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property with allowable values and ref" in { - val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b")),Some(ModelRef("Foo",Some("Bar")))) - write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]},"items":{"type":"Foo","$ref":"Bar"}}""") - } - - it should "deserialize a model property with allowable values" in { - val jsonString = """ - { - "type":"string", - "required":false, - "description":"nice", - "allowableValues": { - "valueType":"LIST", - "values":["1","2","3"] - } - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (false) - p.description should be (Some("nice")) - p.allowableValues match { - case e: AllowableListValues => e.values should be (List("1","2","3")) - case _ => fail("expected allowable values") - } - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property with allowable values" in { - val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b"))) - write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]}}""") - } - - it should "deserialize a model property" in { - val jsonString = """ - { - "type":"string", - "required":true, - "description":"nice" - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (true) - p.description should be (Some("nice")) - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property" in { - val p = ModelProperty("string", "string", 0, false, Some("nice")) - write(p) should be ("""{"type":"string","required":false,"description":"nice"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class AllowableValuesValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize allowable value list" in { - val allowableValuesListString = """ - { - "valueType":"LIST", - "values":["1","2","3"] - } - """ - val json = parse(allowableValuesListString) - json.extract[AllowableValues] match { - case avl: AllowableListValues => { - avl.valueType should be ("LIST") - avl.values should be (List("1","2","3")) - } - } - } - - it should "serialize allowable values list" in { - val l = AllowableListValues(List("1","2","3")) - write(l) should be ("""{"valueType":"LIST","values":["1","2","3"]}""") - } - - it should "deserialize allowable values range" in { - val allowableValuesRangeString = """ - { - "valueType":"RANGE", - "min":"abc", - "max":3 - } - """ - val json = parse(allowableValuesRangeString) - json.extract[AllowableValues] match { - case avr: AllowableRangeValues => { - avr.min should be ("abc") - avr.max should be ("3") - } - case _ => fail("wrong type returned, should be AllowabeValuesList") - } - } - - it should "serialize allowable values range" in { - val l = AllowableRangeValues("-1", "3") - write(l) should be ("""{"valueType":"RANGE","min":"-1","max":"3"}""") - } -} \ No newline at end of file diff --git a/src/test/scala/swaggerSpec1_1/ModelSerializersTest.scala b/src/test/scala/swaggerSpec1_1/ModelSerializersTest.scala deleted file mode 100644 index 37aadfbe4762..000000000000 --- a/src/test/scala/swaggerSpec1_1/ModelSerializersTest.scala +++ /dev/null @@ -1,641 +0,0 @@ -package swaggerSpec1_1 - -import com.wordnik.swagger.codegen.model._ - -import org.json4s._ -import org.json4s.JsonDSL._ -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.{read, write} - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.collection.mutable.LinkedHashMap - -@RunWith(classOf[JUnitRunner]) -class ResourceListingSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize an ResourceListing with no apis" in { - val jsonString = """ - { - "apiVersion":"1.2.3", - "swaggerVersion":"1.1", - "basePath":"http://foo/bar" - } - """ - val json = parse(jsonString) - json.extract[ResourceListing] match { - case p: ResourceListing => { - p.apiVersion should be ("1.2.3") - p.swaggerVersion should be ("1.1") - p.basePath should be ("http://foo/bar") - p.apis.size should be (0) - } - case _ => fail("wrong type returned, should be ResourceListing") - } - } - - it should "serialize an ApiListingReference with no apis" in { - val l = ApiListingReference("/foo/bar", Some("the description")) - write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") - } - - it should "deserialize an ResourceListing" in { - val jsonString = """ - { - "apiVersion":"1.2.3", - "swaggerVersion":"1.1", - "basePath":"http://foo/bar", - "apis":[ - { - "path":"/a/b", - "description":"path ab apis" - },{ - "path":"/c", - "description":"path c apis" - } - ] - } - """ - val json = parse(jsonString) - json.extract[ResourceListing] match { - case p: ResourceListing => { - p.apiVersion should be ("1.2.3") - p.swaggerVersion should be ("1.1") - p.basePath should be ("http://foo/bar") - p.apis.size should be (2) - } - case _ => fail("wrong type returned, should be ResourceListing") - } - } - - it should "serialize an ApiListingReference" in { - val l = ApiListingReference("/foo/bar", Some("the description")) - write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ApiListingReferenceSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize an ApiListingReference" in { - val jsonString = """ - { - "path":"/foo/bar", - "description":"the description" - } - """ - val json = parse(jsonString) - json.extract[ApiListingReference] match { - case p: ApiListingReference => { - p.path should be ("/foo/bar") - p.description should be (Some("the description")) - } - case _ => fail("wrong type returned, should be ApiListingReference") - } - } - - it should "serialize an ApiListingReference" in { - val l = ApiListingReference("/foo/bar", Some("the description")) - write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ApiDescriptionSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize an ApiDescription with no ops" in { - val jsonString = """ - { - "path":"/foo/bar", - "description":"the description" - } - """ - val json = parse(jsonString) - json.extract[ApiDescription] match { - case p: ApiDescription => { - p.path should be ("/foo/bar") - p.description should be (Some("the description")) - p.operations.size should be (0) - } - case _ => fail("wrong type returned, should be ApiDescription") - } - } - - it should "serialize an ApiDescription with no operations" in { - val l = ApiDescription("/foo/bar", Some("the description")) - write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") - } - - it should "deserialize an ApiDescription" in { - val jsonString = """ - { - "path":"/foo/bar", - "description":"the description", - "operations":[ - { - "method":"GET", - "summary":"the summary", - "notes":"the notes", - "responseClass":"string", - "nickname":"getMeSomeStrings", - "parameters":[ - { - "name":"id", - "description":"the id", - "defaultValue":"-1", - "required":false, - "allowMultiple":true, - "dataType":"string", - "allowableValues":{ - "valueType":"LIST", - "values":["a","b","c"] - }, - "paramType":"query" - } - ] - } - ] - } - """ - val json = parse(jsonString) - json.extract[ApiDescription] match { - case p: ApiDescription => { - p.path should be ("/foo/bar") - p.description should be (Some("the description")) - p.operations.size should be (1) - p.operations.foreach(op => { - op.method should be ("GET") - op.summary should be ("the summary") - op.notes should be ("the notes") - op.responseClass should be ("string") - op.nickname should be ("getMeSomeStrings") - op.parameters.size should be (1) - - op.parameters.foreach(m => { - m.name should be ("id") - m.description should be (Some("the id")) - m.defaultValue should be (Some("-1")) - m.required should be (false) - m.allowMultiple should be (true) - m.dataType should be ("string") - m.paramType should be ("query") - }) - }) - } - case _ => fail("wrong type returned, should be ApiDescription") - } - } - - it should "serialize an ApiDescription" in { - val l = ApiDescription( - "/foo/bar", - Some("the description"), - List(Operation( - "get", - "the summary", - "the notes", - "string", - "getMeSomeStrings", - 0, - List.empty, - List.empty, - List.empty, - List.empty, - List(Parameter("id", Some("the id"), Some("-1"), false, true, "string", AllowableListValues(List("a","b","c")), "query")) - )) - ) - write(l) should be ("""{"path":"/foo/bar","description":"the description","operations":[{"method":"get","summary":"the summary","notes":"the notes","responseClass":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"dataType":"string","allowableValues":{"valueType":"LIST","values":["a","b","c"]},"paramType":"query"}]}]}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class OperationSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize an Operation" in { - val jsonString = """ - { - "method":"GET", - "summary":"the summary", - "notes":"the notes", - "responseClass":"string", - "nickname":"getMeSomeStrings", - "parameters":[ - { - "name":"id", - "description":"the id", - "defaultValue":"-1", - "required":false, - "allowMultiple":true, - "dataType":"string", - "allowableValues":{ - "valueType":"LIST", - "values":["a","b","c"] - }, - "paramType":"query" - } - ] - } - """ - val json = parse(jsonString) - json.extract[Operation] match { - case op: Operation => { - op.method should be ("GET") - op.summary should be ("the summary") - op.notes should be ("the notes") - op.responseClass should be ("string") - op.nickname should be ("getMeSomeStrings") - op.parameters.size should be (1) - - op.parameters.foreach(m => { - m.name should be ("id") - m.description should be (Some("the id")) - m.defaultValue should be (Some("-1")) - m.required should be (false) - m.allowMultiple should be (true) - m.dataType should be ("string") - m.paramType should be ("query") - }) - } - case _ => fail("wrong type returned, should be Operation") - } - } - - it should "serialize an operation" in { - val op = Operation( - "get", - "the summary", - "the notes", - "string", - "getMeSomeStrings", - 0, - List.empty, - List.empty, - List.empty, - List.empty, - List(Parameter("id", Some("the id"), Some("-1"), false, true, "string", AllowableListValues(List("a","b","c")), "query")) - ) - write(op) should be ("""{"method":"get","summary":"the summary","notes":"the notes","responseClass":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"dataType":"string","allowableValues":{"valueType":"LIST","values":["a","b","c"]},"paramType":"query"}]}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ErrorResponseSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize an ResponseResponse" in { - val jsonString = """ - { - "code":101, - "reason":"the reason" - } - """ - val json = parse(jsonString) - json.extract[ResponseMessage] match { - case p: ResponseMessage => { - p.code should be (101) - p.message should be ("the reason") - } - case _ => fail("wrong type returned, should be ResponseMessage") - } - } - - it should "serialize an operation" in { - val l = ResponseMessage(101, "the message") - write(l) should be ("""{"code":101,"message":"the message"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ParameterSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize another param" in { - val jsonString = """ - { - "name":"includeDuplicates", - "defaultValue":"false", - "description":"Show duplicate examples from different sources", - "required":"false", - "allowableValues":{ - "values":[ - false, - true - ], - "valueType":"LIST" - }, - "dataType":"string", - "allowMultiple":false, - "paramType":"query" - } - """ - val json = parse(jsonString) - json.extract[Parameter] match { - case p: Parameter => { - p.name should be ("includeDuplicates") - p.description should be (Some("Show duplicate examples from different sources")) - p.defaultValue should be (Some("false")) - p.required should be (false) - p.allowMultiple should be (false) - p.dataType should be ("string") - p.paramType should be ("query") - } - case _ => fail("wrong type returned, should be Parameter") - } - } - - it should "deserialize a parameter" in { - val jsonString = """ - { - "name":"name", - "description":"description", - "defaultValue":"tony", - "required":false, - "allowMultiple":true, - "dataType":"string", - "paramType":"query" - } - """ - val json = parse(jsonString) - json.extract[Parameter] match { - case p: Parameter => { - p.name should be ("name") - p.description should be (Some("description")) - p.defaultValue should be (Some("tony")) - p.required should be (false) - p.allowMultiple should be (true) - p.dataType should be ("string") - p.paramType should be ("query") - } - case _ => fail("wrong type returned, should be Parameter") - } - } - - it should "serialize a parameter" in { - val l = Parameter("name", Some("description"), Some("tony"), false, true, "string", AnyAllowableValues, "query") - write(l) should be ("""{"name":"name","description":"description","defaultValue":"tony","required":false,"allowMultiple":true,"dataType":"string","paramType":"query"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelSerializationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize a model" in { - val jsonString = """ - { - "id":"Foo", - "name":"Bar", - "properties": { - "id": { - "type":"string", - "required":true, - "description":"id" - }, - "name": { - "type":"string", - "required":false, - "description":"name" - }, - "tags": { - "type":"Array", - "items": { - "type":"string" - } - } - }, - "description":"nice model" - } - """ - val json = parse(jsonString) - json.extract[Model] match { - case model: Model => { - model.id should be ("Foo") - model.name should be ("Bar") - model.properties should not be (null) - model.properties.size should be (3) - model.description should be (Some("nice model")) - model.properties("id") match { - case e: ModelProperty => { - e.`type` should be ("string") - e.required should be (true) - e.description should be (Some("id")) - } - case _ => fail("missing property id") - } - model.properties("name") match { - case e: ModelProperty => { - e.`type` should be ("string") - e.required should be (false) - e.description should be (Some("name")) - } - case _ => fail("missing property name") - } - - model.properties("tags") match { - case e: ModelProperty => { - e.`type` should be ("Array") - e.required should be (false) - e.items match { - case Some(items) => items.`type` should be ("string") - case _ => fail("didn't find ref for Array") - } - } - case _ => fail("missing property name") - } - } - case _ => fail("expected type Model") - } - } - - it should "serialize a model" in { - val ref = Model("Foo", "Bar", "Bar", (LinkedHashMap("s" -> ModelProperty("string", "string", 0, true, Some("a string"))))) - write(ref) should be ("""{"id":"Foo","name":"Bar","properties":{"s":{"type":"string","required":true,"description":"a string"}}}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelRefSerializationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize a model ref" in { - val jsonString = """ - { - "$ref":"Foo", - "type":"Bar" - } - """ - val json = parse(jsonString) - json.extract[ModelRef] match { - case p: ModelRef => { - p.ref should be (Some("Foo")) - p.`type` should be ("Bar") - } - case _ => fail("expected type ModelRef") - } - } - - it should "serialize a model ref" in { - val ref = ModelRef("Foo", Some("Bar")) - write(ref) should be ("""{"type":"Foo","$ref":"Bar"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelPropertySerializationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize a model property with allowable values and ref" in { - val jsonString = """ - { - "type":"string", - "required":false, - "description":"nice", - "allowableValues": { - "valueType":"LIST", - "values":["1","2","3"] - }, - "items":{ - "type":"Foo", - "$ref":"Bar" - } - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (false) - p.description should be (Some("nice")) - p.allowableValues match { - case e: AllowableListValues => e.values should be (List("1","2","3")) - case _ => fail("expected allowable values") - } - p.items match { - case Some(e: ModelRef) => { - e.`type` should be ("Foo") - e.ref should be (Some("Bar")) - } - case _ => fail("expected type ModelProperty") - } - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property with allowable values and ref" in { - val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b")),Some(ModelRef("Foo",Some("Bar")))) - write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]},"items":{"type":"Foo","$ref":"Bar"}}""") - } - - it should "deserialize a model property with allowable values" in { - val jsonString = """ - { - "type":"string", - "required":false, - "description":"nice", - "allowableValues": { - "valueType":"LIST", - "values":["1","2","3"] - } - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (false) - p.description should be (Some("nice")) - p.allowableValues match { - case e: AllowableListValues => e.values should be (List("1","2","3")) - case _ => fail("expected allowable values") - } - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property with allowable values" in { - val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b"))) - write(p) should be ("""{"type":"string","required":false,"description":"nice","allowableValues":{"valueType":"LIST","values":["a","b"]}}""") - } - - it should "deserialize a model property" in { - val jsonString = """ - { - "type":"string", - "required":true, - "description":"nice" - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (true) - p.description should be (Some("nice")) - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property" in { - val p = ModelProperty("string", "string", 0, false, Some("nice")) - write(p) should be ("""{"type":"string","required":false,"description":"nice"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class AllowableValuesSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - it should "deserialize allowable value list" in { - val allowableValuesListString = """ - { - "valueType":"LIST", - "values":["1","2","3"] - } - """ - val json = parse(allowableValuesListString) - json.extract[AllowableValues] match { - case avl: AllowableListValues => { - avl.valueType should be ("LIST") - avl.values should be (List("1","2","3")) - } - } - } - - it should "serialize allowable values list" in { - val l = AllowableListValues(List("1","2","3")) - write(l) should be ("""{"valueType":"LIST","values":["1","2","3"]}""") - } - - it should "deserialize allowable values range" in { - val allowableValuesRangeString = """ - { - "valueType":"RANGE", - "min":"abc", - "max":3 - } - """ - val json = parse(allowableValuesRangeString) - json.extract[AllowableValues] match { - case avr: AllowableRangeValues => { - avr.min should be ("abc") - avr.max should be ("3") - } - case _ => fail("wrong type returned, should be AllowabeValuesList") - } - } - - it should "serialize allowable values range" in { - val l = AllowableRangeValues("-1", "3") - write(l) should be ("""{"valueType":"RANGE","min":"-1","max":"3"}""") - } -} \ No newline at end of file diff --git a/src/test/scala/swaggerSpec1_1/SwaggerModelTest.scala b/src/test/scala/swaggerSpec1_1/SwaggerModelTest.scala deleted file mode 100644 index 2c2993028fca..000000000000 --- a/src/test/scala/swaggerSpec1_1/SwaggerModelTest.scala +++ /dev/null @@ -1,171 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 swaggerSpec1_1 - -import com.wordnik.swagger.codegen.model._ - -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.read - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.io._ - -@RunWith(classOf[JUnitRunner]) -class SwaggerModelTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.1") - - behavior of "Swagger Model" - - it should "deserialize ResourceListing" in { - val json = Source.fromFile("src/test/resources/petstore-1.1/resources.json").mkString - val listing = parse(json).extract[ResourceListing] - - listing.apiVersion should be ("0.2") - listing.swaggerVersion should be ("1.1") - listing.basePath should be ("http://petstore.swagger.wordnik.com/api") - listing.apis.size should be (3) - - val apis = listing.apis.map(api => (api.path, api.description)).toMap - - apis("/store.{format}") should be (Some("Operations about store")) - apis("/pet.{format}") should be (Some("Operations about pets")) - apis("/user.{format}") should be (Some("Operations about user")) - } - - it should "deserialize ApiListing" in { - val json = Source.fromFile("src/test/resources/petstore-1.1/pet.json").mkString - val apiListing = parse(json).extract[ApiListing] - - apiListing.apiVersion should be ("0.2") - apiListing.swaggerVersion should be ("1.1") - apiListing.basePath should be ("http://petstore.swagger.wordnik.com/api") - apiListing.resourcePath should be ("/pet") - apiListing.apis.size should be (4) - apiListing.models.isDefined should be (true) - apiListing.models.get.size should be (3) - - val apiMap = apiListing.apis.map(api => (api.path, api)).toMap - val petBaseApi = apiMap("/pet.{format}/{petId}") - petBaseApi.description should be (Some("Operations about pets")) - petBaseApi.operations.size should be (1) - - val getPetById = petBaseApi.operations.head - getPetById.method should be ("GET") - getPetById.summary should be ("Find pet by ID") - getPetById.notes should be ("Returns a pet based on ID") - getPetById.responseClass should be ("Pet") - - getPetById.nickname should be ("getPetById") - getPetById.parameters.size should be (1) - - val param = getPetById.parameters.head - param.name should be ("petId") - param.description should be (Some("ID of pet that needs to be fetched")) - param.paramType should be ("path") - param.required should be (true) - param.allowMultiple should be (false) - param.dataType should be ("string") - - getPetById.responseMessages.size should be (2) - val errors = getPetById.responseMessages.map(response => (response.code, response.message)).toMap - - errors(400) should be ("Invalid ID supplied") - errors(404) should be ("Pet not found") - } - - it should "deserialize ApiListing with AllowableValues" in { - val json = Source.fromFile("src/test/resources/petstore-1.1/pet.json").mkString - val apiListing = parse(json).extract[ApiListing] - val apiMap = apiListing.apis.map(api => (api.path, api)).toMap - val petBaseApi = apiMap("/pet.{format}/findByStatus") - val findPetsByStatus = petBaseApi.operations.head - val param = findPetsByStatus.parameters.head - - param.name should be ("status") - param.description should be (Some("Status values that need to be considered for filter")) - param.paramType should be ("query") - param.required should be (true) - param.allowMultiple should be (true) - param.dataType should be ("string") - param.allowableValues should not be (null) - - param.allowableValues.isInstanceOf[AllowableListValues] should be (true) - val allowableValues = param.allowableValues.asInstanceOf[AllowableListValues] - allowableValues.valueType should be ("LIST") - allowableValues.values.size should be (3) - (allowableValues.values.toSet & Set("available", "pending", "sold")).size should be (3) - } - - it should "maintain model property order when deserializing" in { - val json = Source.fromFile("src/test/resources/petstore-1.1/pet.json").mkString - val apiListing = parse(json).extract[ApiListing] - - val modelsOpt = apiListing.models - modelsOpt.isDefined should be (true) - val models = modelsOpt.get - models.size should be (3) - val pet = models("Pet") - - val petProperties = pet.properties.toList - - petProperties.size should be (6) - petProperties(0)._1 should be ("tags") - petProperties(1)._1 should be ("id") - petProperties(2)._1 should be ("category") - petProperties(3)._1 should be ("status") - petProperties(4)._1 should be ("name") - petProperties(5)._1 should be ("photoUrls") - } - - it should "deserialize models" in { - val json = Source.fromFile("src/test/resources/petstore-1.1/pet.json").mkString - val apiListing = parse(json).extract[ApiListing] - - val modelsOpt = apiListing.models - modelsOpt.isDefined should be (true) - val models = modelsOpt.get - models.size should be (3) - - val pet = models("Pet") - pet.id should be ("Pet") - pet.properties.size should be (6) - - val properties = pet.properties - val tags = properties("tags") - tags.`type` should be ("Array") - tags.items should not be (None) - tags.items.get.ref should be (Some("Tag")) - - val id = properties("id") - // id.`type` shoud be ("long") - - val category = properties("category") - category.`type` should be ("Category") - - val status = properties("status") - status.`type` should be ("string") - status.description should be (Some("pet status in the store")) - status.allowableValues should not be (null) - status.allowableValues.isInstanceOf[AllowableListValues] should be (true) - val allowableValues = status.allowableValues.asInstanceOf[AllowableListValues] - allowableValues.valueType should be ("LIST") - (allowableValues.values.toSet & Set("available", "pending", "sold")).size should be (3) - } -} diff --git a/src/test/scala/swaggerSpec1_1/UtilsTest.scala b/src/test/scala/swaggerSpec1_1/UtilsTest.scala deleted file mode 100644 index c8bf3914e6f0..000000000000 --- a/src/test/scala/swaggerSpec1_1/UtilsTest.scala +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 swaggerSpec1_1 - -import com.wordnik.swagger.codegen.model._ -import com.wordnik.swagger.codegen.util.{ResourceExtractor, ApiExtractor, CoreUtils} - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.collection.JavaConverters._ -import scala.beans.BeanProperty - -@RunWith(classOf[JUnitRunner]) -class ResourceExtractorTest extends FlatSpec with Matchers { - behavior of "ResourceExtractor" - it should "get 3 apis from a resource listing" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.1/resources.json") - resourceListing should not be(null) - resourceListing.apis.size should be (3) - } -} - -@RunWith(classOf[JUnitRunner]) -class ApiExtractorTest extends FlatSpec with Matchers { - behavior of "ApiExtractor" - it should "verify the deserialization of the store api" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.1/resources.json") - val docs = ApiExtractor.extractApiOperations(resourceListing.swaggerVersion, "src/test/resources/petstore-1.1", resourceListing.apis) - - val m = docs.map(t => (t.resourcePath, t)).toMap - val storeApi = m("/store") - - storeApi should not be (null) - storeApi.apis.size should be (2) - - val f = storeApi.apis.map(m => (m.path, m)).toMap - (f.keys.toSet & Set("/store.{format}/order/{orderId}","/store.{format}/order")).size should be (2) - - val storeOps = f("/store.{format}/order/{orderId}") - val ops = storeOps.operations.map(o => (o.nickname, o)).toMap - val getOrderById = ops("getOrderById") - - getOrderById should not be null - - getOrderById.method should be ("GET") - getOrderById.parameters.size should be (1) - getOrderById.responseMessages.size should be (2) - } -} diff --git a/src/test/scala/swaggerSpec1_2/CoreUtilsTest.scala b/src/test/scala/swaggerSpec1_2/CoreUtilsTest.scala deleted file mode 100644 index bb83b56c461c..000000000000 --- a/src/test/scala/swaggerSpec1_2/CoreUtilsTest.scala +++ /dev/null @@ -1,267 +0,0 @@ -package swaggerSpec1_2 - -import com.wordnik.swagger.codegen.util.CoreUtils - -import com.wordnik.swagger.codegen.model._ -import com.wordnik.swagger.codegen.util._ - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.read - -import scala.collection.mutable.LinkedHashMap - -@RunWith(classOf[JUnitRunner]) -class CoreUtilsTest extends FlatSpec with Matchers { - sys.props += "fileMap" -> "src/test/resources/petstore-1.2" - - behavior of "CoreUtils" - - it should "verify models are extracted" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.2/api-docs") - val apis = ApiExtractor.extractApiOperations(resourceListing.swaggerVersion, "src/test/resources/petstore-1.2", resourceListing.apis) - - val cu = CoreUtils.extractAllModels(apis) - cu.size should be (5) - - (cu.keys.toSet & Set("User", "Tag", "Pet", "Category", "Order")).size should be (5) - } - - it should "verify operation names" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.2/api-docs") - val apis = ApiExtractor.extractApiOperations(resourceListing.swaggerVersion, "src/test/resources/petstore-1.2", resourceListing.apis) - - val petApi = apis.filter(api => api.resourcePath == "/pet").head - val eps = petApi.apis.map(api => (api.path, api)).toMap - val ops = eps("/pet").operations.map(ep => (ep.nickname, ep)).toMap - - ops.size should be (2) - - (ops.keys.toSet & Set("addPet", "updatePet")).size should be (2) - } - - it should "find required models" in { - val apis = CoreUtilsTest.sampleApis1 - val models = CoreUtils.extractApiModels(apis.head) - models.size should be (5) - } - - it should "find required models from a nested list" in { - val apis = CoreUtilsTest.sampleApis2 - val models = CoreUtils.extractApiModels(apis.head) - models.size should be (5) - } -} - -object CoreUtilsTest { - implicit val formats = SwaggerSerializers.formats("1.1") - - def sampleApis1 = { - parse(""" -[ - { - "apiVersion": "0.2", - "swaggerVersion": "1.1", - "basePath": "http://api.helloreverb.com/api", - "resourcePath": "/mysteries", - "apis": [ - { - "path": "/mysteries.{format}/{petId}", - "description": "As the name suggests", - "operations": [ - { - "httpMethod": "GET", - "summary": "You find amazing htings here", - "responseClass": "DeepMystery", - "nickname": "getMysteryById", - "parameters": [ - { - "name": "id", - "description": "ID of mystery", - "paramType": "path", - "required": true, - "allowMultiple": false, - "dataType": "string" - } - ] - } - ] - } - ], - "models": { - "MysteryList": { - "id": "MysteryList", - "properties": { - "id": { - "type": "long" - }, - "mysteries": { - "items":{ - "$ref":"Mystery1" - }, - "type":"Array" - } - } - }, - "DeepMystery": { - "id": "DeepMystery", - "properties": { - "id": { - "type": "Mystery1" - }, - "name": { - "type": "string" - } - } - }, - "Mystery1": { - "id": "Mystery1", - "properties": { - "mystery2": { - "type": "Mystery2" - }, - "name": { - "type": "string" - } - } - }, - "Mystery2": { - "id": "Mystery2", - "properties": { - "mystery3": { - "type": "Mystery3" - }, - "name": { - "type": "string" - } - } - }, - "Mystery3": { - "id": "Mystery3", - "properties": { - "mystery4": { - "type": "Mystery4" - }, - "name": { - "type": "string" - } - } - }, - "Mystery4": { - "id": "Mystery4", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - } - } - } - } -] - """).extract[List[ApiListing]] - } - - def sampleApis2 = { - parse(""" -[ - { - "apiVersion": "0.2", - "swaggerVersion": "1.1", - "basePath": "http://api.helloreverb.com/api", - "resourcePath": "/mysteries", - "apis": [ - { - "path": "/mysteries/{petId}", - "description": "As the name suggests", - "operations": [ - { - "httpMethod": "GET", - "summary": "You find amazing htings here", - "responseClass": "MysteryList", - "nickname": "getMysteryById", - "parameters": [ - { - "name": "id", - "description": "ID of mystery", - "paramType": "path", - "required": true, - "allowMultiple": false, - "dataType": "string" - } - ] - } - ] - } - ], - "models": { - "MysteryList": { - "id": "MysteryList", - "properties": { - "id": { - "type": "long" - }, - "mystery1": { - "type":"Mystery1" - } - } - }, - "Mystery1": { - "id": "Mystery1", - "properties": { - "mystery2": { - "type": "Mystery2" - }, - "name": { - "type": "string" - } - } - }, - "Mystery2": { - "id": "Mystery2", - "properties": { - "mystery3List": { - "items": { - "$ref": "Mystery3" - }, - "type": "List" - }, - "name": { - "type": "string" - } - } - }, - "Mystery3": { - "id": "Mystery3", - "properties": { - "mystery4": { - "type": "Mystery4" - }, - "name": { - "type": "string" - } - } - }, - "Mystery4": { - "id": "Mystery4", - "properties": { - "id": { - "type": "string" - }, - "name": { - "type": "string" - } - } - } - } - } -] - """).extract[List[ApiListing]] - } -} \ No newline at end of file diff --git a/src/test/scala/swaggerSpec1_2/ModelSerializerValidations.scala b/src/test/scala/swaggerSpec1_2/ModelSerializerValidations.scala deleted file mode 100644 index a5e495f37f80..000000000000 --- a/src/test/scala/swaggerSpec1_2/ModelSerializerValidations.scala +++ /dev/null @@ -1,542 +0,0 @@ -package swaggerSpec1_2 - -import com.wordnik.swagger.codegen.model._ - -import org.json4s._ -import org.json4s.JsonDSL._ -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.{read, write} - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.collection.mutable.{ LinkedHashMap, ListBuffer } - -@RunWith(classOf[JUnitRunner]) -class ResourceListingValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "not have base path" in { -// SwaggerSerializers.validationMessages.clear - val jsonString = """ - { - "apiVersion":"1.2.3", - "swaggerVersion":"1.1" - } - """ - val listing = parse(jsonString).extract[ResourceListing] - val errors = SwaggerValidator.validate(listing) - errors.size should be (0) - } - - it should "fail resource listing without apiVersion" in { -// SwaggerSerializers.validationMessages.clear - val jsonString = """ - { - "basePath": "http://foo.com", - "swaggerVersion":"1.2" - } - """ - val listing = parse(jsonString).extract[ResourceListing] - val errors = SwaggerValidator.validate(listing) - errors.size should be (1) - } - - it should "fail with missing paths in a ResourceListing" in { - val jsonString = """ - { - "apiVersion":"1.2.3", - "swaggerVersion":"1.2", - "apis":[ - { - "description":"path ab apis" - }, - { - "path":"/c", - "description":"path c apis" - } - ] - } - """ - parse(jsonString).extract[ResourceListing] match { - case e: ResourceListing => { - e.apis.size should be (1) - val errors = SwaggerValidator.validate(e) - errors.size should be (0) - } - case _ => fail("didn't parse the underlying apis") - } - } -} - -@RunWith(classOf[JUnitRunner]) -class ApiListingReferenceValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize an ApiListingReference" in { -// SwaggerSerializers.validationMessages.clear - val jsonString = """ - { - "description":"the description" - } - """ - parse(jsonString).extract[ApiListingReference] match { - case p: ApiListingReference => { - p.description should be (Some("the description")) - val errors = new ListBuffer[ValidationError] - SwaggerValidator.validate(p, errors, "") - errors.size should be (1) - } - case _ => fail("wrong type returned, should be ApiListingReference") - } - } - - it should "serialize an ApiListingReference" in { - val l = ApiListingReference("/foo/bar", Some("the description")) - write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ApiDescriptionValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "fail to deserialize an ApiDescription with path, method, return type" in { -// SwaggerSerializers.validationMessages.clear - val jsonString = """ - { - "description":"the description", - "operations":[ - { - "summary":"the summary", - "notes":"the notes", - "nickname":"getMeSomeStrings", - "parameters":[ - { - "name":"id", - "description":"the id", - "defaultValue":"-1", - "required":false, - "allowMultiple":true, - "type":"string", - "enum":["a","b","c"], - "paramType":"query" - } - ] - } - ] - } - """ - parse(jsonString).extract[ApiDescription] match { - case p: ApiDescription => { - val errors = new ListBuffer[ValidationError] - SwaggerValidator.validate(p, errors, "") - errors.size should be (3) - } - case _ => fail("wrong type returned, should be ApiDescription") - } - } -} - -@RunWith(classOf[JUnitRunner]) -class OperationValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "fail to deserialize an Operation with missing param type" in { -// SwaggerSerializers.validationMessages.clear - val jsonString = """ - { - "httpMethod":"GET", - "summary":"the summary", - "notes":"the notes", - "type":"string", - "nickname":"getMeSomeStrings", - "parameters":[ - { - "name":"id", - "description":"the id", - "defaultValue":"-1", - "required":false, - "allowMultiple":true, - "type":"string", - "enum":["a","b","c"] - } - ] - } - """ - val json = parse(jsonString) - json.extract[Operation] match { - case op: Operation => { - val errors = new ListBuffer[ValidationError] - SwaggerValidator.validate(op, errors, "") - errors.size should be (1) - } - case _ => fail("wrong type returned, should be Operation") - } - } - - it should "serialize an operation" in { - val op = Operation( - "get", - "the summary", - "the notes", - "string", - "getMeSomeStrings", - 0, - List.empty, - List.empty, - List.empty, - List.empty, - List(Parameter("id", Some("the id"), Some("-1"), false, true, "string", AllowableListValues(List("a","b","c")), "query")) - ) - write(op) should be ("""{"method":"get","summary":"the summary","notes":"the notes","type":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"type":"string","paramType":"query","enum":["a","b","c"]}]}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ResponseMessageValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize an ResponseMessage" in { - val jsonString = """ - { - "code":101, - "message":"the message" - } - """ - val json = parse(jsonString) - json.extract[ResponseMessage] match { - case p: ResponseMessage => { - p.code should be (101) - p.message should be ("the message") - } - case _ => fail("wrong type returned, should be ResponseMessage") - } - } - - it should "serialize an operation" in { - val l = ResponseMessage(101, "the message") - write(l) should be ("""{"code":101,"message":"the message"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ParameterValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize another param" in { - val jsonString = """ - { - "name":"includeDuplicates", - "defaultValue":"false", - "description":"Show duplicate examples from different sources", - "required":"false", - "enum":[ - false, - true - ], - "type":"string", - "allowMultiple":false, - "paramType":"query" - } - """ - val json = parse(jsonString) - json.extract[Parameter] match { - case p: Parameter => { - p.name should be ("includeDuplicates") - p.description should be (Some("Show duplicate examples from different sources")) - p.defaultValue should be (Some("false")) - p.required should be (false) - p.allowMultiple should be (false) - p.dataType should be ("string") - p.paramType should be ("query") - } - case _ => fail("wrong type returned, should be Parameter") - } - } - - it should "deserialize a parameter" in { - val jsonString = """ - { - "name":"name", - "description":"description", - "defaultValue":"tony", - "required":false, - "allowMultiple":true, - "type":"string", - "paramType":"query" - } - """ - val json = parse(jsonString) - json.extract[Parameter] match { - case p: Parameter => { - p.name should be ("name") - p.description should be (Some("description")) - p.defaultValue should be (Some("tony")) - p.required should be (false) - p.allowMultiple should be (true) - p.dataType should be ("string") - p.paramType should be ("query") - } - case _ => fail("wrong type returned, should be Parameter") - } - } - - it should "serialize a parameter" in { - val l = Parameter("name", Some("description"), Some("tony"), false, true, "string", AnyAllowableValues, "query") - write(l) should be ("""{"name":"name","description":"description","defaultValue":"tony","required":false,"allowMultiple":true,"type":"string","paramType":"query"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize a model" in { - val jsonString = """ - { - "id":"Foo", - "name":"Bar", - "properties": { - "id": { - "type":"string", - "required":true, - "description":"id" - }, - "name": { - "type":"string", - "required":false, - "description":"name" - }, - "tags": { - "type":"Array", - "items": { - "type":"string" - } - } - }, - "description":"nice model" - } - """ - val json = parse(jsonString) - json.extract[Model] match { - case model: Model => { - model.id should be ("Foo") - model.name should be ("Bar") - model.properties should not be (null) - model.properties.size should be (3) - model.description should be (Some("nice model")) - model.properties("id") match { - case e: ModelProperty => { - e.`type` should be ("string") - e.required should be (true) - e.description should be (Some("id")) - } - case _ => fail("missing property id") - } - model.properties("name") match { - case e: ModelProperty => { - e.`type` should be ("string") - e.required should be (false) - e.description should be (Some("name")) - } - case _ => fail("missing property name") - } - - model.properties("tags") match { - case e: ModelProperty => { - e.`type` should be ("Array") - e.required should be (false) - e.items match { - case Some(items) => items.`type` should be ("string") - case _ => fail("didn't find ref for Array") - } - } - case _ => fail("missing property name") - } - } - case _ => fail("expected type Model") - } - } - - it should "serialize a model" in { - val ref = Model("Foo", "Bar", "Bar", (LinkedHashMap("s" -> ModelProperty("string", "string", 0, true, Some("a string"))))) - write(ref) should be ("""{"id":"Foo","name":"Bar","required":["s"],"properties":{"s":{"type":"string","description":"a string"}}}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelRefValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize a model ref" in { - val jsonString = """ - { - "$ref":"Foo", - "type":"Bar" - } - """ - val json = parse(jsonString) - json.extract[ModelRef] match { - case p: ModelRef => { - p.ref should be (Some("Foo")) - p.`type` should be ("Bar") - } - case _ => fail("expected type ModelRef") - } - } - - it should "serialize a model ref" in { - val ref = ModelRef("Foo", Some("Bar")) - write(ref) should be ("""{"type":"Foo","$ref":"Bar"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelPropertyValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize a model property with allowable values and ref" in { - val jsonString = """ - { - "type":"string", - "required":false, - "description":"nice", - "enum":["1","2","3"], - "items":{ - "type":"Foo", - "$ref":"Bar" - } - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (false) - p.description should be (Some("nice")) - p.allowableValues match { - case e: AllowableListValues => e.values should be (List("1","2","3")) - case _ => fail("expected allowable values") - } - p.items match { - case Some(e: ModelRef) => { - e.`type` should be ("Foo") - e.ref should be (Some("Bar")) - } - case _ => fail("expected type ModelProperty") - } - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property with allowable values and ref" in { - val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b")),Some(ModelRef("Foo",Some("Bar")))) - write(p) should be ("""{"type":"string","description":"nice","items":{"type":"Foo","$ref":"Bar"},"enum":["a","b"]}""") - } - - it should "deserialize a model property with allowable values" in { - val jsonString = """ - { - "type":"string", - "required":false, - "description":"nice", - "enum":["1","2","3"] - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (false) - p.description should be (Some("nice")) - p.allowableValues match { - case e: AllowableListValues => e.values should be (List("1","2","3")) - case _ => fail("expected allowable values") - } - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property with allowable values" in { - val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b"))) - write(p) should be ("""{"type":"string","description":"nice","enum":["a","b"]}""") - } - - it should "deserialize a model property" in { - val jsonString = """ - { - "type":"string", - "required":true, - "description":"nice" - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (true) - p.description should be (Some("nice")) - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property" in { - val p = ModelProperty("string", "string", 0, false, Some("nice")) - write(p) should be ("""{"type":"string","description":"nice"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class AllowableValuesValidationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize allowable value list" in { - val allowableValuesListString = """ - { - "valueType":"LIST", - "values":["1","2","3"] - } - """ - val json = parse(allowableValuesListString) - json.extract[AllowableValues] match { - case avl: AllowableListValues => { - avl.valueType should be ("LIST") - avl.values should be (List("1","2","3")) - } - } - } - - it should "serialize allowable values list" in { - val l = AllowableListValues(List("1","2","3")) - write(l) should be ("""{"valueType":"LIST","values":["1","2","3"]}""") - } - - it should "deserialize allowable values range" in { - val allowableValuesRangeString = """ - { - "valueType":"RANGE", - "min":"abc", - "max":3 - } - """ - val json = parse(allowableValuesRangeString) - json.extract[AllowableValues] match { - case avr: AllowableRangeValues => { - avr.min should be ("abc") - avr.max should be ("3") - } - case _ => fail("wrong type returned, should be AllowabeValuesList") - } - } - - it should "serialize allowable values range" in { - val l = AllowableRangeValues("-1", "3") - write(l) should be ("""{"valueType":"RANGE","min":"-1","max":"3"}""") - } -} \ No newline at end of file diff --git a/src/test/scala/swaggerSpec1_2/ModelSerializersTest.scala b/src/test/scala/swaggerSpec1_2/ModelSerializersTest.scala deleted file mode 100644 index 758cc910f954..000000000000 --- a/src/test/scala/swaggerSpec1_2/ModelSerializersTest.scala +++ /dev/null @@ -1,877 +0,0 @@ -package swaggerSpec1_2 - -import com.wordnik.swagger.codegen.model._ - -import org.json4s._ -import org.json4s.JsonDSL._ -import org.json4s.jackson.JsonMethods._ -import org.json4s.jackson.Serialization.{read, write} - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.collection.mutable.LinkedHashMap - -@RunWith(classOf[JUnitRunner]) -class ResourceListingSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize an ResourceListing with no apis" in { - val jsonString = """ - { - "apiVersion":"1.2.3", - "swaggerVersion":"1.2" - } - """ - val json = parse(jsonString) - json.extract[ResourceListing] match { - case p: ResourceListing => { - p.apiVersion should be ("1.2.3") - p.swaggerVersion should be ("1.2") - p.apis.size should be (0) - p.authorizations.size should be (0) - } - case _ => fail("wrong type returned, should be ResourceListing") - } - } - - it should "deserialize an ResourceListing" in { - val jsonString = """ - { - "apiVersion":"1.2.3", - "swaggerVersion":"1.2", - "apis":[ - { - "path":"/a/b", - "description":"path ab apis" - },{ - "path":"/c", - "description":"path c apis" - } - ], - "authorizations": {} - } - """ - val json = parse(jsonString) - json.extract[ResourceListing] match { - case p: ResourceListing => { - p.apiVersion should be ("1.2.3") - p.swaggerVersion should be ("1.2") - p.apis.size should be (2) - p.authorizations.size should be (0) - } - case _ => fail("wrong type returned, should be ResourceListing") - } - } - -} - -@RunWith(classOf[JUnitRunner]) -class ApiListingReferenceSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize an ApiListingReference" in { - val jsonString = """ - { - "path":"/foo/bar", - "description":"the description" - } - """ - val json = parse(jsonString) - json.extract[ApiListingReference] match { - case p: ApiListingReference => { - p.path should be ("/foo/bar") - p.description should be (Some("the description")) - } - case _ => fail("wrong type returned, should be ApiListingReference") - } - } - - it should "serialize an ApiListingReference" in { - val l = ApiListingReference("/foo/bar", Some("the description")) - write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ApiListingSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize an ApiListing" in { - val jsonString = """ - { - "apiVersion":"1.2.3", - "swaggerVersion":"1.2", - "basePath": "/foo/bar", - "resourcePath": "/a/b", - "produces": [ "application/json" ], - "authorizations": {}, - "apis": [] - } - """ - val json = parse(jsonString) - json.extract[ApiListing] match { - case p: ApiListing=> { - p.apiVersion should be ("1.2.3") - p.swaggerVersion should be ("1.2") - p.basePath should be ("/foo/bar") - p.resourcePath should be ("/a/b") - p.produces should be (List("application/json")) - p.authorizations.size should be (0) - p.models should be (None) - p.description should be (None) - p.position should be (0) - } - case _ => fail("wrong type returned, should be ApiListing") - } - } - - it should "serialize an ApiListing" in { - val l = ApiListing( - apiVersion = "1.2.3", - swaggerVersion = "1.2", - basePath = "/foo/bar", - resourcePath = "/a/b" - ) - write(l) should be ("""{"apiVersion":"1.2.3","resourcePath":"/a/b","swaggerVersion":"1.2","basePath":"/foo/bar"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ApiDescriptionSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - it should "deserialize an ApiDescription with no ops" in { - val jsonString = """ - { - "path":"/foo/bar", - "description":"the description" - } - """ - val json = parse(jsonString) - json.extract[ApiDescription] match { - case p: ApiDescription => { - p.path should be ("/foo/bar") - p.description should be (Some("the description")) - p.operations.size should be (0) - } - case _ => fail("wrong type returned, should be ApiDescription") - } - } - - it should "serialize an ApiDescription with no operations" in { - val l = ApiDescription("/foo/bar", Some("the description")) - write(l) should be ("""{"path":"/foo/bar","description":"the description"}""") - } - - it should "deserialize an ApiDescription" in { - val jsonString = """ - { - "path":"/foo/bar", - "description":"the description", - "operations":[ - { - "method":"GET", - "summary":"the summary", - "notes":"the notes", - "type":"string", - "nickname":"getMeSomeStrings", - "parameters":[ - { - "name":"id", - "description":"the id", - "defaultValue":"-1", - "required":false, - "allowMultiple":true, - "type":"string", - "enum":["a","b","c"], - "paramType":"query" - } - ], - "authorizations":{} - } - ] - } - """ - val json = parse(jsonString) - json.extract[ApiDescription] match { - case p: ApiDescription => { - p.path should be ("/foo/bar") - p.description should be (Some("the description")) - p.operations.size should be (1) - p.operations.foreach(op => { - op.method should be ("GET") - op.summary should be ("the summary") - op.notes should be ("the notes") - op.responseClass should be ("string") - op.nickname should be ("getMeSomeStrings") - op.parameters.size should be (1) - - op.parameters.foreach(m => { - m.name should be ("id") - m.description should be (Some("the id")) - m.defaultValue should be (Some("-1")) - m.required should be (false) - m.allowMultiple should be (true) - m.dataType should be ("string") - m.paramType should be ("query") - }) - op.authorizations.size should be (0) - }) - } - case _ => fail("wrong type returned, should be ApiDescription") - } - } - - it should "serialize an ApiDescription" in { - val l = ApiDescription( - "/foo/bar", - Some("the description"), - List(Operation( - "get", - "the summary", - "the notes", - "string", - "getMeSomeStrings", - 0, - List.empty, - List.empty, - List.empty, - List.empty, - List(Parameter("id", Some("the id"), Some("-1"), false, true, "string", AllowableListValues(List("a","b","c")), "query")) - )) - ) - write(l) should be ("""{"path":"/foo/bar","description":"the description","operations":[{"method":"get","summary":"the summary","notes":"the notes","type":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"type":"string","paramType":"query","enum":["a","b","c"]}]}]}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class OperationSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize an Operation" in { - val jsonString = """ - { - "method":"GET", - "summary":"the summary", - "notes":"the notes", - "type":"string", - "nickname":"getMeSomeStrings", - "parameters":[ - { - "name":"id", - "description":"the id", - "defaultValue":"-1", - "required":false, - "allowMultiple":true, - "type":"string", - "enum":["a","b","c"], - "paramType":"query" - } - ], - "authorizations":{} - } - """ - val json = parse(jsonString) - json.extract[Operation] match { - case op: Operation => { - op.method should be ("GET") - op.summary should be ("the summary") - op.notes should be ("the notes") - op.responseClass should be ("string") - op.nickname should be ("getMeSomeStrings") - op.parameters.size should be (1) - - op.parameters.foreach(m => { - m.name should be ("id") - m.description should be (Some("the id")) - m.defaultValue should be (Some("-1")) - m.required should be (false) - m.allowMultiple should be (true) - m.dataType should be ("string") - m.paramType should be ("query") - }) - op.authorizations.size should be (0) - } - case _ => fail("wrong type returned, should be Operation") - } - } - it should "deserialize an Operation with an array property" in { - val jsonString = """ - { - "method":"GET", - "summary":"the summary", - "notes":"the notes", - "type":"string", - "nickname":"getMeSomePets", - "parameters":[ - { - "name":"id", - "description":"the id", - "defaultValue":"-1", - "required":false, - "allowMultiple":true, - "type":"array", - "items": { - "$ref": "Pet" - }, - "enum":["a","b","c"], - "paramType":"query" - } - ] - } -""" - val json = parse(jsonString) - json.extract[Operation] match { - case op: Operation => { - op.method should be ("GET") - op.summary should be ("the summary") - op.notes should be ("the notes") - op.responseClass should be ("string") - op.nickname should be ("getMeSomePets") - op.parameters.size should be (1) - - op.parameters.foreach(m => { - m.name should be ("id") - m.description should be (Some("the id")) - m.defaultValue should be (Some("-1")) - m.required should be (false) - m.allowMultiple should be (true) - m.dataType should be ("Array[Pet]") - m.paramType should be ("query") - }) - } - case _ => fail("wrong type returned, should be Operation") - } - } - - it should "serialize an operation" in { - val op = Operation( - "get", - "the summary", - "the notes", - "string", - "getMeSomeStrings", - 0, - List.empty, - List.empty, - List.empty, - List.empty, - List(Parameter("id", Some("the id"), Some("-1"), false, true, "string", AllowableListValues(List("a","b","c")), "query")) - ) - write(op) should be ("""{"method":"get","summary":"the summary","notes":"the notes","type":"string","nickname":"getMeSomeStrings","parameters":[{"name":"id","description":"the id","defaultValue":"-1","required":false,"allowMultiple":true,"type":"string","paramType":"query","enum":["a","b","c"]}]}""") - } - - it should "deserialize an Operation with array" in { - val jsonString = """ - { - "method":"GET", - "summary":"the summary", - "notes":"the notes", - "type":"string", - "nickname":"getMeSomeStrings", - "parameters":[ - { - "name":"userId", - "description":"the id", - "defaultValue":"-1", - "required":false, - "type":"array", - "items": { - "format": "int64", - "type": "integer" - }, - "paramType":"query" - } - ] - } - """ - val json = parse(jsonString) - - json.extract[Operation] match { - case op: Operation => { - op.method should be ("GET") - op.summary should be ("the summary") - op.notes should be ("the notes") - op.responseClass should be ("string") - op.nickname should be ("getMeSomeStrings") - op.parameters.size should be (1) - - op.parameters.foreach(m => { - m.name should be ("userId") - m.description should be (Some("the id")) - m.defaultValue should be (Some("-1")) - m.required should be (false) - m.dataType should be ("Array[long]") - }) - } - case _ => fail("wrong type returned, should be Operation") - } - } -} - -@RunWith(classOf[JUnitRunner]) -class ErrorResponseSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize an Response" in { - val jsonString = """ - { - "code":101, - "message":"the message" - } - """ - val json = parse(jsonString) - json.extract[ResponseMessage] match { - case p: ResponseMessage => { - p.code should be (101) - p.message should be ("the message") - } - case _ => fail("wrong type returned, should be ResponseMessage") - } - } - - it should "serialize an operation" in { - val l = ResponseMessage(101, "the message") - write(l) should be ("""{"code":101,"message":"the message"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ParameterSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize another param" in { - val jsonString = """ - { - "name":"includeDuplicates", - "defaultValue":"false", - "description":"Show duplicate examples from different sources", - "required":"false", - "enum":[ - false, - true - ], - "type":"string", - "allowMultiple":false, - "paramType":"query" - } - """ - val json = parse(jsonString) - json.extract[Parameter] match { - case p: Parameter => { - p.name should be ("includeDuplicates") - p.description should be (Some("Show duplicate examples from different sources")) - p.defaultValue should be (Some("false")) - p.required should be (false) - p.allowMultiple should be (false) - p.dataType should be ("string") - p.paramType should be ("query") - } - case _ => fail("wrong type returned, should be Parameter") - } - } - - it should "deserialize a parameter" in { - val jsonString = """ - { - "name":"name", - "description":"description", - "defaultValue":"tony", - "required":false, - "allowMultiple":true, - "type":"string", - "paramType":"query" - } - """ - val json = parse(jsonString) - json.extract[Parameter] match { - case p: Parameter => { - p.name should be ("name") - p.description should be (Some("description")) - p.defaultValue should be (Some("tony")) - p.required should be (false) - p.allowMultiple should be (true) - p.dataType should be ("string") - p.paramType should be ("query") - } - case _ => fail("wrong type returned, should be Parameter") - } - } - - it should "serialize a parameter" in { - val l = Parameter("name", Some("description"), Some("tony"), false, true, "string", AnyAllowableValues, "query") - write(l) should be ("""{"name":"name","description":"description","defaultValue":"tony","required":false,"allowMultiple":true,"type":"string","paramType":"query"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelSerializationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize a model" in { - val jsonString = """ - { - "id":"Foo", - "name":"Bar", - "required": ["id"], - "properties": { - "id": { - "type":"string", - "description":"id" - }, - "name": { - "type":"string", - "description":"name" - }, - "tags": { - "type":"array", - "items": { - "type":"string" - } - } - }, - "description":"nice model" - } - """ - val json = parse(jsonString) - json.extract[Model] match { - case model: Model => { - model.id should be ("Foo") - model.name should be ("Bar") - model.properties should not be (null) - model.properties.size should be (3) - model.description should be (Some("nice model")) - model.properties("id") match { - case e: ModelProperty => { - e.`type` should be ("string") - e.required should be (true) - e.description should be (Some("id")) - } - case _ => fail("missing property id") - } - model.properties("name") match { - case e: ModelProperty => { - e.`type` should be ("string") - e.required should be (false) - e.description should be (Some("name")) - } - case _ => fail("missing property name") - } - - model.properties("tags") match { - case e: ModelProperty => { - e.`type` should be ("Array") - e.required should be (false) - e.items match { - case Some(items) => items.`type` should be ("string") - case _ => fail("didn't find ref for Array") - } - } - case _ => fail("missing property name") - } - } - case _ => fail("expected type Model") - } - } - - it should "deserialize a model with a set" in { - val jsonString = """ - { - "id":"Foo", - "name":"Bar", - "required": ["id"], - "properties": { - "id": { - "type":"string", - "description":"id" - }, - "name": { - "type":"string", - "description":"name" - }, - "tags": { - "type":"array", - "uniqueItems": true, - "items": { - "type":"string" - } - } - }, - "description":"nice model" - } - """ - val json = parse(jsonString) - json.extract[Model] match { - case model: Model => { - model.id should be ("Foo") - model.name should be ("Bar") - model.properties should not be (null) - model.properties.size should be (3) - model.description should be (Some("nice model")) - model.properties("id") match { - case e: ModelProperty => { - e.`type` should be ("string") - e.required should be (true) - e.description should be (Some("id")) - } - case _ => fail("missing property id") - } - model.properties("name") match { - case e: ModelProperty => { - e.`type` should be ("string") - e.required should be (false) - e.description should be (Some("name")) - } - case _ => fail("missing property name") - } - - model.properties("tags") match { - case e: ModelProperty => { - e.`type` should be ("Set") - e.required should be (false) - e.items match { - case Some(items) => items.`type` should be ("string") - case _ => fail("didn't find ref for Array") - } - } - case _ => fail("missing property name") - } - } - case _ => fail("expected type Model") - } - } - - it should "serialize a model" in { - val ref = Model("Foo", "Bar", "Bar", (LinkedHashMap("s" -> ModelProperty("string", "string", 0, true, Some("a string"))))) - write(ref) should be ("""{"id":"Foo","name":"Bar","required":["s"],"properties":{"s":{"type":"string","description":"a string"}}}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelRefSerializationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize a model ref" in { - val jsonString = """ - { - "$ref":"Foo", - "type":"Bar" - } - """ - val json = parse(jsonString) - json.extract[ModelRef] match { - case p: ModelRef => { - p.ref should be (Some("Foo")) - p.`type` should be ("Bar") - } - case _ => fail("expected type ModelRef") - } - } - - it should "serialize a model ref" in { - val ref = ModelRef("Foo", Some("Bar")) - write(ref) should be ("""{"type":"Foo","$ref":"Bar"}""") - } -} - -@RunWith(classOf[JUnitRunner]) -class ModelPropertySerializationTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize a model property with allowable values and ref" in { - val jsonString = """ - { - "type":"string", - "required":false, - "description":"nice", - "enum":["1","2","3"], - "items":{ - "type":"Foo", - "$ref":"Bar" - } - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (false) - p.description should be (Some("nice")) - p.allowableValues match { - case e: AllowableListValues => e.values should be (List("1","2","3")) - case _ => fail("expected allowable values") - } - p.items match { - case Some(e: ModelRef) => { - e.`type` should be ("Foo") - e.ref should be (Some("Bar")) - } - case _ => fail("expected type ModelProperty") - } - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property with allowable values and ref" in { - val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b")),Some(ModelRef("Foo",Some("Bar")))) - write(p) should be ("""{"type":"string","description":"nice","items":{"type":"Foo","$ref":"Bar"},"enum":["a","b"]}""") - } - - it should "deserialize a model property with allowable values" in { - val jsonString = """ - { - "type":"string", - "required":false, - "description":"nice", - "enum":["1","2","3"] - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (false) - p.description should be (Some("nice")) - p.allowableValues match { - case e: AllowableListValues => e.values should be (List("1","2","3")) - case _ => fail("expected allowable values") - } - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property with allowable values" in { - val p = ModelProperty("string", "string", 0, false, Some("nice"), AllowableListValues(List("a","b"))) - write(p) should be ("""{"type":"string","description":"nice","enum":["a","b"]}""") - } - - it should "deserialize a model property" in { - val jsonString = """ - { - "type":"string", - "required":true, - "description":"nice" - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("string") - p.required should be (true) - p.description should be (Some("nice")) - } - case _ => fail("expected type ModelProperty") - } - } - - it should "serialize a model property" in { - val p = ModelProperty("string", "string", 0, false, Some("nice")) - write(p) should be ("""{"type":"string","description":"nice"}""") - } - - it should "extract model properties" in { - val jsonString = """ - { - "type":"integer", - "format":"int64", - "required":true, - "description":"nice" - } - """ - val json = parse(jsonString) - json.extract[ModelProperty] match { - case p: ModelProperty => { - p.`type` should be ("long") - p.required should be (true) - p.description should be (Some("nice")) - } - case _ => fail("expected type ModelProperty") - } - } - - it should "extract model properties with arrays" in { - val jsonString = """ -{ - "id": "DocIdList", - "name": "DocIdList", - "properties": { - "docIds": { - "items": { - "format": "int64", - "type": "integer" - }, - "type": "array" - } - } -} -""" - val json = parse(jsonString) - json.extract[Model] match { - case p: Model => { - p.properties should not be (null) - p.properties.size should be (1) - p.properties.keys.size should be (1) - for(key <- p.properties.keys) { - val property = p.properties(key) - property.`type` should be ("Array") - property.items should not be (None) - property.items.get.`type` should be ("long") - } - } - case _ => fail("expected type ModelProperty") - } - } -} - -@RunWith(classOf[JUnitRunner]) -class AllowableValuesSerializersTest extends FlatSpec with Matchers { - implicit val formats = SwaggerSerializers.formats("1.2") - - it should "deserialize allowable value list" in { - val allowableValuesListString = """ - { - "valueType":"LIST", - "values":["1","2","3"] - } - """ - val json = parse(allowableValuesListString) - json.extract[AllowableValues] match { - case avl: AllowableListValues => { - avl.valueType should be ("LIST") - avl.values should be (List("1","2","3")) - } - } - } - - it should "serialize allowable values list" in { - val l = AllowableListValues(List("1","2","3")) - write(l) should be ("""{"valueType":"LIST","values":["1","2","3"]}""") - } - - it should "deserialize allowable values range" in { - val allowableValuesRangeString = """ - { - "valueType":"RANGE", - "min":"abc", - "max":3 - } - """ - val json = parse(allowableValuesRangeString) - json.extract[AllowableValues] match { - case avr: AllowableRangeValues => { - avr.min should be ("abc") - avr.max should be ("3") - } - case _ => fail("wrong type returned, should be AllowabeValuesList") - } - } - - it should "serialize allowable values range" in { - val l = AllowableRangeValues("-1", "3") - write(l) should be ("""{"valueType":"RANGE","min":"-1","max":"3"}""") - } -} diff --git a/src/test/scala/swaggerSpec1_2/UtilsTest.scala b/src/test/scala/swaggerSpec1_2/UtilsTest.scala deleted file mode 100644 index e0b10194e4f8..000000000000 --- a/src/test/scala/swaggerSpec1_2/UtilsTest.scala +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * 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 swaggerSpec1_2 - -import com.wordnik.swagger.codegen.model._ -import com.wordnik.swagger.codegen.util.{ResourceExtractor, ApiExtractor, CoreUtils} - -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.collection.JavaConverters._ -import scala.beans.BeanProperty - -@RunWith(classOf[JUnitRunner]) -class ResourceExtractorTest extends FlatSpec with Matchers { - behavior of "ResourceExtractor" - it should "get 3 apis from a resource listing" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.2/api-docs") - resourceListing should not be(null) - resourceListing.apis.size should be (3) - } -} - -@RunWith(classOf[JUnitRunner]) -class ApiExtractorTest extends FlatSpec with Matchers { - behavior of "ApiExtractor" - it should "verify the deserialization of the store api" in { - val resourceListing = ResourceExtractor.fetchListing("src/test/resources/petstore-1.2/api-docs") - val docs = ApiExtractor.extractApiOperations(resourceListing.swaggerVersion, "src/test/resources/petstore-1.2", resourceListing.apis) - - val m = docs.map(t => (t.resourcePath, t)).toMap - val storeApi = m("/store") - - storeApi should not be (null) - storeApi.apis.size should be (2) - - val f = storeApi.apis.map(m => (m.path, m)).toMap - (f.keys.toSet & Set("/store/order/{orderId}","/store/order")).size should be (2) - - val storeOps = f("/store/order/{orderId}") - val ops = storeOps.operations.map(o => (o.nickname, o)).toMap - val getOrderById = ops("getOrderById") - - getOrderById should not be null - - getOrderById.method should be ("GET") - getOrderById.parameters.size should be (1) - getOrderById.responseMessages.size should be (2) - } -}