From c5ccc0a908a4f1217e36d5ca91b7264f6bb987d2 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 29 Aug 2014 09:47:17 -0700 Subject: [PATCH 001/325] update to swagger 2.0 --- .travis.yml | 3 - LICENSE | 11 - README.md | 246 ----- bin/Version.scala | 8 - bin/all-petstore.sh | 37 - bin/android-java-petstore.sh | 32 - bin/android-java-wordnik-api.sh | 32 - bin/csharp-petstore.sh | 32 - bin/flash-petstore.sh | 32 - bin/java-petstore-filemap.sh | 32 - bin/java-petstore.sh | 32 - bin/java-wordnik-api.sh | 32 - bin/objc-petstore.sh | 34 - bin/objc-wordnik-api.sh | 32 - bin/php-petstore.sh | 32 - bin/php-wordnik-api.sh | 32 - bin/python-petstore.sh | 32 - bin/python-wordnik-api.sh | 32 - bin/python3-petstore.sh | 32 - bin/python3-wordnik-api.sh | 32 - bin/ruby-petstore.sh | 32 - bin/runscala.sh | 32 - bin/scala-async.sh | 31 - bin/scala-petstore.sh | 32 - bin/scala-wordnik-api.sh | 32 - bin/static-docs.sh | 32 - bin/update-spec.sh | 31 - bin/validate.sh | 31 - bin/yml2swagger.js | 56 -- build.sbt | 136 --- distro/pom.xml.disabled | 124 --- distro/src/main/assembly/distribution.xml | 29 - package.json | 16 - project/build.properties | 1 - project/plugins.sbt | 5 - sbt | 518 ----------- specs/admin.json | 100 -- specs/discovery.json | 337 ------- specs/discovery2.json | 403 -------- specs/discovery3.json | 403 -------- specs/resources.json | 15 - src/main/resources/Java/model.mustache | 1 + .../codegen/BasicAndroidJavaClient.scala | 76 -- .../codegen/BasicCSharpGenerator.scala | 209 ----- .../swagger/codegen/BasicFlashCodegen.scala | 168 ---- .../swagger/codegen/BasicGenerator.scala | 394 -------- .../codegen/BasicGroovyGenerator.scala | 53 -- .../swagger/codegen/BasicJavaGenerator.scala | 251 ----- .../swagger/codegen/BasicObjcGenerator.scala | 247 ----- .../swagger/codegen/BasicPHPGenerator.scala | 160 ---- .../codegen/BasicPython3Generator.scala | 45 - .../codegen/BasicPythonGenerator.scala | 165 ---- .../swagger/codegen/BasicRubyGenerator.scala | 117 --- .../swagger/codegen/BasicScalaGenerator.scala | 221 ----- .../com/wordnik/swagger/codegen/Codegen.scala | 548 ----------- .../wordnik/swagger/codegen/PathUtil.scala | 63 -- .../codegen/ScalaAsyncClientGenerator.scala | 508 ---------- .../swagger/codegen/SpecConverter.scala | 71 -- .../swagger/codegen/SwaggerDocGenerator.scala | 107 --- .../codegen/language/CodegenConfig.scala | 156 ---- .../codegen/model/AuthorizationModels.scala | 46 - .../swagger/codegen/model/ClientOpts.scala | 23 - .../codegen/model/LegacySerializers.scala | 351 ------- .../model/SwaggerModelSerializer.scala | 634 ------------- .../swagger/codegen/model/SwaggerModels.scala | 119 --- .../codegen/model/SwaggerValidator.scala | 103 -- .../swagger/codegen/spec/SwaggerSpec.scala | 22 - .../codegen/spec/SwaggerSpecValidator.scala | 446 --------- .../swagger/codegen/spec/Validator.scala | 69 -- .../swagger/codegen/util/ApiExtractor.scala | 75 -- .../swagger/codegen/util/CoreUtils.scala | 106 --- .../swagger/codegen/util/RemoteUrl.scala | 46 - .../codegen/util/ResourceExtractor.scala | 48 - .../codegen/util/ValidationException.scala | 24 - src/test/resources/petstore-1.1/pet.json | 227 ----- .../resources/petstore-1.1/resources.json | 19 - src/test/resources/petstore-1.1/store.json | 127 --- src/test/resources/petstore-1.1/user.json | 254 ----- src/test/resources/petstore-1.2/api-docs | 60 -- src/test/resources/petstore-1.2/pet | 425 --------- src/test/resources/petstore-1.2/store | 144 --- src/test/resources/petstore-1.2/user | 299 ------ src/test/scala/BasicCSharpGeneratorTest.scala | 48 - src/test/scala/BasicGeneratorTest.scala | 152 --- src/test/scala/BasicJavaGeneratorTest.scala | 204 ---- src/test/scala/BasicScalaGeneratorTest.scala | 296 ------ src/test/scala/CodegenConfigTest.scala | 135 --- src/test/scala/CodegenTest.scala | 55 -- src/test/scala/PathUtilTest.scala | 55 -- .../scala/swaggerSpec1_1/CoreUtilsTest.scala | 267 ------ .../ModelSerializerValidations.scala | 552 ----------- .../swaggerSpec1_1/ModelSerializersTest.scala | 641 ------------- .../swaggerSpec1_1/SwaggerModelTest.scala | 171 ---- src/test/scala/swaggerSpec1_1/UtilsTest.scala | 65 -- .../scala/swaggerSpec1_2/CoreUtilsTest.scala | 267 ------ .../ModelSerializerValidations.scala | 542 ----------- .../swaggerSpec1_2/ModelSerializersTest.scala | 877 ------------------ src/test/scala/swaggerSpec1_2/UtilsTest.scala | 65 -- 98 files changed, 1 insertion(+), 14801 deletions(-) delete mode 100644 .travis.yml delete mode 100644 LICENSE delete mode 100644 README.md delete mode 100644 bin/Version.scala delete mode 100755 bin/all-petstore.sh delete mode 100755 bin/android-java-petstore.sh delete mode 100755 bin/android-java-wordnik-api.sh delete mode 100755 bin/csharp-petstore.sh delete mode 100755 bin/flash-petstore.sh delete mode 100755 bin/java-petstore-filemap.sh delete mode 100755 bin/java-petstore.sh delete mode 100755 bin/java-wordnik-api.sh delete mode 100755 bin/objc-petstore.sh delete mode 100755 bin/objc-wordnik-api.sh delete mode 100755 bin/php-petstore.sh delete mode 100755 bin/php-wordnik-api.sh delete mode 100755 bin/python-petstore.sh delete mode 100755 bin/python-wordnik-api.sh delete mode 100755 bin/python3-petstore.sh delete mode 100755 bin/python3-wordnik-api.sh delete mode 100755 bin/ruby-petstore.sh delete mode 100755 bin/runscala.sh delete mode 100755 bin/scala-async.sh delete mode 100755 bin/scala-petstore.sh delete mode 100755 bin/scala-wordnik-api.sh delete mode 100755 bin/static-docs.sh delete mode 100755 bin/update-spec.sh delete mode 100755 bin/validate.sh delete mode 100644 bin/yml2swagger.js delete mode 100644 build.sbt delete mode 100644 distro/pom.xml.disabled delete mode 100644 distro/src/main/assembly/distribution.xml delete mode 100644 package.json delete mode 100644 project/build.properties delete mode 100644 project/plugins.sbt delete mode 100755 sbt delete mode 100755 specs/admin.json delete mode 100755 specs/discovery.json delete mode 100644 specs/discovery2.json delete mode 100644 specs/discovery3.json delete mode 100755 specs/resources.json delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicAndroidJavaClient.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicCSharpGenerator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicFlashCodegen.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicGenerator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicGroovyGenerator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicPHPGenerator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicPython3Generator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicPythonGenerator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicRubyGenerator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/BasicScalaGenerator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/Codegen.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/PathUtil.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/ScalaAsyncClientGenerator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/SpecConverter.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/SwaggerDocGenerator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/language/CodegenConfig.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/model/AuthorizationModels.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/model/ClientOpts.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/model/LegacySerializers.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/model/SwaggerModelSerializer.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/model/SwaggerModels.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/model/SwaggerValidator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/spec/SwaggerSpec.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/spec/SwaggerSpecValidator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/spec/Validator.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/util/ApiExtractor.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/util/CoreUtils.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/util/RemoteUrl.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/util/ResourceExtractor.scala delete mode 100644 src/main/scala/com/wordnik/swagger/codegen/util/ValidationException.scala delete mode 100644 src/test/resources/petstore-1.1/pet.json delete mode 100644 src/test/resources/petstore-1.1/resources.json delete mode 100644 src/test/resources/petstore-1.1/store.json delete mode 100644 src/test/resources/petstore-1.1/user.json delete mode 100644 src/test/resources/petstore-1.2/api-docs delete mode 100644 src/test/resources/petstore-1.2/pet delete mode 100644 src/test/resources/petstore-1.2/store delete mode 100644 src/test/resources/petstore-1.2/user delete mode 100644 src/test/scala/BasicCSharpGeneratorTest.scala delete mode 100644 src/test/scala/BasicGeneratorTest.scala delete mode 100644 src/test/scala/BasicJavaGeneratorTest.scala delete mode 100644 src/test/scala/BasicScalaGeneratorTest.scala delete mode 100644 src/test/scala/CodegenConfigTest.scala delete mode 100644 src/test/scala/CodegenTest.scala delete mode 100644 src/test/scala/PathUtilTest.scala delete mode 100644 src/test/scala/swaggerSpec1_1/CoreUtilsTest.scala delete mode 100644 src/test/scala/swaggerSpec1_1/ModelSerializerValidations.scala delete mode 100644 src/test/scala/swaggerSpec1_1/ModelSerializersTest.scala delete mode 100644 src/test/scala/swaggerSpec1_1/SwaggerModelTest.scala delete mode 100644 src/test/scala/swaggerSpec1_1/UtilsTest.scala delete mode 100644 src/test/scala/swaggerSpec1_2/CoreUtilsTest.scala delete mode 100644 src/test/scala/swaggerSpec1_2/ModelSerializerValidations.scala delete mode 100644 src/test/scala/swaggerSpec1_2/ModelSerializersTest.scala delete mode 100644 src/test/scala/swaggerSpec1_2/UtilsTest.scala diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 6651d4dd98ef..000000000000 --- a/.travis.yml +++ /dev/null @@ -1,3 +0,0 @@ -language: scala -scala: - - 2.10.0 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 deleted file mode 100644 index bda4da924cd2..000000000000 --- a/README.md +++ /dev/null @@ -1,246 +0,0 @@ -# Swagger Code Generator - -[![Build Status](https://travis-ci.org/wordnik/swagger-codegen.png)](https://travis-ci.org/wordnik/swagger-codegen) - -## Overview -This is the swagger codegen project, which allows generation of client libraries automatically from a -Swagger-compliant server. - -## What's Swagger? - -The goal of Swaggerâ„¢ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swager removes the guesswork in calling the service. - - -Check out [Swagger-Spec](https://github.com/wordnik/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more. - - -### 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! - -* [Apache maven 3.0.3 or greater](http://maven.apache.org/) - -* [Scala 2.9.1](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: - -``` -./sbt assembly -``` - -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: - -``` -./bin/scala-petstore.sh -``` - -This will run the script in [samples/client/petstore/ScalaPetstoreCodegen.scala](https://github.com/wordnik/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: - -``` -cd samples/client/petstore/scala -mvn package -``` - -Other languages have petstore samples, too: -``` -./bin/flash-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/wordnik/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. - -### 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. - -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. - -### Where is Javascript??? -See our [javascript library](http://github.com/wordnik/swagger.js)--it's completely dynamic and doesn't require -static code generation. -There is a third-party component called [swagger-js-codegen](https://github.com/wcandillon/swagger-js-codegen) that can generate angularjs or nodejs source code from a swagger specification. - - -#### Generating a client from flat files (i.e. no remote server calls) -If you don't want to call your server, you can save the swagger spec files into a directory and pass an argument -to the code generator like this: - -``` --DfileMap=/path/to/resource-listing -``` - -Or for example: -``` -./bin/java-petstore-filemap.sh -``` - -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. - -### 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-core](https://github.com/wordnik/swagger-core/wiki). 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: - -``` -./bin/validate.sh http://petstore.swagger.wordnik.com/api/api-docs "specia-key" ./swagger-errors.html -``` - -### 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. - -``` -./bin/static-docs.sh -``` - -Will produce the output here: - -``` -https://github.com/wordnik/swagger-codegen/tree/master/samples/docs/swagger-static-docs -``` - -which is based on these templates: - -``` -https://github.com/wordnik/swagger-codegen/tree/master/src/main/resources/swagger-static -``` - -and looks like this - -![Image](https://raw.github.com/wordnik/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/wordnik/swagger-codegen/tree/master/samples/server-generator/node) - -* [ruby sinatra generator](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/sinatra) - -* [scala scalatra generator](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) - -* [java jax-rs generator](https://github.com/wordnik/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/wordnik/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 -``` - -Will read the 1.1 spec from wordnik developer and write it into the folder called `wordnik-developer`. - - -### To build the codegen library - -This will create the swagger-codegen library from source. - -``` -./sbt assembly -``` - -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! - -License -------- - -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 [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/bin/Version.scala b/bin/Version.scala deleted file mode 100644 index 61a0725a149b..000000000000 --- a/bin/Version.scala +++ /dev/null @@ -1,8 +0,0 @@ -val version = scala.util.Properties.scalaPropOrElse("version.number", "unknown").toString match { - case "2.10.0" => "2.10" - case "2.10.2" => "2.10" - case "2.10.3" => "2.10" - case "2.10.4" => "2.10" - case e: String => e -} -println(version) diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh deleted file mode 100755 index 716db5bae155..000000000000 --- a/bin/all-petstore.sh +++ /dev/null @@ -1,37 +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 -./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/java-petstore.sh -./bin/objc-petstore.sh -./bin/php-petstore.sh -./bin/python-petstore.sh -./bin/python3-petstore.sh -./bin/ruby-petstore.sh -./bin/scala-petstore.sh diff --git a/bin/android-java-petstore.sh b/bin/android-java-petstore.sh deleted file mode 100755 index edde6205216f..000000000000 --- a/bin/android-java-petstore.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="$@ samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.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 $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/android-java-wordnik-api.sh b/bin/android-java-wordnik-api.sh deleted file mode 100755 index aba96fb90968..000000000000 --- a/bin/android-java-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" -ags="$@ samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.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/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/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/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 deleted file mode 100755 index fee35e8df4a9..000000000000 --- a/bin/java-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/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 $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/java-wordnik-api.sh b/bin/java-wordnik-api.sh deleted file mode 100755 index 1277e4560097..000000000000 --- a/bin/java-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/java/JavaWordnikApiCodegen.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/objc-petstore.sh b/bin/objc-petstore.sh deleted file mode 100755 index ad1c8dcdc373..000000000000 --- a/bin/objc-petstore.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) - -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/objc/ObjcPetstoreCodegen.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/objc-wordnik-api.sh b/bin/objc-wordnik-api.sh deleted file mode 100755 index bd380dcea926..000000000000 --- a/bin/objc-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/objc/ObjcWordnikApiCodegen.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/php-petstore.sh b/bin/php-petstore.sh deleted file mode 100755 index 07887a0775ce..000000000000 --- a/bin/php-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/php/PHPPetstoreCodegen.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/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 deleted file mode 100755 index 370b7f429808..000000000000 --- a/bin/python-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/python/PythonPetstoreCodegen.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/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.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 deleted file mode 100755 index bb5a9b2afee7..000000000000 --- a/bin/scala-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/scala/ScalaPetstoreCodegen.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/scala-wordnik-api.sh b/bin/scala-wordnik-api.sh deleted file mode 100755 index 2c1703507b24..000000000000 --- a/bin/scala-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/scala/ScalaWordnikApiCodegen.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/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/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 49971a19594a..000000000000 --- a/build.sbt +++ /dev/null @@ -1,136 +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", - "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/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/project/build.properties b/project/build.properties deleted file mode 100644 index 8cbb5226c451..000000000000 --- a/project/build.properties +++ /dev/null @@ -1 +0,0 @@ -sbt.version=0.13.0 \ 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/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 < "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", destinationDir, "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 38a84d862b3f..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicGenerator.scala +++ /dev/null @@ -1,394 +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 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] = { - 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 _ => { - apiKey.map{ key => - Some(ApiKeyValue("api_key", "query", key)) - }.getOrElse(None) - } - } - } - - 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 6111c080f671..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicPythonGenerator.scala +++ /dev/null @@ -1,165 +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( - "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 23cf2a3aacf4..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala +++ /dev/null @@ -1,548 +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 == "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.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) "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 c41245ad68d7..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/ScalaAsyncClientGenerator.scala +++ /dev/null @@ -1,508 +0,0 @@ -package com.wordnik.swagger.codegen - -import scala.collection.mutable -import java.io.{File, FileWriter} -import com.wordnik.swagger.codegen.model._ -import scala.collection.mutable.{HashMap, ListBuffer} -import language.CodegenConfig -import scala.io.Source -import org.json4s.jackson.Serialization._ -import org.fusesource.scalate.{Template, TemplateSource, TemplateEngine} -import org.apache.commons.io.FileUtils -import com.wordnik.swagger.codegen.util.{CoreUtils, ApiExtractor, ResourceExtractor} -import com.wordnik.swagger.codegen.spec.SwaggerSpecValidator -import mojolly.inflector.InflectorImports._ -import org.rogach.scallop.{ScallopConf, Scallop} -import scala.annotation.switch -import scala.collection.JavaConverters._ - -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 - - 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 2249557bcd75..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/model/AuthorizationModels.scala +++ /dev/null @@ -1,46 +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/SwaggerSpec.scala b/src/main/scala/com/wordnik/swagger/codegen/spec/SwaggerSpec.scala deleted file mode 100644 index a958ba3d6937..000000000000 --- a/src/main/scala/com/wordnik/swagger/codegen/spec/SwaggerSpec.scala +++ /dev/null @@ -1,22 +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 - -object SwaggerSpec { - val primitives = List("int", "string", "long", "double", "float", "boolean", "void") - val containers = List("List", "Map", "Set", "Array") -} 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 2452ce5c1499..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.basePath) - } - }) - - 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 51d8dbea5474..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), URLEncoder.encode(auth.value))).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/resources/petstore-1.2/api-docs b/src/test/resources/petstore-1.2/api-docs deleted file mode 100644 index 370eca562a78..000000000000 --- a/src/test/resources/petstore-1.2/api-docs +++ /dev/null @@ -1,60 +0,0 @@ -{ - "apiVersion": "1.0.0", - "swaggerVersion": "1.2", - "apis": [ - { - "path": "/pet", - "description": "Operations about pets" - }, - { - "path": "/user", - "description": "Operations about user" - }, - { - "path": "/store", - "description": "Operations about store" - } - ], - "authorizations": { - "oauth2": { - "type": "oauth2", - "scopes": [ - { - "scope": "email", - "description": "Access to your email address" - }, - { - "scope": "pets", - "description": "Access to your pets" - } - ], - "grantTypes": { - "implicit": { - "loginEndpoint": { - "url": "http://petstore.swagger.wordnik.com/oauth/dialog" - }, - "tokenName": "access_token" - }, - "authorization_code": { - "tokenRequestEndpoint": { - "url": "http://petstore.swagger.wordnik.com/oauth/requestToken", - "clientIdName": "client_id", - "clientSecretName": "client_secret" - }, - "tokenEndpoint": { - "url": "http://petstore.swagger.wordnik.com/oauth/token", - "tokenName": "access_code" - } - } - } - } - }, - "info": { - "title": "Swagger Sample App", - "description": "This is a sample server Petstore server. You can find out more about Swagger \n at http://swagger.wordnik.com or on irc.freenode.net, #swagger. For this sample,\n you can use the api key \"special-key\" to test the authorization filters", - "termsOfServiceUrl": "http://helloreverb.com/terms/", - "contact": "apiteam@wordnik.com", - "license": "Apache 2.0", - "licenseUrl": "http://www.apache.org/licenses/LICENSE-2.0.html" - } -} \ No newline at end of file diff --git a/src/test/resources/petstore-1.2/pet b/src/test/resources/petstore-1.2/pet deleted file mode 100644 index 4a8439a44247..000000000000 --- a/src/test/resources/petstore-1.2/pet +++ /dev/null @@ -1,425 +0,0 @@ -{ - "apiVersion": "1.0.0", - "swaggerVersion": "1.2", - "basePath": "http://petstore.swagger.wordnik.com/api", - "resourcePath": "/pet", - "produces": [ - "application/json", - "application/xml", - "text/plain", - "text/html" - ], - "apis": [ - { - "path": "/pet/{petId}", - "operations": [ - { - "method": "GET", - "summary": "Find pet by ID", - "notes": "Returns a pet based on ID", - "type": "Pet", - "nickname": "getPetById", - "authorizations": {}, - "parameters": [ - { - "name": "petId", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "integer", - "format": "int64", - "paramType": "path", - "minimum": "1.0", - "maximum": "100000.0" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid ID supplied" - }, - { - "code": 404, - "message": "Pet not found" - } - ] - }, - { - "method": "PATCH", - "summary": "partial updates to a pet", - "notes": "", - "type": "array", - "items": { - "$ref": "Pet" - }, - "nickname": "partialUpdate", - "produces": [ - "application/json", - "application/xml" - ], - "consumes": [ - "application/json", - "application/xml" - ], - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - } - ] - }, - "parameters": [ - { - "name": "petId", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "string", - "paramType": "path" - }, - { - "name": "body", - "description": "Pet object that needs to be added to the store", - "required": true, - "type": "Pet", - "paramType": "body" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid tag value" - } - ] - }, - { - "method": "POST", - "summary": "Updates a pet in the store with form data", - "notes": "", - "type": "void", - "nickname": "updatePetWithForm", - "consumes": [ - "application/x-www-form-urlencoded" - ], - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - } - ] - }, - "parameters": [ - { - "name": "petId", - "description": "ID of pet that needs to be updated", - "required": true, - "type": "string", - "paramType": "path" - }, - { - "name": "name", - "description": "Updated name of the pet", - "required": false, - "type": "string", - "paramType": "form" - }, - { - "name": "status", - "description": "Updated status of the pet", - "required": false, - "type": "string", - "paramType": "form" - } - ], - "responseMessages": [ - { - "code": 405, - "message": "Invalid input" - } - ] - }, - { - "method": "DELETE", - "summary": "Deletes a pet", - "notes": "", - "type": "void", - "nickname": "deletePet", - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - } - ] - }, - "parameters": [ - { - "name": "petId", - "description": "Pet id to delete", - "required": true, - "type": "string", - "paramType": "path" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid pet value" - } - ] - } - ] - }, - { - "path": "/pet", - "operations": [ - { - "method": "PUT", - "summary": "Update an existing pet", - "notes": "", - "type": "void", - "nickname": "updatePet", - "authorizations": {}, - "parameters": [ - { - "name": "body", - "description": "Pet object that needs to be updated in the store", - "required": true, - "type": "Pet", - "paramType": "body" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid ID supplied" - }, - { - "code": 404, - "message": "Pet not found" - }, - { - "code": 405, - "message": "Validation exception" - } - ] - }, - { - "method": "POST", - "summary": "Add a new pet to the store", - "notes": "", - "type": "void", - "nickname": "addPet", - "consumes": [ - "application/json", - "application/xml" - ], - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - } - ] - }, - "parameters": [ - { - "name": "body", - "description": "Pet object that needs to be added to the store", - "required": true, - "type": "Pet", - "paramType": "body" - } - ], - "responseMessages": [ - { - "code": 405, - "message": "Invalid input" - } - ] - } - ] - }, - { - "path": "/pet/findByStatus", - "operations": [ - { - "method": "GET", - "summary": "Finds Pets by status", - "notes": "Multiple status values can be provided with comma seperated strings", - "type": "array", - "items": { - "$ref": "Pet" - }, - "nickname": "findPetsByStatus", - "authorizations": {}, - "parameters": [ - { - "name": "status", - "description": "Status values that need to be considered for filter", - "defaultValue": "available", - "required": true, - "type": "string", - "paramType": "query", - "enum": [ - "available", - "pending", - "sold" - ] - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid status value" - } - ] - } - ] - }, - { - "path": "/pet/findByTags", - "operations": [ - { - "method": "GET", - "summary": "Finds Pets by tags", - "notes": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", - "type": "array", - "items": { - "$ref": "Pet" - }, - "nickname": "findPetsByTags", - "authorizations": {}, - "parameters": [ - { - "name": "tags", - "description": "Tags to filter by", - "required": true, - "type": "string", - "paramType": "query" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid tag value" - } - ], - "deprecated": "true" - } - ] - }, - { - "path": "/pet/uploadImage", - "operations": [ - { - "method": "POST", - "summary": "uploads an image", - "notes": "", - "type": "void", - "nickname": "uploadFile", - "consumes": [ - "multipart/form-data" - ], - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - }, - { - "scope": "test:nothing", - "description": "nothing" - } - ] - }, - "parameters": [ - { - "name": "additionalMetadata", - "description": "Additional data to pass to server", - "required": false, - "type": "string", - "paramType": "form" - }, - { - "name": "file", - "description": "file to upload", - "required": false, - "type": "File", - "paramType": "body" - } - ] - } - ] - } - ], - "models": { - "Tag": { - "id": "Tag", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - } - }, - "Pet": { - "id": "Pet", - "required": [ - "id", - "name" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64", - "description": "unique identifier for the pet", - "minimum": "0.0", - "maximum": "100.0" - }, - "category": { - "$ref": "Category" - }, - "name": { - "type": "string" - }, - "photoUrls": { - "type": "array", - "items": { - "type": "string" - } - }, - "tags": { - "type": "array", - "items": { - "$ref": "Tag" - } - }, - "status": { - "type": "string", - "description": "pet status in the store", - "enum": [ - "available", - "pending", - "sold" - ] - } - } - }, - "Category": { - "id": "Category", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string" - } - } - } - } -} \ No newline at end of file diff --git a/src/test/resources/petstore-1.2/store b/src/test/resources/petstore-1.2/store deleted file mode 100644 index f7670669dfe4..000000000000 --- a/src/test/resources/petstore-1.2/store +++ /dev/null @@ -1,144 +0,0 @@ -{ - "apiVersion": "1.0.0", - "swaggerVersion": "1.2", - "basePath": "http://petstore.swagger.wordnik.com/api", - "resourcePath": "/store", - "produces": [ - "application/json" - ], - "apis": [ - { - "path": "/store/order/{orderId}", - "operations": [ - { - "method": "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", - "type": "Order", - "nickname": "getOrderById", - "authorizations": {}, - "parameters": [ - { - "name": "orderId", - "description": "ID of pet that needs to be fetched", - "required": true, - "type": "string", - "paramType": "path" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid ID supplied" - }, - { - "code": 404, - "message": "Order not found" - } - ] - }, - { - "method": "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", - "type": "void", - "nickname": "deleteOrder", - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - } - ] - }, - "parameters": [ - { - "name": "orderId", - "description": "ID of the order that needs to be deleted", - "required": true, - "type": "string", - "paramType": "path" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid ID supplied" - }, - { - "code": 404, - "message": "Order not found" - } - ] - } - ] - }, - { - "path": "/store/order", - "operations": [ - { - "method": "POST", - "summary": "Place an order for a pet", - "notes": "", - "type": "void", - "nickname": "placeOrder", - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - } - ] - }, - "parameters": [ - { - "name": "body", - "description": "order placed for purchasing the pet", - "required": true, - "type": "Order", - "paramType": "body" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid order" - } - ] - } - ] - } - ], - "models": { - "Order": { - "id": "Order", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "petId": { - "type": "integer", - "format": "int64" - }, - "quantity": { - "type": "integer", - "format": "int32" - }, - "status": { - "type": "string", - "description": "Order Status", - "enum": [ - "placed", - " approved", - " delivered" - ] - }, - "shipDate": { - "type": "string", - "format": "date-time" - } - } - } - } -} \ No newline at end of file diff --git a/src/test/resources/petstore-1.2/user b/src/test/resources/petstore-1.2/user deleted file mode 100644 index c9eb3f6ff783..000000000000 --- a/src/test/resources/petstore-1.2/user +++ /dev/null @@ -1,299 +0,0 @@ -{ - "apiVersion": "1.0.0", - "swaggerVersion": "1.2", - "basePath": "http://petstore.swagger.wordnik.com/api", - "resourcePath": "/user", - "produces": [ - "application/json" - ], - "apis": [ - { - "path": "/user", - "operations": [ - { - "method": "POST", - "summary": "Create user", - "notes": "This can only be done by the logged in user.", - "type": "void", - "nickname": "createUser", - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - } - ] - }, - "parameters": [ - { - "name": "body", - "description": "Created user object", - "required": true, - "type": "User", - "paramType": "body" - } - ] - } - ] - }, - { - "path": "/user/logout", - "operations": [ - { - "method": "GET", - "summary": "Logs out current logged in user session", - "notes": "", - "type": "void", - "nickname": "logoutUser", - "authorizations": {}, - "parameters": [] - } - ] - }, - { - "path": "/user/createWithArray", - "operations": [ - { - "method": "POST", - "summary": "Creates list of users with given input array", - "notes": "", - "type": "void", - "nickname": "createUsersWithArrayInput", - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - } - ] - }, - "parameters": [ - { - "name": "body", - "description": "List of user object", - "required": true, - "type": "array", - "items": { - "$ref": "User" - }, - "paramType": "body" - } - ] - } - ] - }, - { - "path": "/user/createWithList", - "operations": [ - { - "method": "POST", - "summary": "Creates list of users with given list input", - "notes": "", - "type": "void", - "nickname": "createUsersWithListInput", - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - } - ] - }, - "parameters": [ - { - "name": "body", - "description": "List of user object", - "required": true, - "type": "array", - "items": { - "$ref": "User" - }, - "paramType": "body" - } - ] - } - ] - }, - { - "path": "/user/{username}", - "operations": [ - { - "method": "PUT", - "summary": "Updated user", - "notes": "This can only be done by the logged in user.", - "type": "void", - "nickname": "updateUser", - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - } - ] - }, - "parameters": [ - { - "name": "username", - "description": "name that need to be deleted", - "required": true, - "type": "string", - "paramType": "path" - }, - { - "name": "body", - "description": "Updated user object", - "required": true, - "type": "User", - "paramType": "body" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid username supplied" - }, - { - "code": 404, - "message": "User not found" - } - ] - }, - { - "method": "DELETE", - "summary": "Delete user", - "notes": "This can only be done by the logged in user.", - "type": "void", - "nickname": "deleteUser", - "authorizations": { - "oauth2": [ - { - "scope": "test:anything", - "description": "anything" - } - ] - }, - "parameters": [ - { - "name": "username", - "description": "The name that needs to be deleted", - "required": true, - "type": "string", - "paramType": "path" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid username supplied" - }, - { - "code": 404, - "message": "User not found" - } - ] - }, - { - "method": "GET", - "summary": "Get user by user name", - "notes": "", - "type": "User", - "nickname": "getUserByName", - "authorizations": {}, - "parameters": [ - { - "name": "username", - "description": "The name that needs to be fetched. Use user1 for testing.", - "required": true, - "type": "string", - "paramType": "path" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid username supplied" - }, - { - "code": 404, - "message": "User not found" - } - ] - } - ] - }, - { - "path": "/user/login", - "operations": [ - { - "method": "GET", - "summary": "Logs user into the system", - "notes": "", - "type": "string", - "nickname": "loginUser", - "authorizations": {}, - "parameters": [ - { - "name": "username", - "description": "The user name for login", - "required": true, - "type": "string", - "paramType": "query" - }, - { - "name": "password", - "description": "The password for login in clear text", - "required": true, - "type": "string", - "paramType": "query" - } - ], - "responseMessages": [ - { - "code": 400, - "message": "Invalid username and password combination" - } - ] - } - ] - } - ], - "models": { - "User": { - "id": "User", - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "firstName": { - "type": "string" - }, - "username": { - "type": "string" - }, - "lastName": { - "type": "string" - }, - "email": { - "type": "string" - }, - "password": { - "type": "string" - }, - "phone": { - "type": "string" - }, - "userStatus": { - "type": "integer", - "format": "int32", - "description": "User Status", - "enum": [ - "1-registered", - "2-active", - "3-closed" - ] - } - } - } - } -} \ 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 07d025ef6cec..000000000000 --- a/src/test/scala/CodegenTest.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.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 - -@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, - List.empty, - List.empty, - 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")) - } -} 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) - } -} From d1daf3a0e6d62dbdd7361b0e52e1ad892363f179 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 29 Aug 2014 09:47:46 -0700 Subject: [PATCH 002/325] added 2.0 support files --- pom.xml | 415 +++++++++++ .../com/wordnik/swagger/codegen/Codegen.java | 25 + .../swagger/codegen/CodegenConfig.java | 20 + .../wordnik/swagger/codegen/CodegenModel.java | 12 + .../swagger/codegen/CodegenProperty.java | 11 + .../swagger/codegen/DefaultCodegen.java | 204 ++++++ .../swagger/codegen/DefaultGenerator.java | 97 +++ .../wordnik/swagger/codegen/Generator.java | 8 + .../wordnik/swagger/codegen/JavaCodegen.java | 14 + .../com/wordnik/swagger/codegen/Person.java | 13 + swagger.json | 676 ++++++++++++++++++ 11 files changed, 1495 insertions(+) create mode 100644 pom.xml create mode 100644 src/main/java/com/wordnik/swagger/codegen/Codegen.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/CodegenModel.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/Generator.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/JavaCodegen.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/Person.java create mode 100644 swagger.json diff --git a/pom.xml b/pom.xml new file mode 100644 index 000000000000..5858d6e38f3e --- /dev/null +++ b/pom.xml @@ -0,0 +1,415 @@ + + + org.sonatype.oss + oss-parent + 5 + + 4.0.0 + com.wordnik + swagger-codegen + jar + wordnik-swagger-codegen + 2.1.0-SNAPSHOT + 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 + + + + 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/test/scala + target/classes + target/test-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 + + + + + + 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 + + + + + + + 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.mortbay.jetty + jetty-maven-plugin + ${jetty-version} + + + com.sun.jersey + jersey-servlet + ${jersey-version} + + + + + + + + + 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 + + + + + + + + + ${project.groupId} + swagger-core + ${swagger-core-version} + compile + + + + com.samskivert + jmustache + ${jmustache-version} + compile + + + org.apache.maven + maven-plugin-tools-api + 2.0 + + + org.apache.felix + maven-bundle-plugin + ${felix-version} + + + org.slf4j + slf4j-ext + ${slf4j-version} + compile + + + org.slf4j + slf4j-api + ${slf4j-version} + compile + + + commons-lang + commons-lang + ${commons-lang-version} + compile + + + org.scalatest + scalatest_2.11 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + + 2.11.1 + 2.3.4 + 1.5.0-SNAPSHOT + 2.1.4 + + 4.8.1 + 1.0.0 + 2.4 + 1.6.3 + 3.1.5 + 1.9 + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java new file mode 100644 index 000000000000..54cd8e3a1bdb --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -0,0 +1,25 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.Swagger; +import com.wordnik.swagger.util.Json; + +import java.io.File; + +public class Codegen extends DefaultGenerator { + public static void main(String[] args) { + JavaCodegen config = new JavaCodegen(); + config.setTemplateDir("src/main/resources/Java"); + + try{ + Swagger swagger = (Swagger) Json.mapper() + .readValue(new File("swagger.json"), Swagger.class); + + new Codegen() + .config(new JavaCodegen()) + .generate(swagger); + } + catch (Exception e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java new file mode 100644 index 000000000000..498bb419cebf --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -0,0 +1,20 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.ModelImpl; + +import java.util.*; + +public interface CodegenConfig { + CodegenModel fromModel(String name, ModelImpl model); + String modelPackage(); + Set defaultIncludes(); + Map typeMapping(); + Set reservedWords(); + Map importMapping(); + String apiPackage(); + String fileSuffix(); + String templateDir(); + Map modelTemplateFiles(); + String toModelFilename(String name); + String modelFileFolder(); +} diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java new file mode 100644 index 000000000000..1010949be806 --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -0,0 +1,12 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; + +class CodegenModel { + public String name, classname, description; + public String defaultValue; + public List vars = new ArrayList(); +} \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java new file mode 100644 index 000000000000..662e6c9700cb --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java @@ -0,0 +1,11 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; + +public class CodegenProperty { + public String getter, setter, description, datatype, name, min, max, defaultValue; + public Map allowableValues; +} \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java new file mode 100644 index 000000000000..e6d76675463b --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -0,0 +1,204 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; +import java.io.File; + +public class DefaultCodegen { + String outputFolder = ""; + Set defaultIncludes; + Map typeMapping; + Set reservedWords; + Map importMapping; + String modelPackage = "", apiPackage, fileSuffix; + Map apiTemplateFiles = new HashMap(); + Map modelTemplateFiles = new HashMap(); + String templateDir; + + public Set defaultIncludes() { + return defaultIncludes; + } + public Map typeMapping() { + return typeMapping; + } + public Set reservedWords() { + return reservedWords; + } + 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 modelTemplateFiles() { + return modelTemplateFiles; + } + public String modelFileFolder() { + return outputFolder + File.separator + modelPackage().replaceAll("\\.", File.separator); + } + + public void setTemplateDir(String templateDir) { + this.templateDir = templateDir; + } + + public String toModelFilename(String name) { + return name; + } + + public DefaultCodegen() { + defaultIncludes = new HashSet( + Arrays.asList("double", + "int", + "long", + "short", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float") + ); + + typeMapping = new HashMap(); + typeMapping.put("Array", "List"); + typeMapping.put("array", "List"); + 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("long", "Long"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "String"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Object"); + typeMapping.put("integer", "Integer"); + + 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") + ); + + 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("Array", "java.util.*"); + importMapping.put("ArrayList", "java.util.*"); + 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 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) + return "null"; + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = toDeclaredType(ap.getItems()); + return "ArrayList<" + inner + ">() "; + } + return null; + } + + public String toDeclaredType(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 != null) + datatype = p.getType(); + } + return datatype; + } + + public CodegenModel fromModel(String name, ModelImpl model) { + CodegenModel m = new CodegenModel(); + m.name = name; + m.description = model.getDescription(); + m.classname = name; + + for(String key: model.getProperties().keySet()) { + Property prop = model.getProperties().get(key); + m.vars.add(fromProperty(key, prop)); + } + return m; + } + + public CodegenProperty fromProperty(String name, Property p) { + CodegenProperty property = new CodegenProperty(); + + property.name = name; + + property.getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1); + property.setter = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); + + property.defaultValue = toDefaultValue(p); + String datatype = toDeclaredType(p); + + if(typeMapping.containsKey(datatype)) { + property.datatype = typeMapping.get(datatype); + } + else + property.datatype = datatype; + return property; + } +} \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java new file mode 100644 index 000000000000..d1f8eaad17eb --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -0,0 +1,97 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.properties.*; +import com.wordnik.swagger.util.*; + +import com.samskivert.mustache.*; + + +import java.util.*; +import java.io.*; + +public class DefaultGenerator implements Generator { + private CodegenConfig config; + + public Generator config(CodegenConfig config) { + this.config = config; + return this; + } + + public void generate(Swagger swagger) { + try { + Map definitions = swagger.getDefinitions(); + + for(String name: definitions.keySet()) { + Model model = definitions.get(name); + Map modelMap = new HashMap(); + modelMap.put(name, model); + Object models = processModels(config, modelMap); + 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() + .defaultValue("") + .compile(template); + + writeToFile(filename, tmpl.execute(models)); + } + } + } + catch (Exception e) { + e.printStackTrace(); + } + } + + 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{ + InputStream is = this.getClass().getClassLoader().getResourceAsStream(name); + if(is == null) + is = new FileInputStream(new File(name)); + if(is == null) + throw new RuntimeException("no file found"); + java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); + return s.hasNext() ? s.next() : ""; + } + catch(Exception e) { + e.printStackTrace(); + } + throw new RuntimeException("can't load template " + name); + } + + public Map processModels(CodegenConfig config, Map definitions) { + Map objs = new HashMap(); + objs.put("package", config.modelPackage()); + List models = new ArrayList(); + List model = new ArrayList(); + for(String key: definitions.keySet()) { + Model mm = definitions.get(key); + if(mm instanceof ModelImpl) { + CodegenModel cm = config.fromModel(key, (ModelImpl) mm); + Map mo = new HashMap(); + mo.put("model", cm); + models.add(mo); + } + } + objs.put("models", models); + return objs; + } +} \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/Generator.java b/src/main/java/com/wordnik/swagger/codegen/Generator.java new file mode 100644 index 000000000000..be5b7ff9db02 --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/Generator.java @@ -0,0 +1,8 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.Swagger; + +public interface Generator { + Generator config(CodegenConfig config); + void generate(Swagger swagger); +} \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/JavaCodegen.java b/src/main/java/com/wordnik/swagger/codegen/JavaCodegen.java new file mode 100644 index 000000000000..c8765558174d --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/JavaCodegen.java @@ -0,0 +1,14 @@ +package com.wordnik.swagger.codegen; + +public class JavaCodegen extends DefaultCodegen implements CodegenConfig { + public JavaCodegen() { + super(); + outputFolder = "generated-code/java"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "Java"; + modelPackage = "com.wordnik.model"; + } + + +} \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/Person.java b/src/main/java/com/wordnik/swagger/codegen/Person.java new file mode 100644 index 000000000000..c59492237ff0 --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/Person.java @@ -0,0 +1,13 @@ +package com.wordnik.swagger.codegen; + +public class Person { + public final String name; + public Person (String name, int age) { + this.name = name; + _age = age; + } + public int getAge () { + return _age; + } + protected int _age; +} \ No newline at end of file diff --git a/swagger.json b/swagger.json new file mode 100644 index 000000000000..a9a0e2cb3420 --- /dev/null +++ b/swagger.json @@ -0,0 +1,676 @@ +{ + "swagger": 2.0, + "info": { + "description": "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", + "version": "1.0.0", + "title": "Swagger Sample App", + "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" + } + }, + "basePath": "/v2", + "paths": { + "/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": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/pet": { + "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" + } + } + }, + "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" + } + } + } + }, + "/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": [ + { + "in": "path", + "name": "orderId", + "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": [ + { + "in": "path", + "name": "orderId", + "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" + ], + "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 + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/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" + } + } + } + }, + "/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": [ + { + "in": "query", + "name": "status", + "description": "Status values that need to be considered for filter", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "jaxrs" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "400": { + "description": "Invalid status value" + } + } + } + }, + "/user/{username}": { + "get": { + "tags": [ + "user" + ], + "summary": "Get user by user name", + "description": "", + "operationId": "getUserByName", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "path", + "name": "username", + "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": [ + { + "in": "path", + "name": "username", + "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": [ + { + "in": "path", + "name": "username", + "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" + ], + "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": [ + { + "in": "query", + "name": "tags", + "description": "Tags to filter by", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "jaxrs" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "400": { + "description": "Invalid tag value" + } + } + } + }, + "/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/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/login": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs user into the system", + "description": "", + "operationId": "loginUser", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "query", + "name": "username", + "description": "The user name for login", + "required": false, + "type": "string" + }, + { + "in": "query", + "name": "password", + "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" + } + } + } + }, + "/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": [ + { + "in": "path", + "name": "petId", + "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" + } + } + } + } + }, + "definitions": { + "User": { + "properties": { + "phone": { + "type": "string" + }, + "password": { + "type": "string" + }, + "email": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "username": { + "type": "string" + }, + "id": { + "type": "integer", + "format": "int64" + }, + "userStatus": { + "type": "integer", + "format": "int32", + "position": 0 + } + } + }, + "Category": { + "properties": { + "name": { + "type": "string" + }, + "id": { + "type": "integer", + "format": "int64" + } + } + }, + "Pet": { + "enum": [ + "photoUrls", + "name" + ], + "properties": { + "tags": { + "type": "array", + "items": { + "$ref": "Tag" + } + }, + "photoUrls": { + "type": "array", + "items": { + "type": "string" + } + }, + "category": { + "$ref": "Category" + }, + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "example": "doggie", + "position": 0 + }, + "status": { + "type": "string", + "position": 0 + } + } + }, + "Tag": { + "properties": { + "name": { + "type": "string" + }, + "id": { + "type": "integer", + "format": "int64" + } + } + }, + "Order": { + "properties": { + "complete": { + "type": "boolean" + }, + "shipDate": { + "type": "string", + "format": "date-time" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "petId": { + "type": "integer", + "format": "int64" + }, + "id": { + "type": "integer", + "format": "int64" + }, + "status": { + "type": "string", + "position": 0 + } + } + } + } +} \ No newline at end of file From 812520e29fab87999fd4e8401d572cb92b8b27ef Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Mon, 1 Sep 2014 13:31:01 -0700 Subject: [PATCH 003/325] added support for models, partial for ops --- .../com/wordnik/swagger/codegen/Codegen.java | 20 +- .../swagger/codegen/CodegenConfig.java | 28 ++- .../wordnik/swagger/codegen/CodegenModel.java | 1 + .../swagger/codegen/CodegenOperation.java | 15 ++ .../swagger/codegen/CodegenProperty.java | 9 +- .../swagger/codegen/DefaultCodegen.java | 215 +++++++++++++++--- .../swagger/codegen/DefaultGenerator.java | 92 +++++++- .../wordnik/swagger/codegen/JavaCodegen.java | 14 -- .../com/wordnik/swagger/codegen/Person.java | 13 -- .../codegen/languages/JavaClientCodegen.java | 61 +++++ .../codegen/languages/ObjcClientCodegen.java | 136 +++++++++++ src/main/resources/Java/api.mustache | 2 +- src/main/resources/Java/model.mustache | 37 ++- src/main/resources/objc/model-body.mustache | 40 ++-- swagger.json | 85 ++++--- 15 files changed, 605 insertions(+), 163 deletions(-) create mode 100644 src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java delete mode 100644 src/main/java/com/wordnik/swagger/codegen/JavaCodegen.java delete mode 100644 src/main/java/com/wordnik/swagger/codegen/Person.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index 54cd8e3a1bdb..b62a8f40d926 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -1,5 +1,6 @@ package com.wordnik.swagger.codegen; +import com.wordnik.swagger.codegen.languages.*; import com.wordnik.swagger.models.Swagger; import com.wordnik.swagger.util.Json; @@ -7,15 +8,28 @@ import java.io.File; public class Codegen extends DefaultGenerator { public static void main(String[] args) { - JavaCodegen config = new JavaCodegen(); - config.setTemplateDir("src/main/resources/Java"); + CodegenConfig config = null; + if(args != null && args.length > 0) { + String lang = args[0]; + if("java".equals(lang)) { + JavaClientCodegen javaConfig = new JavaClientCodegen(); + javaConfig.setTemplateDir("src/main/resources/Java"); + config = javaConfig; + } + else if ("objc".equals(lang)) { + ObjcClientCodegen objcConfig = new ObjcClientCodegen(); + objcConfig.setTemplateDir("src/main/resources/objc"); + config = objcConfig; + } + } + try{ Swagger swagger = (Swagger) Json.mapper() .readValue(new File("swagger.json"), Swagger.class); new Codegen() - .config(new JavaCodegen()) + .config(config) .generate(swagger); } catch (Exception e) { diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java index 498bb419cebf..e33fcf29121d 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -1,20 +1,30 @@ package com.wordnik.swagger.codegen; -import com.wordnik.swagger.models.ModelImpl; +import com.wordnik.swagger.models.*; import java.util.*; public interface CodegenConfig { - CodegenModel fromModel(String name, ModelImpl model); - String modelPackage(); - Set defaultIncludes(); - Map typeMapping(); - Set reservedWords(); - Map importMapping(); String apiPackage(); + String apiFileFolder(); String fileSuffix(); String templateDir(); - Map modelTemplateFiles(); - String toModelFilename(String name); String modelFileFolder(); + String modelPackage(); + String toApiName(String name); + String toModelName(String name); + + Set reservedWords(); + + CodegenModel fromModel(String name, ModelImpl model); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation); + Set defaultIncludes(); + Map typeMapping(); + Map importMapping(); + Map apiTemplateFiles(); + Map modelTemplateFiles(); + + String toApiFilename(String name); + String toModelFilename(String name); + String toModelImport(String name); } diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index 1010949be806..b774ea5450eb 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -9,4 +9,5 @@ class CodegenModel { public String name, classname, description; public String defaultValue; public List vars = new ArrayList(); + public Set imports = new HashSet(); } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java b/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java new file mode 100644 index 000000000000..9c826389340c --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java @@ -0,0 +1,15 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; + + +public class CodegenOperation { + public String path, operationId, + returnType; + + // legacy support + public String nickname; +} diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java index 662e6c9700cb..f9ee0655d294 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java @@ -6,6 +6,11 @@ import com.wordnik.swagger.models.properties.*; import java.util.*; public class CodegenProperty { - public String getter, setter, description, datatype, name, min, max, defaultValue; + public String baseName, complexType, getter, setter, description, datatype, name, + min, max, defaultValue; + public Double minimum, maximum, exclusiveMinimum, exclusiveMaximum; + public Boolean hasMore = null, required = null; + public boolean isPrimitiveType, isContainer, isNotContainer; + public List _enum; public Map allowableValues; -} \ No newline at end of file +} diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index e6d76675463b..e6ed76840118 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -1,5 +1,6 @@ package com.wordnik.swagger.codegen; +import com.wordnik.swagger.util.Json; import com.wordnik.swagger.models.*; import com.wordnik.swagger.models.properties.*; @@ -7,15 +8,16 @@ import java.util.*; import java.io.File; public class DefaultCodegen { - String outputFolder = ""; - Set defaultIncludes; - Map typeMapping; - Set reservedWords; - Map importMapping; - String modelPackage = "", apiPackage, fileSuffix; - Map apiTemplateFiles = new HashMap(); - Map modelTemplateFiles = new HashMap(); - String templateDir; + protected String outputFolder = ""; + protected Set defaultIncludes = new HashSet(); + protected Map typeMapping = 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; public Set defaultIncludes() { return defaultIncludes; @@ -26,6 +28,9 @@ public class DefaultCodegen { public Set reservedWords() { return reservedWords; } + public Set languageSpecificPrimitives() { + return languageSpecificPrimitives; + } public Map importMapping() { return importMapping; } @@ -41,9 +46,15 @@ public class DefaultCodegen { public String templateDir() { return templateDir; } + public Map apiTemplateFiles() { + return apiTemplateFiles; + } public Map modelTemplateFiles() { return modelTemplateFiles; } + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage().replaceAll("\\.", File.separator); + } public String modelFileFolder() { return outputFolder + File.separator + modelPackage().replaceAll("\\.", File.separator); } @@ -52,26 +63,38 @@ public class DefaultCodegen { this.templateDir = templateDir; } + public String toApiFilename(String name) { + return initialCaps(name); + } + public String toModelFilename(String name) { return name; } + public String toVarName(String name) { + return name; + } + + public String toModelImport(String name) { + return modelPackage() + "." + name; + } + public DefaultCodegen() { defaultIncludes = new HashSet( - Arrays.asList("double", - "int", - "long", - "short", - "char", - "float", - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float") - ); + Arrays.asList("double", + "int", + "long", + "short", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float") + ); typeMapping = new HashMap(); typeMapping.put("Array", "List"); @@ -82,6 +105,7 @@ public class DefaultCodegen { 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"); @@ -137,13 +161,20 @@ public class DefaultCodegen { return "null"; else if (p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; - String inner = toDeclaredType(ap.getItems()); - return "ArrayList<" + inner + ">() "; + String inner = getSwaggerType(ap.getItems()); + return "new ArrayList<" + inner + ">() "; + } + else { + System.out.println("unhandled property default value"); + Json.prettyPrint(p); + return "null"; } - return null; } - public String toDeclaredType(Property p) { + /** + * returns the swagger type for the property + **/ + public String getSwaggerType(Property p) { String datatype = null; if(p instanceof StringProperty) datatype = "string"; @@ -152,7 +183,7 @@ public class DefaultCodegen { else if(p instanceof DateProperty) datatype = "date"; else if(p instanceof DateTimeProperty) - datatype = "dateTime"; + datatype = "DateTime"; else if (p instanceof DoubleProperty) datatype = "double"; else if (p instanceof FloatProperty) @@ -163,6 +194,12 @@ public class DefaultCodegen { datatype = "long"; else if (p instanceof MapProperty) datatype = "map"; + 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(); @@ -170,15 +207,48 @@ public class DefaultCodegen { return datatype; } + public String initialCaps(String name) { + return Character.toUpperCase(name.charAt(0)) + name.substring(1); + } + + public String getTypeDeclaration(Property p) { + String swaggerType = getSwaggerType(p); + if(typeMapping.containsKey(swaggerType)) + return typeMapping.get(swaggerType); + return swaggerType; + } + + public String toApiName(String name) { + return initialCaps(name); + } + + public String toModelName(String name) { + return initialCaps(name); + } + public CodegenModel fromModel(String name, ModelImpl model) { CodegenModel m = new CodegenModel(); m.name = name; m.description = model.getDescription(); - m.classname = name; + m.classname = toModelName(name); + int count = 0; for(String key: model.getProperties().keySet()) { Property prop = model.getProperties().get(key); - m.vars.add(fromProperty(key, prop)); + if(prop == null) { + System.out.println("null property for " + key); + Json.prettyPrint(model.getProperties()); + } + else { + CodegenProperty cp = fromProperty(key, prop); + if(cp.complexType != null && !defaultIncludes.contains(cp.complexType)) { + m.imports.add(cp.complexType); + } + m.vars.add(cp); + count += 1; + if(count != model.getProperties().keySet().size()) + cp.hasMore = new Boolean(true); + } } return m; } @@ -186,19 +256,92 @@ public class DefaultCodegen { public CodegenProperty fromProperty(String name, Property p) { CodegenProperty property = new CodegenProperty(); - property.name = name; - + property.name = toVarName(name); + property.baseName = name; + property.description = p.getDescription(); property.getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1); property.setter = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); property.defaultValue = toDefaultValue(p); - String datatype = toDeclaredType(p); + property.required = p.getRequired(); - if(typeMapping.containsKey(datatype)) { - property.datatype = typeMapping.get(datatype); + 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; + if(sp.getEnum() != null) { + List _enum = sp.getEnum(); + property._enum = _enum; + + // legacy support + Map allowableValues = new HashMap(); + allowableValues.put("values", _enum); + property.allowableValues = allowableValues; + } + } + + property.datatype = getTypeDeclaration(p); + + if(languageSpecificPrimitives().contains(type)) { + property.isPrimitiveType = true; } else - property.datatype = datatype; + property.complexType = type; + if(p instanceof ArrayProperty) + property.isContainer = true; + else + property.isNotContainer = true; return property; } + + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation){ + CodegenOperation op = new CodegenOperation(); + + String operationId = operation.getOperationId(); + if(operationId == null) + operationId = "fixme"; + op.path = path; + op.operationId = operationId; + + Response methodResponse = null; + + if(operation.getResponses() != null) { + for(String responseCode: operation.getResponses().keySet()) { + Response response = operation.getResponses().get(responseCode); + if("200".equals(responseCode)) { + methodResponse = response; + } + } + if(methodResponse == null && operation.getResponses().keySet().contains("default")) + methodResponse = operation.getResponses().get("default"); + } + + if(methodResponse != null && methodResponse.getSchema() != null) { + CodegenProperty responseModel = fromProperty("response", methodResponse.getSchema()); + Json.prettyPrint(responseModel); + op.returnType = responseModel.datatype; + } + + + // legacy support + op.nickname = operationId; + + return op; + } } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index d1f8eaad17eb..8a084ecd1a8c 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -20,8 +20,8 @@ public class DefaultGenerator implements Generator { public void generate(Swagger swagger) { try { + // models Map definitions = swagger.getDefinitions(); - for(String name: definitions.keySet()) { Model model = definitions.get(name); Map modelMap = new HashMap(); @@ -39,12 +39,77 @@ public class DefaultGenerator implements Generator { writeToFile(filename, tmpl.execute(models)); } } + // apis + Map> paths = groupPaths(swagger.getPaths()); + for(String tag: paths.keySet()) { + List ops = paths.get(tag); + + Object tagObject = processOperations(config, tag, ops); + Json.prettyPrint(tagObject); + + 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() + .defaultValue("") + .compile(template); + + writeToFile(filename, tmpl.execute(tagObject)); + } + + } } catch (Exception e) { e.printStackTrace(); } } + public void processOperation(String tag, String resourcePath, String httpMethod, Operation operation, Map> operations) { + if(tag == null) + tag = "default"; + + List opList = operations.get(tag); + if(opList == null) { + opList = new ArrayList(); + operations.put(tag, opList); + } + CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation); + opList.add(co); + } + + public Map> groupPaths(Map paths) { + // group by tag, create a Default grouping if none + Map> ops = new HashMap>(); + List tags = null; + + for(String resourcePath: paths.keySet()) { + Path path = paths.get(resourcePath); + Operation get = path.getGet(); + if(get != null) { + tags = get.getTags(); + if(tags != null && tags.size() > 0) { + for(String tag: tags) { + processOperation(tag, resourcePath, "get", get, ops); + } + } + else { + processOperation(null, resourcePath, "get", get, ops); + } + } + // List ops = ops + Operation put = path.getPut(); + Operation post = path.getPost(); + Operation delete = path.getDelete(); + Operation patch = path.getPatch(); + Operation options = path.getOptions(); + + } + Json.prettyPrint(ops); + return ops; + } + public File writeToFile(String filename, String contents) throws IOException { System.out.println("writing file " + filename); File output = new File(filename); @@ -77,11 +142,21 @@ public class DefaultGenerator implements Generator { throw new RuntimeException("can't load template " + 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); + 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 HashSet(); for(String key: definitions.keySet()) { Model mm = definitions.get(key); if(mm instanceof ModelImpl) { @@ -89,9 +164,24 @@ public class DefaultGenerator implements Generator { 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 HashMap(); + String m = config.importMapping().get(i); + if(m == null) + m = config.toModelImport(i); + if(m != null) { + im.put("import", m); + imports.add(im); + } + } + + objs.put("imports", imports); return objs; } } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/JavaCodegen.java b/src/main/java/com/wordnik/swagger/codegen/JavaCodegen.java deleted file mode 100644 index c8765558174d..000000000000 --- a/src/main/java/com/wordnik/swagger/codegen/JavaCodegen.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.wordnik.swagger.codegen; - -public class JavaCodegen extends DefaultCodegen implements CodegenConfig { - public JavaCodegen() { - super(); - outputFolder = "generated-code/java"; - modelTemplateFiles.put("model.mustache", ".java"); - apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "Java"; - modelPackage = "com.wordnik.model"; - } - - -} \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/Person.java b/src/main/java/com/wordnik/swagger/codegen/Person.java deleted file mode 100644 index c59492237ff0..000000000000 --- a/src/main/java/com/wordnik/swagger/codegen/Person.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.wordnik.swagger.codegen; - -public class Person { - public final String name; - public Person (String name, int age) { - this.name = name; - _age = age; - } - public int getAge () { - return _age; - } - protected int _age; -} \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java new file mode 100644 index 000000000000..e2e78d4fd383 --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -0,0 +1,61 @@ +package com.wordnik.swagger.codegen.languages; + +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.properties.*; + +import java.util.*; + +public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { + public JavaClientCodegen() { + super(); + outputFolder = "generated-code/java"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "Java"; + apiPackage = "com.wordnik.api"; + modelPackage = "com.wordnik.model"; + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float") + ); + } + + @Override + public String toModelImport(String name) { + return null; + } + + @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) { + throw new RuntimeException("not supported yet"); + } + 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/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java new file mode 100644 index 000000000000..a50afe77d69f --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -0,0 +1,136 @@ +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(); + + 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 = "com.wordnik.model"; + + defaultIncludes = new HashSet( + Arrays.asList("bool", + "int", + "NSString", + "NSObject", + "NSArray", + "NSNumber") + ); + 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" + )); + + 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("array", "NSArray"); + typeMapping.put("List", "NSArray"); + typeMapping.put("object", "NSObject"); + + importMapping = new HashMap (); + importMapping.put("Date", "SWGDate"); + + foundationClasses = new HashSet ( + Arrays.asList( + "NSNumber", + "NSObject", + "NSString") + ); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + System.out.println("checking type mapping for " + swaggerType); + 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 "SWG" + Character.toUpperCase(type.charAt(0)) + type.substring(1); + } + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + "models"; + } + + @Override + public String toModelFilename(String name) { + return "SWG" + name; + } + + @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/src/main/resources/Java/api.mustache b/src/main/resources/Java/api.mustache index 91472d131e11..87c764417d55 100644 --- a/src/main/resources/Java/api.mustache +++ b/src/main/resources/Java/api.mustache @@ -35,7 +35,7 @@ public class {{classname}} { {{/responseModel}}{{^responseModel}} {{/responseModel}} {{/errorList}} - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { Object postBody = {{#bodyParam}}{{bodyParam}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#requiredParamCount}} // verify required params are set diff --git a/src/main/resources/Java/model.mustache b/src/main/resources/Java/model.mustache index f6a493e3e3a3..938daf4d5f67 100644 --- a/src/main/resources/Java/model.mustache +++ b/src/main/resources/Java/model.mustache @@ -4,24 +4,23 @@ package {{package}}; {{/imports}} {{#models}} -{{#model}} -public class {{classname}} { - {{#vars}} - - {{#description}}/* {{{description}}} */ - {{/description}} - private {{{datatype}}} {{name}} = {{{defaultValue}}}; - {{#allowableValues}}{{#min}} // range from {{min}} to {{max}} - {{/min}} +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +public class {{classname}} { {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}} + * required: {{required}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{#allowableValues}} + //{{^min}}public enum {{name}}Enum { {{#values}} {{.}}, {{/values}} }; - {{/min}} - {{/allowableValues}} + {{/min}}{{/allowableValues}}{{/vars}} - {{/vars}} - - {{#vars}} - - public {{{datatype}}} {{getter}}() { + {{#vars}}public {{{datatype}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatype}}} {{name}}) { @@ -34,10 +33,8 @@ public class {{classname}} { public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); - {{#vars}} - sb.append(" {{name}}: ").append({{name}}).append("\n"); - {{/vars}} - sb.append("}\n"); + {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); + {{/vars}}sb.append("}\n"); return sb.toString(); } } diff --git a/src/main/resources/objc/model-body.mustache b/src/main/resources/objc/model-body.mustache index f927adedb00b..190d9bfc308d 100644 --- a/src/main/resources/objc/model-body.mustache +++ b/src/main/resources/objc/model-body.mustache @@ -5,10 +5,10 @@ @implementation {{classname}} --(id){{#vars}}{{name}}: ({{datatype}}) {{name}}{{#hasMore}}{{newline}} {{/hasMore}}{{/vars}}{{newline}}{ - {{#vars}}_{{name}} = {{name}}; - {{/vars}} - +-(id){{#vars}}{{name}}: ({{datatype}}) {{name}}{{^hasMore}} { {{/hasMore}} + {{/vars}} + {{#vars}}_{{name}} = {{name}}; + {{/vars}} return self; } @@ -16,16 +16,9 @@ { self = [super init]; if(self) { - {{#vars}} - - {{#isPrimitiveType}} - _{{name}} = dict[@"{{baseName}}"]; - {{/isPrimitiveType}} - {{#complexType}} - id {{name}}_dict = dict[@"{{baseName}}"]; - {{#isContainer}} + {{#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) { @@ -44,21 +37,16 @@ _{{name}} = [[NSArray alloc] init]; } {{/isContainer}} - {{#isNotContainer}} - if({{name}}_dict != nil) + {{#isNotContainer}}if({{name}}_dict != nil) _{{name}} = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{complexType}}} {{/instantiationType}} alloc]initWithValues:{{name}}_dict]; - {{/isNotContainer}} - {{/complexType}} - {{/vars}}{{newline}} + {{/isNotContainer}}{{/complexType}}{{/vars}} } return self; } -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; - {{#vars}} - {{#complexType}} - if(_{{name}} != nil){ + {{#vars}}{{#complexType}}if(_{{name}} != nil){ if([_{{name}} isKindOfClass:[NSArray class]]){ NSMutableArray * array = [[NSMutableArray alloc] init]; for( {{complexType}} *{{name}} in (NSArray*)_{{name}}) { @@ -73,14 +61,12 @@ } } else { - {{/complexType}} - if(_{{name}} != nil) dict[@"{{baseName}}"] = {{#complexType}}[(SWGObject*){{/complexType}}_{{name}} {{#complexType}}asDictionary]{{/complexType}}; - {{#complexType}} + if(_{{name}} != nil) dict[@"{{baseName}}"] = [(SWGObject*)_{{name}} asDictionary]; } } - {{/complexType}} - {{/vars}} - + {{/complexType}}{{#isPrimitiveType}}if(_{{name}} != nil) + dict[@"{{baseName}}"] = [(SWGObject*)_{{name}} asDictionary]; + {{/isPrimitiveType}}{{/vars}} NSDictionary* output = [dict copy]; return output; } diff --git a/swagger.json b/swagger.json index a9a0e2cb3420..4e8fe2310e6d 100644 --- a/swagger.json +++ b/swagger.json @@ -275,7 +275,10 @@ "200": { "description": "successful operation", "schema": { - "$ref": "#/definitions/Pet" + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } } }, "400": { @@ -417,7 +420,10 @@ "200": { "description": "successful operation", "schema": { - "$ref": "#/definitions/Pet" + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } } }, "400": { @@ -600,15 +606,22 @@ }, "Pet": { "enum": [ + "id", "photoUrls", "name" ], "properties": { - "tags": { - "type": "array", - "items": { - "$ref": "Tag" - } + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "Category" + }, + "name": { + "type": "string", + "example": "doggie", + "position": 0 }, "photoUrls": { "type": "array", @@ -616,17 +629,11 @@ "type": "string" } }, - "category": { - "$ref": "Category" - }, - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string", - "example": "doggie", - "position": 0 + "tags": { + "type": "array", + "items": { + "$ref": "Tag" + } }, "status": { "type": "string", @@ -646,31 +653,35 @@ } }, "Order": { + "description": "All you ever needed to know about orders", + "enum": [ "id" ], "properties": { - "complete": { - "type": "boolean" + "id": { + "description": "the unique ID for the order", + "type": "integer", + "format": "int64" + }, + "petId": { + "description": "the ID of the pet being purchased", + "type": "integer", + "format": "int64" + }, + "quantity": { + "description": "number of pets in the order", + "type": "integer", + "format": "int32", + "minimum": 1, + "maximum": 100 + }, + "status": { + "type": "string", + "enum": [ "dead", "alive" ] }, "shipDate": { "type": "string", "format": "date-time" - }, - "quantity": { - "type": "integer", - "format": "int32" - }, - "petId": { - "type": "integer", - "format": "int64" - }, - "id": { - "type": "integer", - "format": "int64" - }, - "status": { - "type": "string", - "position": 0 } } } } -} \ No newline at end of file +} From 6f63ba43ad3f83f142ce65261d139b5cff18cad0 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 3 Sep 2014 00:38:24 -0700 Subject: [PATCH 004/325] added return types, media types --- .../com/wordnik/swagger/codegen/Codegen.java | 1 - .../swagger/codegen/CodegenConfig.java | 3 +- .../swagger/codegen/CodegenOperation.java | 10 +- .../swagger/codegen/CodegenParameter.java | 5 + .../swagger/codegen/DefaultCodegen.java | 169 ++++++++++++++++-- .../swagger/codegen/DefaultGenerator.java | 71 ++++---- .../codegen/languages/JavaClientCodegen.java | 2 + src/main/resources/Java/api.mustache | 7 +- swagger.json | 32 +++- 9 files changed, 237 insertions(+), 63 deletions(-) create mode 100644 src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index b62a8f40d926..19f31b80d3e0 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -23,7 +23,6 @@ public class Codegen extends DefaultGenerator { } } - try{ Swagger swagger = (Swagger) Json.mapper() .readValue(new File("swagger.json"), Swagger.class); diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java index e33fcf29121d..60da0c43e429 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -5,6 +5,7 @@ import com.wordnik.swagger.models.*; import java.util.*; public interface CodegenConfig { + Map additionalProperties(); String apiPackage(); String apiFileFolder(); String fileSuffix(); @@ -16,7 +17,7 @@ public interface CodegenConfig { Set reservedWords(); - CodegenModel fromModel(String name, ModelImpl model); + CodegenModel fromModel(String name, Model model); CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation); Set defaultIncludes(); Map typeMapping(); diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java b/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java index 9c826389340c..0d23fa86e9ac 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java @@ -7,8 +7,14 @@ import java.util.*; public class CodegenOperation { - public String path, operationId, - returnType; + public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer; + public List> consumes, produces; + 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(); // legacy support public String nickname; diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java new file mode 100644 index 000000000000..4f9d709c38f6 --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java @@ -0,0 +1,5 @@ +package com.wordnik.swagger.codegen; + +public class CodegenParameter { + public String baseName, paramName, dataType, collectionFormat; +} \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index e6ed76840118..cae3346e7532 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -2,6 +2,7 @@ package com.wordnik.swagger.codegen; import com.wordnik.swagger.util.Json; import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.parameters.*; import com.wordnik.swagger.models.properties.*; import java.util.*; @@ -18,6 +19,7 @@ public class DefaultCodegen { protected Map apiTemplateFiles = new HashMap(); protected Map modelTemplateFiles = new HashMap(); protected String templateDir; + protected Map additionalProperties = new HashMap(); public Set defaultIncludes() { return defaultIncludes; @@ -58,6 +60,9 @@ public class DefaultCodegen { public String modelFileFolder() { return outputFolder + File.separator + modelPackage().replaceAll("\\.", File.separator); } + public Map additionalProperties() { + return additionalProperties; + } public void setTemplateDir(String templateDir) { this.templateDir = templateDir; @@ -166,7 +171,7 @@ public class DefaultCodegen { } else { System.out.println("unhandled property default value"); - Json.prettyPrint(p); + // Json.prettyPrint(p); return "null"; } } @@ -226,28 +231,40 @@ public class DefaultCodegen { return initialCaps(name); } - public CodegenModel fromModel(String name, ModelImpl model) { + public CodegenModel fromModel(String name, Model model) { CodegenModel m = new CodegenModel(); m.name = name; m.description = model.getDescription(); m.classname = toModelName(name); int count = 0; - for(String key: model.getProperties().keySet()) { - Property prop = model.getProperties().get(key); - if(prop == null) { - System.out.println("null property for " + key); - Json.prettyPrint(model.getProperties()); - } - else { - CodegenProperty cp = fromProperty(key, prop); - if(cp.complexType != null && !defaultIncludes.contains(cp.complexType)) { - m.imports.add(cp.complexType); + if(model instanceof ArrayModel) { + ArrayModel am = (ArrayModel) model; + ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); + CodegenProperty cp = fromProperty(name, arrayProperty); + m.vars.add(cp); + } + else if (model instanceof RefModel) { + + } + else { + ModelImpl impl = (ModelImpl) model; + for(String key: impl.getProperties().keySet()) { + Property prop = impl.getProperties().get(key); + if(prop == null) { + System.out.println("null property for " + key); + // Json.prettyPrint(impl.getProperties()); + } + else { + CodegenProperty cp = fromProperty(key, prop); + 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); } - m.vars.add(cp); - count += 1; - if(count != model.getProperties().keySet().size()) - cp.hasMore = new Boolean(true); } } return m; @@ -321,6 +338,34 @@ public class DefaultCodegen { 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; + } + + 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; + } + if(operation.getResponses() != null) { for(String responseCode: operation.getResponses().keySet()) { Response response = operation.getResponses().get(responseCode); @@ -334,11 +379,101 @@ public class DefaultCodegen { if(methodResponse != null && methodResponse.getSchema() != null) { CodegenProperty responseModel = fromProperty("response", methodResponse.getSchema()); - Json.prettyPrint(responseModel); + + Property responseProperty = methodResponse.getSchema(); + if(responseProperty instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) responseProperty; + CodegenProperty innerProperty = fromProperty("response", ap.getItems()); + + op.returnBaseType = innerProperty.datatype; + } + else + op.returnBaseType = responseModel.datatype; + op.returnType = responseModel.datatype; + if(responseModel.isContainer) + op.returnContainer = responseModel.complexType; + } + List parameters = operation.getParameters(); + 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 = new CodegenParameter(); + p.baseName = param.getName(); + + if(param instanceof SerializableParameter) { + SerializableParameter qp = (SerializableParameter) param; + Property property = null; + String collectionFormat = null; + if("array".equals(qp.getType())) { + Property inner = qp.getItems(); + property = new ArrayProperty(inner); + collectionFormat = qp.getCollectionFormat(); + } + else + property = PropertyBuilder.build(qp.getType(), qp.getFormat(), null); + CodegenProperty model = fromProperty(qp.getName(), property); + p.collectionFormat = collectionFormat; + p.dataType = model.datatype; + p.paramName = qp.getName(); + } + else { + BodyParameter bp = (BodyParameter) param; + Model model = bp.getSchema(); + + if(model instanceof ModelImpl) { + ModelImpl impl = (ModelImpl) model; + CodegenModel cm = fromModel(bp.getName(), impl); + p.dataType = cm.classname; + } + 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 + CodegenProperty cp = cm.vars.get(0); + p.dataType = cp.datatype; + } + else{ + Model sub = bp.getSchema(); + if(sub instanceof RefModel) + p.dataType = ((RefModel)sub).getSimpleRef(); + } + p.paramName = bp.getName(); + } + allParams.add(p); + if(param instanceof QueryParameter) + queryParams.add(p); + else if(param instanceof PathParameter) + pathParams.add(p); + else if(param instanceof HeaderParameter) + headerParams.add(p); + else if(param instanceof CookieParameter) + cookieParams.add(p); + else if(param instanceof BodyParameter) + bodyParams.add(p); + // else if(param instanceof FormParameter) + // formParams.add(p); + } + } + op.httpMethod = httpMethod.toUpperCase(); + op.allParams = allParams; + op.bodyParams = bodyParams; + op.pathParams = pathParams; + op.queryParams = queryParams; + op.headerParams = headerParams; + // op.cookieParams = cookieParams; + op.formParams = formParams; // legacy support op.nickname = operationId; diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 8a084ecd1a8c..c83fdb233f53 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -26,7 +26,8 @@ public class DefaultGenerator implements Generator { Model model = definitions.get(name); Map modelMap = new HashMap(); modelMap.put(name, model); - Object models = processModels(config, modelMap); + Map models = processModels(config, modelMap); + models.putAll(config.additionalProperties()); for(String templateName: config.modelTemplateFiles().keySet()) { String suffix = config.modelTemplateFiles().get(templateName); String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix; @@ -44,9 +45,8 @@ public class DefaultGenerator implements Generator { for(String tag: paths.keySet()) { List ops = paths.get(tag); - Object tagObject = processOperations(config, tag, ops); - Json.prettyPrint(tagObject); - + Map operations = processOperations(config, tag, ops); + operations.putAll(config.additionalProperties()); for(String templateName: config.apiTemplateFiles().keySet()) { String suffix = config.apiTemplateFiles().get(templateName); String filename = config.apiFileFolder() + File.separator + config.toApiFilename(tag) + suffix; @@ -56,7 +56,7 @@ public class DefaultGenerator implements Generator { .defaultValue("") .compile(template); - writeToFile(filename, tmpl.execute(tagObject)); + writeToFile(filename, tmpl.execute(operations)); } } @@ -66,19 +66,6 @@ public class DefaultGenerator implements Generator { } } - public void processOperation(String tag, String resourcePath, String httpMethod, Operation operation, Map> operations) { - if(tag == null) - tag = "default"; - - List opList = operations.get(tag); - if(opList == null) { - opList = new ArrayList(); - operations.put(tag, opList); - } - CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation); - opList.add(co); - } - public Map> groupPaths(Map paths) { // group by tag, create a Default grouping if none Map> ops = new HashMap>(); @@ -86,30 +73,37 @@ public class DefaultGenerator implements Generator { for(String resourcePath: paths.keySet()) { Path path = paths.get(resourcePath); - Operation get = path.getGet(); - if(get != null) { - tags = get.getTags(); - if(tags != null && tags.size() > 0) { - for(String tag: tags) { - processOperation(tag, resourcePath, "get", get, ops); - } - } - else { - processOperation(null, resourcePath, "get", get, ops); - } - } - // List ops = ops - Operation put = path.getPut(); - Operation post = path.getPost(); - Operation delete = path.getDelete(); - Operation patch = path.getPatch(); - Operation options = path.getOptions(); - + 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); } - Json.prettyPrint(ops); + // Json.prettyPrint(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) { + List opList = operations.get(tag); + if(opList == null) { + opList = new ArrayList(); + operations.put(tag, opList); + } + CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation); + opList.add(co); + } + } + } + public File writeToFile(String filename, String contents) throws IOException { System.out.println("writing file " + filename); File output = new File(filename); @@ -148,6 +142,7 @@ public class DefaultGenerator implements Generator { objs.put("classname", config.toApiName(tag)); objs.put("operation", ops); operations.put("operations", objs); + operations.put("package", config.apiPackage()); return operations; } diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index e2e78d4fd383..5b4252f2ba05 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -15,6 +15,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { apiPackage = "com.wordnik.api"; modelPackage = "com.wordnik.model"; + additionalProperties.put("invokerPackage", "com.wordnik.common"); + languageSpecificPrimitives = new HashSet( Arrays.asList( "String", diff --git a/src/main/resources/Java/api.mustache b/src/main/resources/Java/api.mustache index 87c764417d55..ae1d030955bf 100644 --- a/src/main/resources/Java/api.mustache +++ b/src/main/resources/Java/api.mustache @@ -21,11 +21,11 @@ public class {{classname}} { public ApiInvoker getInvoker() { return apiInvoker; } - + public void setBasePath(String basePath) { this.basePath = basePath; } - + public String getBasePath() { return basePath; } @@ -45,7 +45,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(); diff --git a/swagger.json b/swagger.json index 4e8fe2310e6d..de651aca641d 100644 --- a/swagger.json +++ b/swagger.json @@ -34,7 +34,10 @@ "description": "List of user object", "required": false, "schema": { - "$ref": "#/definitions/User" + "type": "array", + "items": { + "$ref": "#/definitions/User" + } } } ], @@ -558,6 +561,33 @@ "description": "Invalid ID supplied" } } + }, + "delete": { + "tags": [ + "pet" + ], + "summary": "Deletes a pet", + "description": "", + "operationId": "deletePet", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "path", + "name": "petId", + "description": "Pet id to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid pet value" + } + } } } }, From 7901d8a7c6ceff4e6eadaaf4151b39c0fe806071 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 3 Sep 2014 00:41:06 -0700 Subject: [PATCH 005/325] fixed api filenames --- src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index cae3346e7532..f90ddb0897db 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -69,7 +69,7 @@ public class DefaultCodegen { } public String toApiFilename(String name) { - return initialCaps(name); + return initialCaps(name) + "Api"; } public String toModelFilename(String name) { @@ -224,7 +224,7 @@ public class DefaultCodegen { } public String toApiName(String name) { - return initialCaps(name); + return initialCaps(name) + "Api"; } public String toModelName(String name) { From 73ad5022514ed1b6954c9a9353533ea4fc98517f Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 3 Sep 2014 01:10:02 -0700 Subject: [PATCH 006/325] updated 2.0 support for objc --- .../swagger/codegen/CodegenOperation.java | 4 +- .../swagger/codegen/DefaultCodegen.java | 18 ++++++- .../codegen/languages/ObjcClientCodegen.java | 1 - src/main/resources/objc/api-body.mustache | 53 ++++++++----------- src/main/resources/objc/api-header.mustache | 19 +++---- 5 files changed, 48 insertions(+), 47 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java b/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java index 0d23fa86e9ac..9c12f2296809 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java @@ -7,7 +7,9 @@ import java.util.*; public class CodegenOperation { - public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer; + public Boolean hasParams, returnTypeIsPrimitive, returnSimpleType; + public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer, + summary, notes; public List> consumes, produces; public List allParams = new ArrayList(); public List bodyParams = new ArrayList(); diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index f90ddb0897db..fc13d17d1649 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -335,6 +335,8 @@ public class DefaultCodegen { operationId = "fixme"; op.path = path; op.operationId = operationId; + op.summary = operation.getSummary(); + op.notes = operation.getDescription(); Response methodResponse = null; @@ -387,13 +389,23 @@ public class DefaultCodegen { op.returnBaseType = innerProperty.datatype; } - else - op.returnBaseType = responseModel.datatype; + else { + op.returnBaseType = responseModel.complexType; + + } op.returnType = responseModel.datatype; if(responseModel.isContainer) op.returnContainer = responseModel.complexType; + else + op.returnSimpleType = true; + if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null) + op.returnTypeIsPrimitive = true; + } + if(op.returnBaseType == null) { + op.returnTypeIsPrimitive = true; + op.returnSimpleType = true; } List parameters = operation.getParameters(); @@ -477,6 +489,8 @@ public class DefaultCodegen { // legacy support op.nickname = operationId; + if(op.allParams.size() > 0) + op.hasParams = true; return op; } } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index a50afe77d69f..e0c457dc2fe7 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -76,7 +76,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); String type = null; - System.out.println("checking type mapping for " + swaggerType); if(typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); if(languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) diff --git a/src/main/resources/objc/api-body.mustache b/src/main/resources/objc/api-body.mustache index 18571099c1e2..02e25263d8eb 100644 --- a/src/main/resources/objc/api-body.mustache +++ b/src/main/resources/objc/api-body.mustache @@ -69,17 +69,15 @@ static NSString * basePath = @"{{basePath}}"; NSString* requestContentType = @"application/json"; NSString* responseContentType = @"application/json"; - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; {{#queryParams}}if({{paramName}} != nil) - queryParams[@"{{baseName}}"] = {{paramName}}; - {{/queryParams}} - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + queryParams[@"{{baseName}}"] = {{paramName}};{{/queryParams}} + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; {{#headerParams}}if({{paramName}} != nil) - headerParams[@"{{baseName}}"] = {{paramName}}; - {{/headerParams}} + headerParams[@"{{baseName}}"] = {{paramName}};{{/headerParams}} id bodyDictionary = nil; - {{#bodyParam}} + {{#bodyParam}} if(body != nil && [body isKindOfClass:[NSArray class]]){ NSMutableArray * objs = [[NSMutableArray alloc] init]; for (id dict in (NSArray*)body) { @@ -170,22 +168,21 @@ static NSString * basePath = @"{{basePath}}"; {{#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}} + 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}}" @@ -201,10 +198,8 @@ static NSString * basePath = @"{{basePath}}"; } completionBlock(nil); }]; - {{/returnBaseType}} - {{/returnTypeIsPrimitive}} - {{#returnBaseType}} - {{^returnTypeIsPrimitive}} + {{/returnBaseType}}{{/returnTypeIsPrimitive}} + {{#returnBaseType}}{{^returnTypeIsPrimitive}} return [client dictionary:requestUrl method:@"{{httpMethod}}" queryParams:queryParams @@ -226,9 +221,7 @@ static NSString * basePath = @"{{basePath}}"; {{#returnBaseType}}completionBlock(result , nil);{{/returnBaseType}} {{/returnBaseType}} }]; - {{/returnTypeIsPrimitive}} - {{/returnBaseType}} - {{/returnSimpleType}} + {{/returnTypeIsPrimitive}}{{/returnBaseType}}{{/returnSimpleType}} {{newline}} } diff --git a/src/main/resources/objc/api-header.mustache b/src/main/resources/objc/api-header.mustache index 6b2091aed215..a66461d8ec2e 100644 --- a/src/main/resources/objc/api-header.mustache +++ b/src/main/resources/objc/api-header.mustache @@ -14,22 +14,15 @@ {{#operation}} /** - {{{summary}}} - {{#notes}} - {{{notes}}} - {{/notes}} + {{#summary}}{{{summary}}}{{/summary}} + {{#notes}}{{{notes}}}{{/notes}} - {{#allParams}} - @param {{paramName}} {{description}} + {{#allParams}}@param {{paramName}} {{description}} {{/allParams}} - */ --(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}} - -{{newline}} +-(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}} {{/operation}} - {{/operations}} @end \ No newline at end of file From ad3006d49c9dc7dc137c3f9de5dd516e1fc766c3 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 3 Sep 2014 10:20:13 -0700 Subject: [PATCH 007/325] added support for supporting files --- pom.xml | 7 ++ .../swagger/codegen/CodegenConfig.java | 4 ++ .../swagger/codegen/CodegenOperation.java | 7 +- .../swagger/codegen/CodegenParameter.java | 1 + .../swagger/codegen/CodegenProperty.java | 6 +- .../swagger/codegen/DefaultCodegen.java | 63 +++++++++++++++--- .../swagger/codegen/DefaultGenerator.java | 64 +++++++++++++++++-- .../swagger/codegen/SupportingFile.java | 13 ++++ .../codegen/languages/JavaClientCodegen.java | 28 +++++++- swagger.json | 8 ++- 10 files changed, 179 insertions(+), 22 deletions(-) create mode 100644 src/main/java/com/wordnik/swagger/codegen/SupportingFile.java diff --git a/pom.xml b/pom.xml index 5858d6e38f3e..d4d026e9d181 100644 --- a/pom.xml +++ b/pom.xml @@ -349,6 +349,12 @@ ${jmustache-version} compile + + commons-io + commons-io + ${commons-io-version} + compile + org.apache.maven maven-plugin-tools-api @@ -395,6 +401,7 @@ 2.3.4 1.5.0-SNAPSHOT 2.1.4 + 2.3 4.8.1 1.0.0 diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java index 60da0c43e429..0e72ed81665a 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -9,6 +9,7 @@ public interface CodegenConfig { String apiPackage(); String apiFileFolder(); String fileSuffix(); + String outputFolder(); String templateDir(); String modelFileFolder(); String modelPackage(); @@ -17,6 +18,8 @@ public interface CodegenConfig { Set reservedWords(); + List supportingFiles(); + CodegenModel fromModel(String name, Model model); CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation); Set defaultIncludes(); @@ -28,4 +31,5 @@ public interface CodegenConfig { String toApiFilename(String name); String toModelFilename(String name); String toModelImport(String name); + String toApiImport(String name); } diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java b/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java index 9c12f2296809..51dc2e19ad5d 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java @@ -8,8 +8,9 @@ import java.util.*; public class CodegenOperation { public Boolean hasParams, returnTypeIsPrimitive, returnSimpleType; - public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer, - summary, notes; + public String path, operationId, returnType, httpMethod, returnBaseType, + returnContainer, summary, notes; + public List> consumes, produces; public List allParams = new ArrayList(); public List bodyParams = new ArrayList(); @@ -18,6 +19,8 @@ public class CodegenOperation { public List headerParams = new ArrayList(); public List formParams = new ArrayList(); + public Set imports = new HashSet(); + // legacy support public String nickname; } diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java index 4f9d709c38f6..fa3f34bdfc7b 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java @@ -1,5 +1,6 @@ package com.wordnik.swagger.codegen; public class CodegenParameter { + public Boolean hasMore = null; public String baseName, paramName, dataType, collectionFormat; } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java index f9ee0655d294..e569c9a14fe3 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java @@ -6,11 +6,11 @@ import com.wordnik.swagger.models.properties.*; import java.util.*; public class CodegenProperty { - public String baseName, complexType, getter, setter, description, datatype, name, - min, max, defaultValue; + public String baseName, complexType, getter, setter, description, datatype, + name, min, max, defaultValue; public Double minimum, maximum, exclusiveMinimum, exclusiveMaximum; public Boolean hasMore = null, required = null; - public boolean isPrimitiveType, isContainer, isNotContainer; + public Boolean isPrimitiveType, isContainer, isNotContainer; public List _enum; public Map allowableValues; } diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index fc13d17d1649..eb77a76fa4c3 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -20,6 +20,7 @@ public class DefaultCodegen { protected Map modelTemplateFiles = new HashMap(); protected String templateDir; protected Map additionalProperties = new HashMap(); + protected List supportingFiles = new ArrayList(); public Set defaultIncludes() { return defaultIncludes; @@ -63,6 +64,12 @@ public class DefaultCodegen { public Map additionalProperties() { return additionalProperties; } + public List supportingFiles() { + return supportingFiles; + } + public String outputFolder() { + return outputFolder; + } public void setTemplateDir(String templateDir) { this.templateDir = templateDir; @@ -84,6 +91,10 @@ public class DefaultCodegen { return modelPackage() + "." + name; } + public String toApiImport(String name) { + return apiPackage() + "." + name; + } + public DefaultCodegen() { defaultIncludes = new HashSet( Arrays.asList("double", @@ -329,6 +340,7 @@ public class DefaultCodegen { public CodegenOperation fromOperation(String path, String httpMethod, Operation operation){ CodegenOperation op = new CodegenOperation(); + Set imports = new HashSet(); String operationId = operation.getOperationId(); if(operationId == null) @@ -390,18 +402,24 @@ public class DefaultCodegen { op.returnBaseType = innerProperty.datatype; } else { - op.returnBaseType = responseModel.complexType; - + if(responseModel.complexType != null) + op.returnBaseType = responseModel.complexType; + else + op.returnBaseType = responseModel.datatype; } + imports.add(op.returnBaseType); + op.returnType = responseModel.datatype; - if(responseModel.isContainer) + if(responseModel.isContainer != null) op.returnContainer = responseModel.complexType; else op.returnSimpleType = true; if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null) op.returnTypeIsPrimitive = true; } + else { + } if(op.returnBaseType == null) { op.returnTypeIsPrimitive = true; @@ -478,14 +496,23 @@ public class DefaultCodegen { // formParams.add(p); } } + for(String i: imports) { + if(!defaultIncludes.contains(i) && !languageSpecificPrimitives.contains(i)){ + if(typeMapping.keySet().contains(i)) { + op.imports.add(typeMapping.get(i)); + } + else + op.imports.add(i); + } + } op.httpMethod = httpMethod.toUpperCase(); - op.allParams = allParams; - op.bodyParams = bodyParams; - op.pathParams = pathParams; - op.queryParams = queryParams; - op.headerParams = headerParams; + 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 = formParams; + op.formParams = addHasMore(formParams); // legacy support op.nickname = operationId; @@ -493,4 +520,22 @@ public class DefaultCodegen { op.hasParams = true; return op; } + + private List addHasMore(List objs) { + if(objs != null) { + for(int i = 0; i < objs.size() - 1; i++) { + 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++) { + objs.put("hasMore", true); + } + } + return objs; + } } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index c83fdb233f53..3200d2d9336b 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -6,6 +6,7 @@ import com.wordnik.swagger.util.*; import com.samskivert.mustache.*; +import org.apache.commons.io.FileUtils; import java.util.*; import java.io.*; @@ -20,13 +21,15 @@ public class DefaultGenerator implements Generator { public void generate(Swagger swagger) { try { + Map models = null; + Map operations = null; // models Map definitions = swagger.getDefinitions(); for(String name: definitions.keySet()) { Model model = definitions.get(name); Map modelMap = new HashMap(); modelMap.put(name, model); - Map models = processModels(config, modelMap); + models = processModels(config, modelMap); models.putAll(config.additionalProperties()); for(String templateName: config.modelTemplateFiles().keySet()) { String suffix = config.modelTemplateFiles().get(templateName); @@ -45,11 +48,14 @@ public class DefaultGenerator implements Generator { for(String tag: paths.keySet()) { List ops = paths.get(tag); - Map operations = processOperations(config, tag, ops); + operations = processOperations(config, tag, ops); operations.putAll(config.additionalProperties()); for(String templateName: config.apiTemplateFiles().keySet()) { String suffix = config.apiTemplateFiles().get(templateName); - String filename = config.apiFileFolder() + File.separator + config.toApiFilename(tag) + suffix; + String filename = config.apiFileFolder() + + File.separator + + config.toApiFilename(tag) + + suffix; String template = readTemplate(config.templateDir() + File.separator + templateName); Template tmpl = Mustache.compiler() @@ -58,7 +64,32 @@ public class DefaultGenerator implements Generator { writeToFile(filename, tmpl.execute(operations)); } - + } + + // supporting files + Map bundle = new HashMap(); + bundle.putAll(config.additionalProperties()); + 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() + .defaultValue("") + .compile(template); + + writeToFile(outputFilename, tmpl.execute(bundle)); + } + else { + String template = readTemplate(config.templateDir() + File.separator + support.templateFile); + FileUtils.writeStringToFile(new File(outputFilename), template); + } } } catch (Exception e) { @@ -143,6 +174,31 @@ public class DefaultGenerator implements Generator { objs.put("operation", ops); operations.put("operations", objs); operations.put("package", config.apiPackage()); + + Set allImports = new HashSet(); + for(CodegenOperation op: ops) { + allImports.addAll(op.imports); + } + + List> imports = new ArrayList>(); + for(String i: allImports) { + Map im = new HashMap(); + String m = config.importMapping().get(i); + if(m == null) + m = config.toModelImport(i); + + System.out.println("adding import " + i + ", " + m); + if(m != null) { + im.put("import", m); + imports.add(im); + } + } + + operations.put("imports", imports); + + Json.prettyPrint(allImports); + Json.prettyPrint(imports); + return operations; } diff --git a/src/main/java/com/wordnik/swagger/codegen/SupportingFile.java b/src/main/java/com/wordnik/swagger/codegen/SupportingFile.java new file mode 100644 index 000000000000..85f08bfa70c3 --- /dev/null +++ b/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/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 5b4252f2ba05..8f0eccab81f4 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -4,8 +4,15 @@ 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 = "com.wordnik.api"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/java"; + public JavaClientCodegen() { super(); outputFolder = "generated-code/java"; @@ -15,7 +22,18 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { apiPackage = "com.wordnik.api"; modelPackage = "com.wordnik.model"; - additionalProperties.put("invokerPackage", "com.wordnik.common"); + 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( @@ -30,8 +48,12 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { } @Override - public String toModelImport(String name) { - return null; + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replaceAll("\\.", File.separator); + } + + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replaceAll("\\.", File.separator); } @Override diff --git a/swagger.json b/swagger.json index de651aca641d..5227492f2073 100644 --- a/swagger.json +++ b/swagger.json @@ -203,7 +203,13 @@ "in": "body", "name": "body", "description": "List of user object", - "required": false + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } } ], "responses": { From bc0cc567d97cd365611b8e16253d6229e47f6a60 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 3 Sep 2014 11:07:48 -0700 Subject: [PATCH 008/325] updated output filenames --- .../swagger/codegen/DefaultCodegen.java | 13 ++++++---- .../swagger/codegen/DefaultGenerator.java | 4 ---- .../codegen/languages/ObjcClientCodegen.java | 24 ++++++++++++++++--- 3 files changed, 29 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index eb77a76fa4c3..0e3d5fc7eb3e 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -88,7 +88,10 @@ public class DefaultCodegen { } public String toModelImport(String name) { - return modelPackage() + "." + name; + if("".equals(modelPackage())) + return name; + else + return modelPackage() + "." + name; } public String toApiImport(String name) { @@ -181,7 +184,7 @@ public class DefaultCodegen { return "new ArrayList<" + inner + ">() "; } else { - System.out.println("unhandled property default value"); + // System.out.println("unhandled property default value"); // Json.prettyPrint(p); return "null"; } @@ -402,14 +405,14 @@ public class DefaultCodegen { op.returnBaseType = innerProperty.datatype; } else { - if(responseModel.complexType != null) + if(responseModel.complexType != null) { op.returnBaseType = responseModel.complexType; + imports.add(responseModel.complexType); + } else op.returnBaseType = responseModel.datatype; } - imports.add(op.returnBaseType); - op.returnType = responseModel.datatype; if(responseModel.isContainer != null) op.returnContainer = responseModel.complexType; diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 3200d2d9336b..d5e4177cb36b 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -187,7 +187,6 @@ public class DefaultGenerator implements Generator { if(m == null) m = config.toModelImport(i); - System.out.println("adding import " + i + ", " + m); if(m != null) { im.put("import", m); imports.add(im); @@ -196,9 +195,6 @@ public class DefaultGenerator implements Generator { operations.put("imports", imports); - Json.prettyPrint(allImports); - Json.prettyPrint(imports); - return operations; } diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index e0c457dc2fe7..007abe9b7a3a 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -18,7 +18,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { apiTemplateFiles.put("api-header.mustache", ".h"); apiTemplateFiles.put("api-body.mustache", ".m"); templateDir = "objc"; - modelPackage = "com.wordnik.model"; + modelPackage = ""; defaultIncludes = new HashSet( Arrays.asList("bool", @@ -109,14 +109,32 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { } } + @Override + public String toModelImport(String name) { + name = name + ".h"; + if("".equals(modelPackage())) + return name; + else + return modelPackage() + "." + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + "client"; + } + @Override public String modelFileFolder() { - return outputFolder + File.separator + "models"; + return outputFolder + File.separator + "client"; } @Override public String toModelFilename(String name) { - return "SWG" + name; + return "SWG" + initialCaps(name); + } + + public String toApiFilename(String name) { + return "SWG" + initialCaps(name); } @Override From 79c456ecfc40f9e34466fc77cbae53c050815c62 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 3 Sep 2014 11:18:19 -0700 Subject: [PATCH 009/325] updates for reserved words --- .../wordnik/swagger/codegen/CodegenConfig.java | 2 ++ .../wordnik/swagger/codegen/DefaultCodegen.java | 15 +++++++++++++-- .../codegen/languages/JavaClientCodegen.java | 5 +++++ src/main/resources/objc/model-header.mustache | 3 ++- 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java index 0e72ed81665a..cd0e166b18e5 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -15,6 +15,8 @@ public interface CodegenConfig { String modelPackage(); String toApiName(String name); String toModelName(String name); + String toParamName(String name); + String escapeReservedWord(String name); Set reservedWords(); diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 0e3d5fc7eb3e..1b242d086890 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -87,6 +87,17 @@ public class DefaultCodegen { 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; @@ -457,7 +468,7 @@ public class DefaultCodegen { CodegenProperty model = fromProperty(qp.getName(), property); p.collectionFormat = collectionFormat; p.dataType = model.datatype; - p.paramName = qp.getName(); + p.paramName = toParamName(qp.getName()); } else { BodyParameter bp = (BodyParameter) param; @@ -482,7 +493,7 @@ public class DefaultCodegen { if(sub instanceof RefModel) p.dataType = ((RefModel)sub).getSimpleRef(); } - p.paramName = bp.getName(); + p.paramName = toParamName(bp.getName()); } allParams.add(p); if(param instanceof QueryParameter) diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 8f0eccab81f4..8ec271fad1e1 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -47,6 +47,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { ); } + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + @Override public String apiFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replaceAll("\\.", File.separator); diff --git a/src/main/resources/objc/model-header.mustache b/src/main/resources/objc/model-header.mustache index 80b4458bca89..9dc5f15f4e84 100644 --- a/src/main/resources/objc/model-header.mustache +++ b/src/main/resources/objc/model-header.mustache @@ -11,7 +11,8 @@ {{#vars}} @property(nonatomic) {{datatype}} {{name}}; {{#description}}/* {{{description}}} {{#isNotRequired}}[optional]{{/isNotRequired}} */{{/description}}{{newline}} {{/vars}} -- (id) {{#vars}}{{name}}: ({{datatype}}) {{name}}{{#hasMore}}{{newline}} {{/hasMore}}{{^hasMore}};{{/hasMore}} +- (id) {{#vars}}{{name}}: ({{datatype}}) {{name}}{{#hasMore}} + {{/hasMore}}{{^hasMore}};{{/hasMore}} {{/vars}} {{newline}} - (id) initWithValues: (NSDictionary*)dict; From fbf83983241eb99031adf1df14330e8f1ce81228 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 3 Sep 2014 22:10:34 -0700 Subject: [PATCH 010/325] fixes for return types, arrays --- .../swagger/codegen/CodegenConfig.java | 4 + .../swagger/codegen/CodegenParameter.java | 2 +- .../swagger/codegen/CodegenProperty.java | 4 +- .../swagger/codegen/DefaultCodegen.java | 121 ++++++++++++------ .../swagger/codegen/DefaultGenerator.java | 2 +- .../codegen/languages/ObjcClientCodegen.java | 36 +++++- src/main/resources/objc/api-body.mustache | 5 +- src/main/resources/objc/api-header.mustache | 5 +- src/main/resources/objc/model-header.mustache | 2 +- 9 files changed, 130 insertions(+), 51 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java index cd0e166b18e5..78604490ba16 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -1,6 +1,7 @@ package com.wordnik.swagger.codegen; import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.properties.*; import java.util.*; @@ -18,6 +19,9 @@ public interface CodegenConfig { String toParamName(String name); String escapeReservedWord(String name); + String getTypeDeclaration(Property p); + String getTypeDeclaration(String name); + Set reservedWords(); List supportingFiles(); diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java index fa3f34bdfc7b..70e0f59f7d55 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java @@ -1,6 +1,6 @@ package com.wordnik.swagger.codegen; public class CodegenParameter { - public Boolean hasMore = null; + public Boolean hasMore = null, isContainer = null, secondaryParam = null; public String baseName, paramName, dataType, collectionFormat; } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java index e569c9a14fe3..e1ff535362f7 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java @@ -7,9 +7,9 @@ import java.util.*; public class CodegenProperty { public String baseName, complexType, getter, setter, description, datatype, - name, min, max, defaultValue; + name, min, max, defaultValue, baseType; public Double minimum, maximum, exclusiveMinimum, exclusiveMaximum; - public Boolean hasMore = null, required = null; + public Boolean hasMore = null, required = null, secondaryParam = null; public Boolean isPrimitiveType, isContainer, isNotContainer; public List _enum; public Map allowableValues; diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 1b242d086890..04bc9f55bcb1 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -196,7 +196,6 @@ public class DefaultCodegen { } else { // System.out.println("unhandled property default value"); - // Json.prettyPrint(p); return "null"; } } @@ -241,6 +240,10 @@ public class DefaultCodegen { 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)) @@ -278,7 +281,6 @@ public class DefaultCodegen { Property prop = impl.getProperties().get(key); if(prop == null) { System.out.println("null property for " + key); - // Json.prettyPrint(impl.getProperties()); } else { CodegenProperty cp = fromProperty(key, prop); @@ -289,9 +291,27 @@ public class DefaultCodegen { 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); } } } + return m; } @@ -339,16 +359,21 @@ public class DefaultCodegen { } property.datatype = getTypeDeclaration(p); + property.baseType = getSwaggerType(p); - if(languageSpecificPrimitives().contains(type)) { - property.isPrimitiveType = true; - } - else - property.complexType = type; - if(p instanceof ArrayProperty) + if(p instanceof ArrayProperty) { property.isContainer = true; - else + ArrayProperty ap = (ArrayProperty) p; + CodegenProperty cp = fromProperty("inner", ap.getItems()); + property.baseType = cp.baseType; + if(!languageSpecificPrimitives.contains(cp.baseType)) + property.complexType = cp.baseType; + } + else { property.isNotContainer = true; + if(languageSpecificPrimitives().contains(type)) + property.isPrimitiveType = true; + } return property; } @@ -401,45 +426,48 @@ public class DefaultCodegen { methodResponse = response; } } - if(methodResponse == null && operation.getResponses().keySet().contains("default")) + if(methodResponse == null && operation.getResponses().keySet().contains("default")) { methodResponse = operation.getResponses().get("default"); + } } if(methodResponse != null && methodResponse.getSchema() != null) { - CodegenProperty responseModel = fromProperty("response", methodResponse.getSchema()); + 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.datatype; + op.returnBaseType = innerProperty.baseType; } else { - if(responseModel.complexType != null) { - op.returnBaseType = responseModel.complexType; - imports.add(responseModel.complexType); - } + if(cm.complexType != null) + op.returnBaseType = cm.complexType; else - op.returnBaseType = responseModel.datatype; + op.returnBaseType = cm.baseType; } - op.returnType = responseModel.datatype; - if(responseModel.isContainer != null) - op.returnContainer = responseModel.complexType; + op.returnType = cm.datatype; + if(cm.isContainer != null) { + op.returnContainer = cm.complexType; + } else op.returnSimpleType = true; if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null) op.returnTypeIsPrimitive = true; } - else { - } 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(); List allParams = new ArrayList(); List bodyParams = new ArrayList(); @@ -469,6 +497,9 @@ public class DefaultCodegen { 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; @@ -477,7 +508,8 @@ public class DefaultCodegen { if(model instanceof ModelImpl) { ModelImpl impl = (ModelImpl) model; CodegenModel cm = fromModel(bp.getName(), impl); - p.dataType = cm.classname; + p.dataType = getTypeDeclaration(cm.classname); + // imports.add(p.dataType); } else if(model instanceof ArrayModel) { // to use the built-in model parsing, we unwrap the ArrayModel @@ -485,13 +517,27 @@ public class DefaultCodegen { ArrayModel impl = (ArrayModel) model; CodegenModel cm = fromModel(bp.getName(), impl); // get the single property - CodegenProperty cp = cm.vars.get(0); - p.dataType = cp.datatype; + CodegenProperty cp = fromProperty("inner", impl.getItems()); + + imports.add(cp.baseType); + p.dataType = getTypeDeclaration(typeMapping.get(impl.getType())); + p.isContainer = true; } else{ Model sub = bp.getSchema(); - if(sub instanceof RefModel) - p.dataType = ((RefModel)sub).getSimpleRef(); + 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); + name = getTypeDeclaration(name); + } + p.dataType = name; + + } } p.paramName = toParamName(bp.getName()); } @@ -512,11 +558,7 @@ public class DefaultCodegen { } for(String i: imports) { if(!defaultIncludes.contains(i) && !languageSpecificPrimitives.contains(i)){ - if(typeMapping.keySet().contains(i)) { - op.imports.add(typeMapping.get(i)); - } - else - op.imports.add(i); + op.imports.add(i); } } op.httpMethod = httpMethod.toUpperCase(); @@ -532,13 +574,17 @@ public class DefaultCodegen { if(op.allParams.size() > 0) op.hasParams = true; + return op; } private List addHasMore(List objs) { if(objs != null) { - for(int i = 0; i < objs.size() - 1; i++) { - objs.get(i).hasMore = new Boolean(true); + 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; @@ -547,7 +593,10 @@ public class DefaultCodegen { private Map addHasMore(Map objs) { if(objs != null) { for(int i = 0; i < objs.size() - 1; i++) { - objs.put("hasMore", true); + if(i > 0) + objs.put("secondaryParam", new Boolean(true)); + if(i < objs.size() - 1) + objs.put("hasMore", true); } } return objs; diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index d5e4177cb36b..945e042621c4 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -89,6 +89,7 @@ public class DefaultGenerator implements Generator { else { String template = readTemplate(config.templateDir() + File.separator + support.templateFile); FileUtils.writeStringToFile(new File(outputFilename), template); + System.out.println("copying file to " + outputFilename); } } } @@ -186,7 +187,6 @@ public class DefaultGenerator implements Generator { String m = config.importMapping().get(i); if(m == null) m = config.toModelImport(i); - if(m != null) { im.put("import", m); imports.add(im); diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index 007abe9b7a3a..d2bb06b0686b 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -9,6 +9,7 @@ import java.io.File; public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { protected Set foundationClasses = new HashSet(); + protected String sourceFolder = "client"; public ObjcClientCodegen() { super(); @@ -46,8 +47,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping = new HashMap(); typeMapping.put("enum", "NSString"); - typeMapping.put("date", "SWGDate"); - typeMapping.put("dateTime", "SWGDate"); + typeMapping.put("Date", "SWGDate"); + typeMapping.put("DateTime", "SWGDate"); // typeMapping.put("Date", "SWGDate"); typeMapping.put("boolean", "NSNumber"); typeMapping.put("string", "NSString"); @@ -56,7 +57,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("float", "NSNumber"); typeMapping.put("long", "NSNumber"); typeMapping.put("double", "NSNumber"); - typeMapping.put("Array", "NSArray"); + typeMapping.put("array", "NSArray"); // typeMapping.put("array", "NSArray"); typeMapping.put("List", "NSArray"); typeMapping.put("object", "NSObject"); @@ -70,6 +71,24 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { "NSObject", "NSString") ); + + 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 getTypeDeclaration(String name) { + if(languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) + return name; + else + return name + "*"; } @Override @@ -120,12 +139,12 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + File.separator + "client"; + return outputFolder + File.separator + sourceFolder; } @Override public String modelFileFolder() { - return outputFolder + File.separator + "client"; + return outputFolder + File.separator + sourceFolder; } @Override @@ -133,8 +152,13 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return "SWG" + initialCaps(name); } + @Override + public String toApiName(String name) { + return "SWG" + initialCaps(name) + "Api"; + } + public String toApiFilename(String name) { - return "SWG" + initialCaps(name); + return "SWG" + initialCaps(name) + "Api"; } @Override diff --git a/src/main/resources/objc/api-body.mustache b/src/main/resources/objc/api-body.mustache index 02e25263d8eb..c4ffa9b8e768 100644 --- a/src/main/resources/objc/api-body.mustache +++ b/src/main/resources/objc/api-body.mustache @@ -2,7 +2,7 @@ #import "{{classname}}.h" #import "SWGFile.h" #import "SWGApiClient.h" -{{#imports}}#import "{{import}}.h" +{{#imports}}#import "{{import}}" {{/imports}} {{newline}} @@ -53,7 +53,8 @@ static NSString * basePath = @"{{basePath}}"; {{#operation}} --(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}}{{newline}} {{/allParams}} +-(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}} { diff --git a/src/main/resources/objc/api-header.mustache b/src/main/resources/objc/api-header.mustache index a66461d8ec2e..92d74fbbfbb8 100644 --- a/src/main/resources/objc/api-header.mustache +++ b/src/main/resources/objc/api-header.mustache @@ -1,5 +1,5 @@ #import -{{#imports}}#import "{{import}}.h" +{{#imports}}#import "{{import}}" {{/imports}} {{newline}} @@ -20,7 +20,8 @@ {{#allParams}}@param {{paramName}} {{description}} {{/allParams}} */ --(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} +-(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}} {{/operation}} diff --git a/src/main/resources/objc/model-header.mustache b/src/main/resources/objc/model-header.mustache index 9dc5f15f4e84..581978bec197 100644 --- a/src/main/resources/objc/model-header.mustache +++ b/src/main/resources/objc/model-header.mustache @@ -1,6 +1,6 @@ #import #import "SWGObject.h" -{{#imports}}#import "{{import}}.h" +{{#imports}}#import "{{import}}" {{/imports}} {{newline}} {{#models}} From 370c22cddb8c07e3b8d3d1bb2675001d1cdd4869 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 3 Sep 2014 22:17:26 -0700 Subject: [PATCH 011/325] made templates same as 2.0 --- src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java | 2 +- .../wordnik/swagger/codegen/languages/ObjcClientCodegen.java | 2 +- src/main/resources/objc/api-body.mustache | 2 +- src/main/resources/objc/api-header.mustache | 2 +- src/main/resources/objc/model-header.mustache | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 945e042621c4..c5f5d37db21b 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -23,6 +23,7 @@ public class DefaultGenerator implements Generator { try { Map models = null; Map operations = null; + // models Map definitions = swagger.getDefinitions(); for(String name: definitions.keySet()) { @@ -112,7 +113,6 @@ public class DefaultGenerator implements Generator { processOperation(resourcePath, "patch", path.getPatch(), ops); processOperation(resourcePath, "options", path.getOptions(), ops); } - // Json.prettyPrint(ops); return ops; } diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index d2bb06b0686b..860698ada8c7 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -130,7 +130,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toModelImport(String name) { - name = name + ".h"; + // name = name + ".h"; if("".equals(modelPackage())) return name; else diff --git a/src/main/resources/objc/api-body.mustache b/src/main/resources/objc/api-body.mustache index c4ffa9b8e768..a147c5eaab5c 100644 --- a/src/main/resources/objc/api-body.mustache +++ b/src/main/resources/objc/api-body.mustache @@ -2,7 +2,7 @@ #import "{{classname}}.h" #import "SWGFile.h" #import "SWGApiClient.h" -{{#imports}}#import "{{import}}" +{{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} diff --git a/src/main/resources/objc/api-header.mustache b/src/main/resources/objc/api-header.mustache index 92d74fbbfbb8..7bc55a0fade7 100644 --- a/src/main/resources/objc/api-header.mustache +++ b/src/main/resources/objc/api-header.mustache @@ -1,5 +1,5 @@ #import -{{#imports}}#import "{{import}}" +{{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} diff --git a/src/main/resources/objc/model-header.mustache b/src/main/resources/objc/model-header.mustache index 581978bec197..9dc5f15f4e84 100644 --- a/src/main/resources/objc/model-header.mustache +++ b/src/main/resources/objc/model-header.mustache @@ -1,6 +1,6 @@ #import #import "SWGObject.h" -{{#imports}}#import "{{import}}" +{{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} {{#models}} From d5e62086c8da658fb9ec2e667dfbee556040e924 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 4 Sep 2014 12:42:35 -0700 Subject: [PATCH 012/325] added cli parser, input opts --- pom.xml | 8 ++- .../swagger/codegen/ClientOptInput.java | 59 ++++++++++++++++++ .../wordnik/swagger/codegen/ClientOpts.java | 52 ++++++++++++++++ .../com/wordnik/swagger/codegen/Codegen.java | 61 +++++++++++++------ .../swagger/codegen/CodegenConfig.java | 4 +- .../swagger/codegen/DefaultCodegen.java | 7 +++ .../swagger/codegen/DefaultGenerator.java | 17 +++++- .../wordnik/swagger/codegen/Generator.java | 4 +- 8 files changed, 185 insertions(+), 27 deletions(-) create mode 100644 src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/ClientOpts.java diff --git a/pom.xml b/pom.xml index d4d026e9d181..94e6ed427004 100644 --- a/pom.xml +++ b/pom.xml @@ -382,7 +382,12 @@ commons-lang ${commons-lang-version} compile - + + + commons-cli + commons-cli + ${commons-cli-version} + org.scalatest scalatest_2.11 @@ -402,6 +407,7 @@ 1.5.0-SNAPSHOT 2.1.4 2.3 + 1.2 4.8.1 1.0.0 diff --git a/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java b/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java new file mode 100644 index 000000000000..a48a92f3faa5 --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java @@ -0,0 +1,59 @@ +/** + * Copyright 2014 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.models.Swagger; + +public class ClientOptInput { + private ClientOpts opts; + private Swagger model; + protected CodegenConfig config; + + public ClientOptInput model(Swagger model) { + this.setModel(model); + return this; + } + public ClientOptInput opts(ClientOpts opts) { + this.setOpts(opts); + return this; + } + + 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 setModel(Swagger model) { + this.model = model; + } + + public Swagger getModel() { + return model; + } +} \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/ClientOpts.java b/src/main/java/com/wordnik/swagger/codegen/ClientOpts.java new file mode 100644 index 000000000000..b8d681cc3078 --- /dev/null +++ b/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/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index 19f31b80d3e0..5d2cfb4818b9 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -1,38 +1,59 @@ package com.wordnik.swagger.codegen; -import com.wordnik.swagger.codegen.languages.*; +import com.wordnik.swagger.codegen.languages.*; import com.wordnik.swagger.models.Swagger; -import com.wordnik.swagger.util.Json; +import com.wordnik.swagger.util.*; + +import org.apache.commons.cli.*; import java.io.File; public class Codegen extends DefaultGenerator { public static void main(String[] args) { - CodegenConfig config = null; - if(args != null && args.length > 0) { - String lang = args[0]; - if("java".equals(lang)) { - JavaClientCodegen javaConfig = new JavaClientCodegen(); - javaConfig.setTemplateDir("src/main/resources/Java"); - config = javaConfig; - } - else if ("objc".equals(lang)) { - ObjcClientCodegen objcConfig = new ObjcClientCodegen(); - objcConfig.setTemplateDir("src/main/resources/objc"); - config = objcConfig; - } + Options options = new Options(); + options.addOption("l", "lang", true, "client language to generate"); + 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"); + + ClientOptInput codegenInput = new ClientOptInput(); + ClientOpts clientArgs = new ClientOpts(); + Swagger swagger = null; + + CommandLine cmd = null; + try { + CommandLineParser parser = new BasicParser(); + cmd = parser.parse(options, args); + if (cmd.hasOption("l")) + codegenInput.setConfig(getConfig(cmd.getOptionValue("l"))); + if (cmd.hasOption("o")) + codegenInput.getConfig().setOutputDir(cmd.getOptionValue("o")); + if (cmd.hasOption("i")) + swagger = new SwaggerLoader().read(cmd.getOptionValue("i")); + + } + catch (Exception e) { + e.printStackTrace(); + return; } try{ - Swagger swagger = (Swagger) Json.mapper() - .readValue(new File("swagger.json"), Swagger.class); + codegenInput + .opts(clientArgs) + .model(swagger); - new Codegen() - .config(config) - .generate(swagger); + new Codegen().opts(codegenInput).generate(); } catch (Exception e) { e.printStackTrace(); } } + + static CodegenConfig getConfig(String name) { + if("objc".equals(name)) + return new ObjcClientCodegen(); + else if("java".equals(name)) + return new JavaClientCodegen(); + else + throw new RuntimeException("unsupported client type"); + } } diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java index 78604490ba16..43a5f2902abb 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -18,7 +18,6 @@ public interface CodegenConfig { String toModelName(String name); String toParamName(String name); String escapeReservedWord(String name); - String getTypeDeclaration(Property p); String getTypeDeclaration(String name); @@ -26,6 +25,9 @@ public interface CodegenConfig { List supportingFiles(); + void setOutputDir(String dir); + String getOutputDir(); + CodegenModel fromModel(String name, Model model); CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation); Set defaultIncludes(); diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 04bc9f55bcb1..877d8ffe0f84 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -71,6 +71,13 @@ public class DefaultCodegen { return outputFolder; } + public void setOutputDir(String dir) { + this.outputFolder = dir; + } + public String getOutputDir() { + return outputFolder(); + } + public void setTemplateDir(String templateDir) { this.templateDir = templateDir; } diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index c5f5d37db21b..0cfe4c8b7cdc 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -4,6 +4,7 @@ import com.wordnik.swagger.models.*; import com.wordnik.swagger.models.properties.*; import com.wordnik.swagger.util.*; +import com.wordnik.swagger.codegen.languages.*; import com.samskivert.mustache.*; import org.apache.commons.io.FileUtils; @@ -13,13 +14,23 @@ import java.io.*; public class DefaultGenerator implements Generator { private CodegenConfig config; + private ClientOptInput opts = null; + private Swagger swagger = null; + + public Generator opts(ClientOptInput opts) { + this.opts = opts; + + this.swagger = opts.getModel(); + ClientOpts clientOpts = opts.getOpts(); + this.config = opts.getConfig(); - public Generator config(CodegenConfig config) { - this.config = config; return this; } - public void generate(Swagger swagger) { + public void generate() { + if(swagger == null || config == null) { + throw new RuntimeException("missing swagger input or config!"); + } try { Map models = null; Map operations = null; diff --git a/src/main/java/com/wordnik/swagger/codegen/Generator.java b/src/main/java/com/wordnik/swagger/codegen/Generator.java index be5b7ff9db02..929ae580991f 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Generator.java +++ b/src/main/java/com/wordnik/swagger/codegen/Generator.java @@ -3,6 +3,6 @@ package com.wordnik.swagger.codegen; import com.wordnik.swagger.models.Swagger; public interface Generator { - Generator config(CodegenConfig config); - void generate(Swagger swagger); + Generator opts(ClientOptInput opts); + void generate(); } \ No newline at end of file From cab4ffa2862b33c8c245ba119afb463aae7e8294 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 10 Sep 2014 06:13:49 -0700 Subject: [PATCH 013/325] property renames --- .../wordnik/swagger/codegen/ClientOptInput.java | 14 +++++++------- .../java/com/wordnik/swagger/codegen/Codegen.java | 2 +- .../wordnik/swagger/codegen/DefaultCodegen.java | 2 ++ .../wordnik/swagger/codegen/DefaultGenerator.java | 2 +- 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java b/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java index a48a92f3faa5..cdfb1191b2f7 100644 --- a/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java +++ b/src/main/java/com/wordnik/swagger/codegen/ClientOptInput.java @@ -22,11 +22,11 @@ import com.wordnik.swagger.models.Swagger; public class ClientOptInput { private ClientOpts opts; - private Swagger model; + private Swagger swagger; protected CodegenConfig config; - public ClientOptInput model(Swagger model) { - this.setModel(model); + public ClientOptInput swagger(Swagger swagger) { + this.setSwagger(swagger); return this; } public ClientOptInput opts(ClientOpts opts) { @@ -49,11 +49,11 @@ public class ClientOptInput { return opts; } - public void setModel(Swagger model) { - this.model = model; + public void setSwagger(Swagger swagger) { + this.swagger = swagger; } - public Swagger getModel() { - return model; + public Swagger getSwagger() { + return swagger; } } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index 5d2cfb4818b9..fbbf55f80dd9 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -39,7 +39,7 @@ public class Codegen extends DefaultGenerator { try{ codegenInput .opts(clientArgs) - .model(swagger); + .swagger(swagger); new Codegen().opts(codegenInput).generate(); } diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 877d8ffe0f84..278e91fd86f7 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -381,6 +381,8 @@ public class DefaultCodegen { if(languageSpecificPrimitives().contains(type)) property.isPrimitiveType = true; } + if("id".equals(property.name)) + Json.prettyPrint(property); return property; } diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 0cfe4c8b7cdc..28fab4d90a8f 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -20,7 +20,7 @@ public class DefaultGenerator implements Generator { public Generator opts(ClientOptInput opts) { this.opts = opts; - this.swagger = opts.getModel(); + this.swagger = opts.getSwagger(); ClientOpts clientOpts = opts.getOpts(); this.config = opts.getConfig(); From d4122d197f41e5c9774da49963afcd09e93b82b3 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sun, 14 Sep 2014 17:47:36 -0700 Subject: [PATCH 014/325] updated to support jaxrs --- .../com/wordnik/swagger/codegen/Codegen.java | 2 + .../swagger/codegen/CodegenConfig.java | 3 + .../swagger/codegen/CodegenOperation.java | 4 +- .../swagger/codegen/CodegenParameter.java | 2 +- .../swagger/codegen/DefaultCodegen.java | 42 +++++- .../swagger/codegen/DefaultGenerator.java | 65 ++++++--- .../codegen/languages/JaxRSServerCodegen.java | 123 +++++++++++++++++ .../resources/JavaJaxRS/ApiException.mustache | 9 ++ .../JavaJaxRS/ApiOriginFilter.mustache | 26 ++++ .../JavaJaxRS/ApiResponseMessage.mustache | 68 ++++++++++ .../JavaJaxRS/NotFoundException.mustache | 9 ++ src/main/resources/JavaJaxRS/README.mustache | 10 ++ src/main/resources/JavaJaxRS/api.mustache | 36 +++++ .../resources/JavaJaxRS/bodyParams.mustache | 1 + .../resources/JavaJaxRS/headerParams.mustache | 1 + src/main/resources/JavaJaxRS/model.mustache | 42 ++++++ .../resources/JavaJaxRS/pathParams.mustache | 1 + src/main/resources/JavaJaxRS/pom.mustache | 126 ++++++++++++++++++ .../JavaJaxRS/project/build.properties | 1 + .../resources/JavaJaxRS/project/plugins.sbt | 9 ++ .../resources/JavaJaxRS/queryParams.mustache | 1 + src/main/resources/JavaJaxRS/web.mustache | 54 ++++++++ 22 files changed, 614 insertions(+), 21 deletions(-) create mode 100644 src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java create mode 100644 src/main/resources/JavaJaxRS/ApiException.mustache create mode 100644 src/main/resources/JavaJaxRS/ApiOriginFilter.mustache create mode 100644 src/main/resources/JavaJaxRS/ApiResponseMessage.mustache create mode 100644 src/main/resources/JavaJaxRS/NotFoundException.mustache create mode 100644 src/main/resources/JavaJaxRS/README.mustache create mode 100644 src/main/resources/JavaJaxRS/api.mustache create mode 100644 src/main/resources/JavaJaxRS/bodyParams.mustache create mode 100644 src/main/resources/JavaJaxRS/headerParams.mustache create mode 100644 src/main/resources/JavaJaxRS/model.mustache create mode 100644 src/main/resources/JavaJaxRS/pathParams.mustache create mode 100644 src/main/resources/JavaJaxRS/pom.mustache create mode 100644 src/main/resources/JavaJaxRS/project/build.properties create mode 100644 src/main/resources/JavaJaxRS/project/plugins.sbt create mode 100644 src/main/resources/JavaJaxRS/queryParams.mustache create mode 100644 src/main/resources/JavaJaxRS/web.mustache diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index fbbf55f80dd9..17ab91180620 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -53,6 +53,8 @@ public class Codegen extends DefaultGenerator { return new ObjcClientCodegen(); else if("java".equals(name)) return new JavaClientCodegen(); + else if("jaxrs".equals(name)) + return new JaxRSServerCodegen(); else throw new RuntimeException("unsupported client type"); } diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java index 43a5f2902abb..808b893913a6 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -40,4 +40,7 @@ public interface CodegenConfig { 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); } diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java b/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java index 51dc2e19ad5d..01e3898c5c16 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenOperation.java @@ -9,7 +9,7 @@ import java.util.*; public class CodegenOperation { public Boolean hasParams, returnTypeIsPrimitive, returnSimpleType; public String path, operationId, returnType, httpMethod, returnBaseType, - returnContainer, summary, notes; + returnContainer, summary, notes, baseName; public List> consumes, produces; public List allParams = new ArrayList(); @@ -18,6 +18,8 @@ public class CodegenOperation { public List queryParams = new ArrayList(); public List headerParams = new ArrayList(); public List formParams = new ArrayList(); + public List tags; + public List responses = new ArrayList(); public Set imports = new HashSet(); diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java index 70e0f59f7d55..1b502442530f 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java @@ -2,5 +2,5 @@ package com.wordnik.swagger.codegen; public class CodegenParameter { public Boolean hasMore = null, isContainer = null, secondaryParam = null; - public String baseName, paramName, dataType, collectionFormat; + public String baseName, paramName, dataType, collectionFormat, description; } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 278e91fd86f7..91baf03a2572 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -22,6 +22,16 @@ public class DefaultCodegen { protected Map additionalProperties = new HashMap(); protected List supportingFiles = new ArrayList(); + // 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; + } + public Set defaultIncludes() { return defaultIncludes; } @@ -381,8 +391,6 @@ public class DefaultCodegen { if(languageSpecificPrimitives().contains(type)) property.isPrimitiveType = true; } - if("id".equals(property.name)) - Json.prettyPrint(property); return property; } @@ -397,6 +405,7 @@ public class DefaultCodegen { op.operationId = operationId; op.summary = operation.getSummary(); op.notes = operation.getDescription(); + op.tags = operation.getTags(); Response methodResponse = null; @@ -438,6 +447,23 @@ public class DefaultCodegen { 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 = new CodegenResponse(); + if("default".equals(responseCode)) + r.code = "0"; + else + r.code = responseCode; + r.message = response.getDescription(); + r.schema = response.getSchema(); + 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 && methodResponse.getSchema() != null) { @@ -490,6 +516,7 @@ public class DefaultCodegen { for(Parameter param : parameters) { CodegenParameter p = new CodegenParameter(); p.baseName = param.getName(); + p.description = param.getDescription(); if(param instanceof SerializableParameter) { SerializableParameter qp = (SerializableParameter) param; @@ -610,4 +637,15 @@ public class DefaultCodegen { } 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/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 28fab4d90a8f..1e6c9c75200f 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -43,12 +43,17 @@ public class DefaultGenerator implements Generator { modelMap.put(name, model); models = processModels(config, modelMap); models.putAll(config.additionalProperties()); - for(String templateName: config.modelTemplateFiles().keySet()) { + 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); @@ -56,13 +61,14 @@ public class DefaultGenerator implements Generator { } } // apis - Map> paths = groupPaths(swagger.getPaths()); - for(String tag: paths.keySet()) { + Map> paths = processPaths(swagger.getPaths()); + for(String tag : paths.keySet()) { List ops = paths.get(tag); operations = processOperations(config, tag, ops); operations.putAll(config.additionalProperties()); - for(String templateName: config.apiTemplateFiles().keySet()) { + operations.put("baseName", tag); + for(String templateName : config.apiTemplateFiles().keySet()) { String suffix = config.apiTemplateFiles().get(templateName); String filename = config.apiFileFolder() + File.separator + @@ -71,6 +77,12 @@ public class DefaultGenerator implements Generator { String template = readTemplate(config.templateDir() + File.separator + templateName); Template tmpl = Mustache.compiler() + .withLoader(new Mustache.TemplateLoader() { + public Reader getTemplate (String name) { + System.out.println("loading template " + name); + return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + }; + }) .defaultValue("") .compile(template); @@ -81,7 +93,8 @@ public class DefaultGenerator implements Generator { // supporting files Map bundle = new HashMap(); bundle.putAll(config.additionalProperties()); - for(SupportingFile support: config.supportingFiles()) { + bundle.put("apiPackage", config.apiPackage()); + for(SupportingFile support : config.supportingFiles()) { String outputFolder = config.outputFolder(); if(support.folder != null && !"".equals(support.folder)) outputFolder += File.separator + support.folder; @@ -93,6 +106,11 @@ public class DefaultGenerator implements Generator { 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); @@ -110,12 +128,12 @@ public class DefaultGenerator implements Generator { } } - public Map> groupPaths(Map paths) { + public Map> processPaths(Map paths) { // group by tag, create a Default grouping if none Map> ops = new HashMap>(); List tags = null; - for(String resourcePath: paths.keySet()) { + for(String resourcePath : paths.keySet()) { Path path = paths.get(resourcePath); processOperation(resourcePath, "get", path.getGet(), ops); processOperation(resourcePath, "put", path.getPut(), ops); @@ -135,14 +153,12 @@ public class DefaultGenerator implements Generator { tags.add("default"); } - for(String tag: tags) { - List opList = operations.get(tag); - if(opList == null) { - opList = new ArrayList(); - operations.put(tag, opList); - } + for(String tag : tags) { CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation); - opList.add(co); + co.tags = new ArrayList(); + co.tags.add(tag); + + config.addOperationToGroup(tag, resourcePath, operation, co, operations); } } } @@ -164,14 +180,27 @@ public class DefaultGenerator implements Generator { } 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(name); if(is == null) is = new FileInputStream(new File(name)); if(is == null) throw new RuntimeException("no file found"); - java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); - return s.hasNext() ? s.next() : ""; + return new InputStreamReader(is); } catch(Exception e) { e.printStackTrace(); @@ -205,7 +234,7 @@ public class DefaultGenerator implements Generator { } operations.put("imports", imports); - + config.postProcessOperations(operations); return operations; } @@ -240,6 +269,8 @@ public class DefaultGenerator implements Generator { } objs.put("imports", imports); + config.postProcessModels(objs); + return objs; } } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java new file mode 100644 index 000000000000..4bde8918afb3 --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java @@ -0,0 +1,123 @@ +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 = "com.wordnik.api"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-server"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/java"; + protected String title = "Swagger Server"; + + public JaxRSServerCodegen() { + super(); + outputFolder = "generated-code/javaJaxRS"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "src/main/resources/JavaJaxRS"; + apiPackage = "com.wordnik.api"; + modelPackage = "com.wordnik.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 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()); + } + 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"; + } + } + // Json.prettyPrint(operation); + // if(return) + } + } + // Json.prettyPrint(objs); + return objs; + } +} \ No newline at end of file diff --git a/src/main/resources/JavaJaxRS/ApiException.mustache b/src/main/resources/JavaJaxRS/ApiException.mustache new file mode 100644 index 000000000000..ffab3b1088e7 --- /dev/null +++ b/src/main/resources/JavaJaxRS/ApiException.mustache @@ -0,0 +1,9 @@ +package {{apiPackage}}; + +public class ApiException extends Exception{ + private int code; + public ApiException (int code, String msg) { + super(msg); + this.code = code; + } +} diff --git a/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache b/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache new file mode 100644 index 000000000000..68675432c648 --- /dev/null +++ b/src/main/resources/JavaJaxRS/ApiOriginFilter.mustache @@ -0,0 +1,26 @@ +package {{apiPackage}}; + +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/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache b/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache new file mode 100644 index 000000000000..94711b26efb2 --- /dev/null +++ b/src/main/resources/JavaJaxRS/ApiResponseMessage.mustache @@ -0,0 +1,68 @@ +package {{apiPackage}}; + +import javax.xml.bind.annotation.XmlTransient; + +@javax.xml.bind.annotation.XmlRootElement +public class ApiResponseMessage { + public static final int ERROR = 1; + public static final int WARNING = 2; + public static final int INFO = 3; + public static final int OK = 4; + public static final int TOO_BUSY = 5; + + int code; + String type; + String message; + + public ApiResponseMessage(){} + + public ApiResponseMessage(int code, String message){ + this.code = code; + switch(code){ + case ERROR: + setType("error"); + break; + case WARNING: + setType("warning"); + break; + case INFO: + setType("info"); + break; + case OK: + setType("ok"); + break; + case TOO_BUSY: + setType("too busy"); + break; + default: + setType("unknown"); + break; + } + this.message = message; + } + + @XmlTransient + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/src/main/resources/JavaJaxRS/NotFoundException.mustache b/src/main/resources/JavaJaxRS/NotFoundException.mustache new file mode 100644 index 000000000000..8ab2c99e4f84 --- /dev/null +++ b/src/main/resources/JavaJaxRS/NotFoundException.mustache @@ -0,0 +1,9 @@ +package {{apiPackage}}; + +public class NotFoundException extends ApiException { + private int code; + public NotFoundException (int code, String msg) { + super(code, msg); + this.code = code; + } +} diff --git a/src/main/resources/JavaJaxRS/README.mustache b/src/main/resources/JavaJaxRS/README.mustache new file mode 100644 index 000000000000..f8a560b776f5 --- /dev/null +++ b/src/main/resources/JavaJaxRS/README.mustache @@ -0,0 +1,10 @@ +# 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 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) \ No newline at end of file diff --git a/src/main/resources/JavaJaxRS/api.mustache b/src/main/resources/JavaJaxRS/api.mustache new file mode 100644 index 000000000000..766af3a8a4f9 --- /dev/null +++ b/src/main/resources/JavaJaxRS/api.mustache @@ -0,0 +1,36 @@ +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}}") +@Api(value = "/{{baseName}}", description = "the {{baseName}} API") +@Produces({"application/json"}) +{{#operations}} +public class {{classname}} { + {{#operation}} + @{{httpMethod}} + @Path("{{path}}") + @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}} {{#hasMore}},{{/hasMore}}{{/allParams}}) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + + {{/operation}} +} +{{/operations}} diff --git a/src/main/resources/JavaJaxRS/bodyParams.mustache b/src/main/resources/JavaJaxRS/bodyParams.mustache new file mode 100644 index 000000000000..109e3bf26fc5 --- /dev/null +++ b/src/main/resources/JavaJaxRS/bodyParams.mustache @@ -0,0 +1 @@ +{{#bodyParams}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{newline}}{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/bodyParams}} \ No newline at end of file diff --git a/src/main/resources/JavaJaxRS/headerParams.mustache b/src/main/resources/JavaJaxRS/headerParams.mustache new file mode 100644 index 000000000000..0054c4c6dee7 --- /dev/null +++ b/src/main/resources/JavaJaxRS/headerParams.mustache @@ -0,0 +1 @@ +{{#headerParams}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{newline}}{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}})@HeaderParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}}{{/headerParams}} \ No newline at end of file diff --git a/src/main/resources/JavaJaxRS/model.mustache b/src/main/resources/JavaJaxRS/model.mustache new file mode 100644 index 000000000000..938daf4d5f67 --- /dev/null +++ b/src/main/resources/JavaJaxRS/model.mustache @@ -0,0 +1,42 @@ +package {{package}}; + +{{#imports}}import {{import}}; +{{/imports}} +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +public class {{classname}} { {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}} + * required: {{required}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{#allowableValues}} + + //{{^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/JavaJaxRS/pathParams.mustache b/src/main/resources/JavaJaxRS/pathParams.mustache new file mode 100644 index 000000000000..7d3fcce56adf --- /dev/null +++ b/src/main/resources/JavaJaxRS/pathParams.mustache @@ -0,0 +1 @@ +{{#pathParams}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{newline}}{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}})@PathParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}}{{/pathParams}} \ No newline at end of file diff --git a/src/main/resources/JavaJaxRS/pom.mustache b/src/main/resources/JavaJaxRS/pom.mustache new file mode 100644 index 000000000000..55f69368ac94 --- /dev/null +++ b/src/main/resources/JavaJaxRS/pom.mustache @@ -0,0 +1,126 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + src/main/java + + + org.apache.maven.plugins + maven-war-plugin + 2.1.1 + + + maven-failsafe-plugin + 2.6 + + + + integration-test + verify + + + + + + org.mortbay.jetty + jetty-maven-plugin + ${jetty-version} + + + / + + target/${project.artifactId}-${project.version} + ${project.basedir}/conf/jetty/webdefault.xml + 8079 + stopit + + + 8002 + 60000 + 8443 + + + + + + start-jetty + pre-integration-test + + run + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + + + + com.wordnik + swagger-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} + + + + org.scalatest + scalatest_2.9.1 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + javax.servlet + servlet-api + ${servlet-api-version} + + + + 1.5.0-SNAPSHOT + 8.1.11.v20130520 + 1.13 + 1.6.3 + 1.6.1 + 4.8.1 + 2.5 + + \ No newline at end of file diff --git a/src/main/resources/JavaJaxRS/project/build.properties b/src/main/resources/JavaJaxRS/project/build.properties new file mode 100644 index 000000000000..a8c2f849be3c --- /dev/null +++ b/src/main/resources/JavaJaxRS/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.12.0 diff --git a/src/main/resources/JavaJaxRS/project/plugins.sbt b/src/main/resources/JavaJaxRS/project/plugins.sbt new file mode 100644 index 000000000000..713b7f3e9935 --- /dev/null +++ b/src/main/resources/JavaJaxRS/project/plugins.sbt @@ -0,0 +1,9 @@ +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.8.4") + +libraryDependencies <+= sbtVersion(v => v match { + case "0.11.0" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.0-0.2.8" + case "0.11.1" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.1-0.2.10" + case "0.11.2" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.2-0.2.11" + case "0.11.3" => "com.github.siasia" %% "xsbt-web-plugin" % "0.11.3-0.2.11.1" + case x if (x.startsWith("0.12")) => "com.github.siasia" %% "xsbt-web-plugin" % "0.12.0-0.2.11.1" +}) \ No newline at end of file diff --git a/src/main/resources/JavaJaxRS/queryParams.mustache b/src/main/resources/JavaJaxRS/queryParams.mustache new file mode 100644 index 000000000000..7724ba420a8c --- /dev/null +++ b/src/main/resources/JavaJaxRS/queryParams.mustache @@ -0,0 +1 @@ +{{#queryParams}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{newline}}{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}})@QueryParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}}{{/queryParams}} \ No newline at end of file diff --git a/src/main/resources/JavaJaxRS/web.mustache b/src/main/resources/JavaJaxRS/web.mustache new file mode 100644 index 000000000000..b9cd00b71ce1 --- /dev/null +++ b/src/main/resources/JavaJaxRS/web.mustache @@ -0,0 +1,54 @@ + + + + + jersey + com.sun.jersey.spi.container.servlet.ServletContainer + + com.sun.jersey.config.property.packages + com.wordnik.swagger.jaxrs.json;com.wordnik.swagger.jaxrs.listing;{{apiPackage}} + + + com.sun.jersey.spi.container.ContainerRequestFilters + com.sun.jersey.api.container.filter.PostReplaceFilter + + + com.sun.jersey.api.json.POJOMappingFeature + true + + 1 + + + + DefaultJaxrsConfig + com.wordnik.swagger.jaxrs.config.DefaultJaxrsConfig + + api.version + 1.0.0 + + + swagger.api.title + {{{title}}} + + + swagger.api.basepath + http://localhost:8002 + + 2 + + + + jersey + /* + + + ApiOriginFilter + com.wordnik.api.ApiOriginFilter + + + ApiOriginFilter + /* + + From 5112b655bdd6b8b5272b93e17f31c6b48e9c133a Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sun, 14 Sep 2014 17:47:59 -0700 Subject: [PATCH 015/325] added auth and response models --- .../java/com/wordnik/swagger/codegen/CodegenResponse.java | 8 ++++++++ .../java/com/wordnik/swagger/codegen/auth/AuthMethod.java | 6 ++++++ 2 files changed, 14 insertions(+) create mode 100644 src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java create mode 100644 src/main/java/com/wordnik/swagger/codegen/auth/AuthMethod.java diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java b/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java new file mode 100644 index 000000000000..7151764bec22 --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java @@ -0,0 +1,8 @@ +package com.wordnik.swagger.codegen; + + +public class CodegenResponse { + public String code, message; + public Boolean hasMore; + Object schema; +} \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/auth/AuthMethod.java b/src/main/java/com/wordnik/swagger/codegen/auth/AuthMethod.java new file mode 100644 index 000000000000..7de102ec3501 --- /dev/null +++ b/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 From c123bb91301aa0f82ccb4781e0df35d291dcd7eb Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sun, 14 Sep 2014 17:52:25 -0700 Subject: [PATCH 016/325] template cleanup --- src/main/resources/JavaJaxRS/api.mustache | 5 ++--- src/main/resources/JavaJaxRS/bodyParams.mustache | 2 +- src/main/resources/JavaJaxRS/headerParams.mustache | 2 +- src/main/resources/JavaJaxRS/pathParams.mustache | 2 +- src/main/resources/JavaJaxRS/queryParams.mustache | 2 +- 5 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/main/resources/JavaJaxRS/api.mustache b/src/main/resources/JavaJaxRS/api.mustache index 766af3a8a4f9..c5186394c40e 100644 --- a/src/main/resources/JavaJaxRS/api.mustache +++ b/src/main/resources/JavaJaxRS/api.mustache @@ -19,13 +19,12 @@ public class {{classname}} { {{#operation}} @{{httpMethod}} @Path("{{path}}") - @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class {{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) + @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}} {{#hasMore}},{{/hasMore}}{{/allParams}}) + public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/src/main/resources/JavaJaxRS/bodyParams.mustache b/src/main/resources/JavaJaxRS/bodyParams.mustache index 109e3bf26fc5..a959ec2c8d5b 100644 --- a/src/main/resources/JavaJaxRS/bodyParams.mustache +++ b/src/main/resources/JavaJaxRS/bodyParams.mustache @@ -1 +1 @@ -{{#bodyParams}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{newline}}{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/bodyParams}} \ No newline at end of file +{{#bodyParams}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/bodyParams}} \ No newline at end of file diff --git a/src/main/resources/JavaJaxRS/headerParams.mustache b/src/main/resources/JavaJaxRS/headerParams.mustache index 0054c4c6dee7..f9f5e1326fce 100644 --- a/src/main/resources/JavaJaxRS/headerParams.mustache +++ b/src/main/resources/JavaJaxRS/headerParams.mustache @@ -1 +1 @@ -{{#headerParams}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{newline}}{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}})@HeaderParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}}{{/headerParams}} \ No newline at end of file +{{#headerParams}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/headerParams}} \ No newline at end of file diff --git a/src/main/resources/JavaJaxRS/pathParams.mustache b/src/main/resources/JavaJaxRS/pathParams.mustache index 7d3fcce56adf..05923c124353 100644 --- a/src/main/resources/JavaJaxRS/pathParams.mustache +++ b/src/main/resources/JavaJaxRS/pathParams.mustache @@ -1 +1 @@ -{{#pathParams}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{newline}}{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}})@PathParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}}{{/pathParams}} \ No newline at end of file +{{#pathParams}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/pathParams}} \ No newline at end of file diff --git a/src/main/resources/JavaJaxRS/queryParams.mustache b/src/main/resources/JavaJaxRS/queryParams.mustache index 7724ba420a8c..dbe3ed1c3776 100644 --- a/src/main/resources/JavaJaxRS/queryParams.mustache +++ b/src/main/resources/JavaJaxRS/queryParams.mustache @@ -1 +1 @@ -{{#queryParams}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{newline}}{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}})@QueryParam("{{paramName}}"){{newline}} {{{dataType}}} {{paramName}}{{/queryParams}} \ No newline at end of file +{{#queryParams}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{newline}}{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}}) @QueryParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/queryParams}} \ No newline at end of file From fff1f30dbadea1f4e9e020bb68ff2fd2ed3a1c1a Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sun, 14 Sep 2014 21:44:07 -0700 Subject: [PATCH 017/325] updated the query params --- .../swagger/codegen/CodegenParameter.java | 1 + .../swagger/codegen/DefaultCodegen.java | 20 ++++++++++++++----- src/main/resources/JavaJaxRS/api.mustache | 5 +++-- .../resources/JavaJaxRS/bodyParams.mustache | 2 +- .../resources/JavaJaxRS/headerParams.mustache | 2 +- .../resources/JavaJaxRS/pathParams.mustache | 2 +- .../resources/JavaJaxRS/queryParams.mustache | 2 +- 7 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java index 1b502442530f..d8894fed3098 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java @@ -3,4 +3,5 @@ package com.wordnik.swagger.codegen; public class CodegenParameter { public Boolean hasMore = null, isContainer = null, secondaryParam = null; public String baseName, paramName, dataType, collectionFormat, description; + public Boolean isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam; } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 91baf03a2572..37ca600ea2da 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -578,16 +578,26 @@ public class DefaultCodegen { p.paramName = toParamName(bp.getName()); } allParams.add(p); - if(param instanceof QueryParameter) + if(param instanceof QueryParameter) { queryParams.add(p); - else if(param instanceof PathParameter) + p.isQueryParam = new Boolean(true); + } + else if(param instanceof PathParameter) { pathParams.add(p); - else if(param instanceof HeaderParameter) + p.isPathParam = new Boolean(true); + } + else if(param instanceof HeaderParameter) { headerParams.add(p); - else if(param instanceof CookieParameter) + p.isHeaderParam = new Boolean(true); + } + else if(param instanceof CookieParameter) { cookieParams.add(p); - else if(param instanceof BodyParameter) + p.isCookieParam = new Boolean(true); + } + else if(param instanceof BodyParameter) { bodyParams.add(p); + p.isBodyParam = new Boolean(true); + } // else if(param instanceof FormParameter) // formParams.add(p); } diff --git a/src/main/resources/JavaJaxRS/api.mustache b/src/main/resources/JavaJaxRS/api.mustache index c5186394c40e..68c629a6b094 100644 --- a/src/main/resources/JavaJaxRS/api.mustache +++ b/src/main/resources/JavaJaxRS/api.mustache @@ -23,8 +23,9 @@ public class {{classname}} { @ApiResponses(value = { {{#responses}} @ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}}, {{/hasMore}}{{/responses}} }) - - public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) + + public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{#hasMore}}, + {{/hasMore}}{{/allParams}}) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/src/main/resources/JavaJaxRS/bodyParams.mustache b/src/main/resources/JavaJaxRS/bodyParams.mustache index a959ec2c8d5b..86546afb9ca4 100644 --- a/src/main/resources/JavaJaxRS/bodyParams.mustache +++ b/src/main/resources/JavaJaxRS/bodyParams.mustache @@ -1 +1 @@ -{{#bodyParams}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/bodyParams}} \ No newline at end of file +{{#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/src/main/resources/JavaJaxRS/headerParams.mustache b/src/main/resources/JavaJaxRS/headerParams.mustache index f9f5e1326fce..0f88692ad1d4 100644 --- a/src/main/resources/JavaJaxRS/headerParams.mustache +++ b/src/main/resources/JavaJaxRS/headerParams.mustache @@ -1 +1 @@ -{{#headerParams}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@HeaderParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/headerParams}} \ No newline at end of file +{{#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/src/main/resources/JavaJaxRS/pathParams.mustache b/src/main/resources/JavaJaxRS/pathParams.mustache index 05923c124353..1f1b30887a40 100644 --- a/src/main/resources/JavaJaxRS/pathParams.mustache +++ b/src/main/resources/JavaJaxRS/pathParams.mustache @@ -1 +1 @@ -{{#pathParams}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}} {{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @PathParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/pathParams}} \ No newline at end of file +{{#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/src/main/resources/JavaJaxRS/queryParams.mustache b/src/main/resources/JavaJaxRS/queryParams.mustache index dbe3ed1c3776..b9e80e5a7e75 100644 --- a/src/main/resources/JavaJaxRS/queryParams.mustache +++ b/src/main/resources/JavaJaxRS/queryParams.mustache @@ -1 +1 @@ -{{#queryParams}}@ApiParam(value = "{{{description}}}"{{#required}},required=true{{newline}}{{/required}}{{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{newline}}{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{newline}}{{/defaultValue}}) @QueryParam("{{paramName}}") {{{dataType}}} {{paramName}}{{/queryParams}} \ No newline at end of file +{{#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 From 4442dcf2032b7a2a7fb5866b23ddea0bfb868487 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sun, 14 Sep 2014 22:44:05 -0700 Subject: [PATCH 018/325] added operationId generator --- .../swagger/codegen/DefaultCodegen.java | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 37ca600ea2da..0928dd364312 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -240,6 +240,8 @@ public class DefaultCodegen { 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(); @@ -399,8 +401,23 @@ public class DefaultCodegen { Set imports = new HashSet(); String operationId = operation.getOperationId(); - if(operationId == null) - operationId = "fixme"; + if(operationId == null) { + operationId = path.replaceAll("/", "") + "_" + httpMethod; + String[] parts = (path + "/" + httpMethod).split("/"); + StringBuilder builder = new StringBuilder(); + 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 = Character.toUpperCase(part.charAt(0)) + part.substring(1); + builder.append(part); + } + } + operationId = builder.toString(); + System.out.println("generated operationId " + operationId); + } op.path = path; op.operationId = operationId; op.summary = operation.getSummary(); From 21287412180f67dfce6ae1f5f15c7bdacff8bd76 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sun, 14 Sep 2014 22:44:18 -0700 Subject: [PATCH 019/325] removed println --- src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 1e6c9c75200f..63b8b8d2e423 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -79,7 +79,6 @@ public class DefaultGenerator implements Generator { Template tmpl = Mustache.compiler() .withLoader(new Mustache.TemplateLoader() { public Reader getTemplate (String name) { - System.out.println("loading template " + name); return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); }; }) From 9ab12eeda39052f2d6df505a1d920de7c7cdc497 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sun, 14 Sep 2014 22:44:29 -0700 Subject: [PATCH 020/325] added mapping --- .../wordnik/swagger/codegen/languages/ObjcClientCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index 860698ada8c7..1182575c0938 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -58,7 +58,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("long", "NSNumber"); typeMapping.put("double", "NSNumber"); typeMapping.put("array", "NSArray"); - // typeMapping.put("array", "NSArray"); + typeMapping.put("number", "NSNumber"); typeMapping.put("List", "NSArray"); typeMapping.put("object", "NSObject"); From b90742e9954f38b43a5d30a9e81837d492b47118 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 18 Sep 2014 08:28:19 -0700 Subject: [PATCH 021/325] updated template location, added snapshot --- .../codegen/languages/JaxRSServerCodegen.java | 2 +- src/main/resources/JavaJaxRS/pom.mustache | 6 + swagger.json | 851 +++--------------- 3 files changed, 139 insertions(+), 720 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java index 4bde8918afb3..4a663faab6f4 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java @@ -22,7 +22,7 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf outputFolder = "generated-code/javaJaxRS"; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "src/main/resources/JavaJaxRS"; + templateDir = "JavaJaxRS"; apiPackage = "com.wordnik.api"; modelPackage = "com.wordnik.model"; diff --git a/src/main/resources/JavaJaxRS/pom.mustache b/src/main/resources/JavaJaxRS/pom.mustache index 55f69368ac94..26f154d167c4 100644 --- a/src/main/resources/JavaJaxRS/pom.mustache +++ b/src/main/resources/JavaJaxRS/pom.mustache @@ -114,6 +114,12 @@ ${servlet-api-version} + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + 1.5.0-SNAPSHOT 8.1.11.v20130520 diff --git a/swagger.json b/swagger.json index 5227492f2073..a06df3bfba07 100644 --- a/swagger.json +++ b/swagger.json @@ -1,723 +1,136 @@ { - "swagger": 2.0, - "info": { - "description": "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", - "version": "1.0.0", - "title": "Swagger Sample App", - "termsOfService": "http://helloreverb.com/terms/", - "contact": { - "name": "apiteam@wordnik.com" + "swagger": 2, + "info": { + "title": "HR API", + "description": "A way to manage people in our organization", + "version": "1.0.0" }, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + "host": "my.api.com", + "basePath": "/v2", + "paths": { + "/users": { + "get": { + "operationId": "getUsers", + "tags": [ + "users are awesome" + ], + "parameters": [ + { + "in": "query", + "description": "number of records to skip", + "name": "skip", + "type": "integer", + "format": "int32" + } + ], + "responses": { + "200": { + "description": "successful response", + "schema": { + "type": "array", + "items": { + "$ref": "User" + } + } + }, + "400": { + "description": "bad input", + "schema": { + "$ref": "ErrorModel" + } + }, + "default": { + "description": "got a response" + } + } + } + }, + "/users/{id}": { + "get": { + "tags": [ + "users" + ], + "operationId": "getUserById", + "parameters": [ + { + "in": "path", + "name": "id", + "type": "integer", + "format": "int64", + "description": "user id to look up by" + } + ], + "responses": { + "default": { + "description": "got a response" + } + } + } + }, + "/places": { + "get": { + "tags": [ + "locations" + ], + "operationId": "getPlaces", + "responses": { + "default": { + "description": "got a response" + } + } + } + }, + "/photos": { + "get": { + "tags": [ + "users" + ], + "operationId": "getPhotos", + "responses": { + "default": { + "description": "got a response" + } + } + } + } + }, + "definitions": { + "ErrorModel": { + "required": [ + "code", + "message" + ], + "properties": { + "code": { + "type": "integer", + "format": "int64" + }, + "message": { + "type": "string" + } + } + }, + "User": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "age": { + "type": "integer", + "format": "int32" + }, + "lastUpdated": { + "type": "string", + "format": "date-time" + } + } + } } - }, - "basePath": "/v2", - "paths": { - "/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" - } - } - } - }, - "/pet": { - "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" - } - } - }, - "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" - } - } - } - }, - "/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": [ - { - "in": "path", - "name": "orderId", - "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": [ - { - "in": "path", - "name": "orderId", - "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" - ], - "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" - } - } - } - }, - "/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" - } - } - } - }, - "/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": [ - { - "in": "query", - "name": "status", - "description": "Status values that need to be considered for filter", - "required": false, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "jaxrs" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "400": { - "description": "Invalid status value" - } - } - } - }, - "/user/{username}": { - "get": { - "tags": [ - "user" - ], - "summary": "Get user by user name", - "description": "", - "operationId": "getUserByName", - "produces": [ - "application/json", - "application/xml" - ], - "parameters": [ - { - "in": "path", - "name": "username", - "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": [ - { - "in": "path", - "name": "username", - "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": [ - { - "in": "path", - "name": "username", - "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" - ], - "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": [ - { - "in": "query", - "name": "tags", - "description": "Tags to filter by", - "required": false, - "type": "array", - "items": { - "type": "string" - }, - "collectionFormat": "jaxrs" - } - ], - "responses": { - "200": { - "description": "successful operation", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/Pet" - } - } - }, - "400": { - "description": "Invalid tag value" - } - } - } - }, - "/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/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/login": { - "get": { - "tags": [ - "user" - ], - "summary": "Logs user into the system", - "description": "", - "operationId": "loginUser", - "produces": [ - "application/json", - "application/xml" - ], - "parameters": [ - { - "in": "query", - "name": "username", - "description": "The user name for login", - "required": false, - "type": "string" - }, - { - "in": "query", - "name": "password", - "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" - } - } - } - }, - "/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": [ - { - "in": "path", - "name": "petId", - "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" - } - } - }, - "delete": { - "tags": [ - "pet" - ], - "summary": "Deletes a pet", - "description": "", - "operationId": "deletePet", - "produces": [ - "application/json", - "application/xml" - ], - "parameters": [ - { - "in": "path", - "name": "petId", - "description": "Pet id to delete", - "required": true, - "type": "integer", - "format": "int64" - } - ], - "responses": { - "400": { - "description": "Invalid pet value" - } - } - } - } - }, - "definitions": { - "User": { - "properties": { - "phone": { - "type": "string" - }, - "password": { - "type": "string" - }, - "email": { - "type": "string" - }, - "lastName": { - "type": "string" - }, - "firstName": { - "type": "string" - }, - "username": { - "type": "string" - }, - "id": { - "type": "integer", - "format": "int64" - }, - "userStatus": { - "type": "integer", - "format": "int32", - "position": 0 - } - } - }, - "Category": { - "properties": { - "name": { - "type": "string" - }, - "id": { - "type": "integer", - "format": "int64" - } - } - }, - "Pet": { - "enum": [ - "id", - "photoUrls", - "name" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "category": { - "$ref": "Category" - }, - "name": { - "type": "string", - "example": "doggie", - "position": 0 - }, - "photoUrls": { - "type": "array", - "items": { - "type": "string" - } - }, - "tags": { - "type": "array", - "items": { - "$ref": "Tag" - } - }, - "status": { - "type": "string", - "position": 0 - } - } - }, - "Tag": { - "properties": { - "name": { - "type": "string" - }, - "id": { - "type": "integer", - "format": "int64" - } - } - }, - "Order": { - "description": "All you ever needed to know about orders", - "enum": [ "id" ], - "properties": { - "id": { - "description": "the unique ID for the order", - "type": "integer", - "format": "int64" - }, - "petId": { - "description": "the ID of the pet being purchased", - "type": "integer", - "format": "int64" - }, - "quantity": { - "description": "number of pets in the order", - "type": "integer", - "format": "int32", - "minimum": 1, - "maximum": 100 - }, - "status": { - "type": "string", - "enum": [ "dead", "alive" ] - }, - "shipDate": { - "type": "string", - "format": "date-time" - } - } - } - } } From 504e1b28c542f6c42b8973542b8a3611b1ee2a6a Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 19 Sep 2014 14:05:31 -0700 Subject: [PATCH 022/325] added model package to templates --- src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java | 1 + src/main/resources/JavaJaxRS/api.mustache | 2 ++ 2 files changed, 3 insertions(+) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 63b8b8d2e423..05dfb6f1bd91 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -66,6 +66,7 @@ public class DefaultGenerator implements Generator { List ops = paths.get(tag); operations = processOperations(config, tag, ops); + operations.put("modelPackage", config.modelPackage()); operations.putAll(config.additionalProperties()); operations.put("baseName", tag); for(String templateName : config.apiTemplateFiles().keySet()) { diff --git a/src/main/resources/JavaJaxRS/api.mustache b/src/main/resources/JavaJaxRS/api.mustache index 68c629a6b094..adcacaeb29e0 100644 --- a/src/main/resources/JavaJaxRS/api.mustache +++ b/src/main/resources/JavaJaxRS/api.mustache @@ -1,5 +1,7 @@ package {{package}}; +import {{modelPackage}}.*; + import com.wordnik.swagger.annotations.*; {{#imports}}import {{import}}; From a0876f24a37133e2f909f9eab791fd9714c2cee5 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 19 Sep 2014 14:38:00 -0700 Subject: [PATCH 023/325] added travis file --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000000..85a33a2d847e --- /dev/null +++ b/.travis.yml @@ -0,0 +1,4 @@ +language: java +script: mvn verify +jdk: + - oraclejdk7 From 134c900aa16a2f33ae1fa4e7a4c04d93582d6371 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 19 Sep 2014 16:28:56 -0700 Subject: [PATCH 024/325] reorded for cleanliness --- src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 05dfb6f1bd91..6c5a1e76a73b 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -66,9 +66,9 @@ public class DefaultGenerator implements Generator { List ops = paths.get(tag); operations = processOperations(config, tag, ops); + operations.put("baseName", tag); operations.put("modelPackage", config.modelPackage()); operations.putAll(config.additionalProperties()); - operations.put("baseName", tag); for(String templateName : config.apiTemplateFiles().keySet()) { String suffix = config.apiTemplateFiles().get(templateName); String filename = config.apiFileFolder() + From 7630fd4f854690f9dbf056f1daf689837bbbf9dc Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 19 Sep 2014 16:36:28 -0700 Subject: [PATCH 025/325] added scripts --- bin/java-petstore-filemap.sh | 26 ++++++++++++++++++++++++++ bin/objc-petstore.sh | 26 ++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100755 bin/java-petstore-filemap.sh create mode 100755 bin/objc-petstore.sh diff --git a/bin/java-petstore-filemap.sh b/bin/java-petstore-filemap.sh new file mode 100755 index 000000000000..bedec4ab2c7f --- /dev/null +++ b/bin/java-petstore-filemap.sh @@ -0,0 +1,26 @@ +#!/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 + +# 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.Codegen -i src/test/resources/petstore.json -l java" + +java -cp $APP_DIR/target/*:$APP_DIR/target/lib/* $ags diff --git a/bin/objc-petstore.sh b/bin/objc-petstore.sh new file mode 100755 index 000000000000..683b1a8371dc --- /dev/null +++ b/bin/objc-petstore.sh @@ -0,0 +1,26 @@ +#!/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 + +# 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.Codegen -i src/test/resources/petstore.json -l objc" + +java -cp $APP_DIR/target/*:$APP_DIR/target/lib/* $ags From e5392dc21a539bbfe71a29e9cdb2d96854602381 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 19 Sep 2014 16:41:09 -0700 Subject: [PATCH 026/325] added script --- bin/objc-wordnik-api.sh | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100755 bin/objc-wordnik-api.sh diff --git a/bin/objc-wordnik-api.sh b/bin/objc-wordnik-api.sh new file mode 100755 index 000000000000..cde5fb50fc26 --- /dev/null +++ b/bin/objc-wordnik-api.sh @@ -0,0 +1,26 @@ +#!/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 + +# 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.Codegen -i src/test/resources/wordnik.json -l objc" + +java -cp $APP_DIR/target/*:$APP_DIR/target/lib/* $ags From 8762f38470eec586fbd7f02600378c92129bd5d4 Mon Sep 17 00:00:00 2001 From: isf Date: Mon, 8 Sep 2014 08:50:35 +0200 Subject: [PATCH 027/325] Issue 244 - checkout on windows fails due to special chars --- .../Podfile" => samples/client/wordnik-api-objc/Podfile | 0 .../client/wordnik-api-objc/client/SWGAccountApi.h | 0 .../client/wordnik-api-objc/client/SWGAccountApi.m | 0 .../client/wordnik-api-objc/client/SWGApiClient.h | 0 .../client/wordnik-api-objc/client/SWGApiClient.m | 0 .../client/wordnik-api-objc/client/SWGApiTokenStatus.h | 0 .../client/wordnik-api-objc/client/SWGApiTokenStatus.m | 0 .../client/wordnik-api-objc/client/SWGAudioFile.h | 0 .../client/wordnik-api-objc/client/SWGAudioFile.m | 0 .../client/wordnik-api-objc/client/SWGAuthenticationToken.h | 0 .../client/wordnik-api-objc/client/SWGAuthenticationToken.m | 0 .../client/wordnik-api-objc/client/SWGBigram.h | 0 .../client/wordnik-api-objc/client/SWGBigram.m | 0 .../client/wordnik-api-objc/client/SWGCitation.h | 0 .../client/wordnik-api-objc/client/SWGCitation.m | 0 .../client/wordnik-api-objc/client/SWGContentProvider.h | 0 .../client/wordnik-api-objc/client/SWGContentProvider.m | 0 .../client/wordnik-api-objc/client/SWGDate.h | 0 .../client/wordnik-api-objc/client/SWGDate.m | 0 .../client/wordnik-api-objc/client/SWGDefinition.h | 0 .../client/wordnik-api-objc/client/SWGDefinition.m | 0 .../client/wordnik-api-objc/client/SWGDefinitionSearchResults.h | 0 .../client/wordnik-api-objc/client/SWGDefinitionSearchResults.m | 0 .../client/wordnik-api-objc/client/SWGExample.h | 0 .../client/wordnik-api-objc/client/SWGExample.m | 0 .../client/wordnik-api-objc/client/SWGExampleSearchResults.h | 0 .../client/wordnik-api-objc/client/SWGExampleSearchResults.m | 0 .../client/wordnik-api-objc/client/SWGExampleUsage.h | 0 .../client/wordnik-api-objc/client/SWGExampleUsage.m | 0 .../client/wordnik-api-objc/client/SWGFacet.h | 0 .../client/wordnik-api-objc/client/SWGFacet.m | 0 .../client/wordnik-api-objc/client/SWGFacetValue.h | 0 .../client/wordnik-api-objc/client/SWGFacetValue.m | 0 .../client/wordnik-api-objc/client/SWGFile.h | 0 .../client/wordnik-api-objc/client/SWGFile.m | 0 .../client/wordnik-api-objc/client/SWGFrequency.h | 0 .../client/wordnik-api-objc/client/SWGFrequency.m | 0 .../client/wordnik-api-objc/client/SWGFrequencySummary.h | 0 .../client/wordnik-api-objc/client/SWGFrequencySummary.m | 0 .../client/wordnik-api-objc/client/SWGLabel.h | 0 .../client/wordnik-api-objc/client/SWGLabel.m | 0 .../client/wordnik-api-objc/client/SWGNote.h | 0 .../client/wordnik-api-objc/client/SWGNote.m | 0 .../client/wordnik-api-objc/client/SWGObject.h | 0 .../client/wordnik-api-objc/client/SWGObject.m | 0 .../client/wordnik-api-objc/client/SWGRelated.h | 0 .../client/wordnik-api-objc/client/SWGRelated.m | 0 .../client/wordnik-api-objc/client/SWGScoredWord.h | 0 .../client/wordnik-api-objc/client/SWGScoredWord.m | 0 .../client/wordnik-api-objc/client/SWGScrabbleScoreResult.h | 0 .../client/wordnik-api-objc/client/SWGScrabbleScoreResult.m | 0 .../client/wordnik-api-objc/client/SWGSentence.h | 0 .../client/wordnik-api-objc/client/SWGSentence.m | 0 .../client/wordnik-api-objc/client/SWGSimpleDefinition.h | 0 .../client/wordnik-api-objc/client/SWGSimpleDefinition.m | 0 .../client/wordnik-api-objc/client/SWGSimpleExample.h | 0 .../client/wordnik-api-objc/client/SWGSimpleExample.m | 0 .../client/wordnik-api-objc/client/SWGStringValue.h | 0 .../client/wordnik-api-objc/client/SWGStringValue.m | 0 .../client/wordnik-api-objc/client/SWGSyllable.h | 0 .../client/wordnik-api-objc/client/SWGSyllable.m | 0 .../client/wordnik-api-objc/client/SWGTextPron.h | 0 .../client/wordnik-api-objc/client/SWGTextPron.m | 0 .../client/wordnik-api-objc/client/SWGUser.h | 0 .../client/wordnik-api-objc/client/SWGUser.m | 0 .../client/wordnik-api-objc/client/SWGWordApi.h | 0 .../client/wordnik-api-objc/client/SWGWordApi.m | 0 .../client/wordnik-api-objc/client/SWGWordList.h | 0 .../client/wordnik-api-objc/client/SWGWordList.m | 0 .../client/wordnik-api-objc/client/SWGWordListApi.h | 0 .../client/wordnik-api-objc/client/SWGWordListApi.m | 0 .../client/wordnik-api-objc/client/SWGWordListWord.h | 0 .../client/wordnik-api-objc/client/SWGWordListWord.m | 0 .../client/wordnik-api-objc/client/SWGWordListsApi.h | 0 .../client/wordnik-api-objc/client/SWGWordListsApi.m | 0 .../client/wordnik-api-objc/client/SWGWordObject.h | 0 .../client/wordnik-api-objc/client/SWGWordObject.m | 0 .../client/wordnik-api-objc/client/SWGWordOfTheDay.h | 0 .../client/wordnik-api-objc/client/SWGWordOfTheDay.m | 0 .../client/wordnik-api-objc/client/SWGWordSearchResult.h | 0 .../client/wordnik-api-objc/client/SWGWordSearchResult.m | 0 .../client/wordnik-api-objc/client/SWGWordSearchResults.h | 0 .../client/wordnik-api-objc/client/SWGWordSearchResults.m | 0 .../client/wordnik-api-objc/client/SWGWordsApi.h | 0 .../client/wordnik-api-objc/client/SWGWordsApi.m | 0 .../client/wordnik-api-php/PHPWordnikApiCodegen.scala | 0 .../README.md" => samples/client/wordnik-api-php/README.md | 0 .../client/wordnik-api-php/tests/BaseApiTest.php | 0 .../client/wordnik-api-php/wordnik/AccountApi.php | 0 89 files changed, 0 insertions(+), 0 deletions(-) rename "samples/client/wordnik-api\aobjc/Podfile" => samples/client/wordnik-api-objc/Podfile (100%) rename "samples/client/wordnik-api\aobjc/client/SWGAccountApi.h" => samples/client/wordnik-api-objc/client/SWGAccountApi.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGAccountApi.m" => samples/client/wordnik-api-objc/client/SWGAccountApi.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGApiClient.h" => samples/client/wordnik-api-objc/client/SWGApiClient.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGApiClient.m" => samples/client/wordnik-api-objc/client/SWGApiClient.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGApiTokenStatus.h" => samples/client/wordnik-api-objc/client/SWGApiTokenStatus.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGApiTokenStatus.m" => samples/client/wordnik-api-objc/client/SWGApiTokenStatus.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGAudioFile.h" => samples/client/wordnik-api-objc/client/SWGAudioFile.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGAudioFile.m" => samples/client/wordnik-api-objc/client/SWGAudioFile.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGAuthenticationToken.h" => samples/client/wordnik-api-objc/client/SWGAuthenticationToken.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGAuthenticationToken.m" => samples/client/wordnik-api-objc/client/SWGAuthenticationToken.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGBigram.h" => samples/client/wordnik-api-objc/client/SWGBigram.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGBigram.m" => samples/client/wordnik-api-objc/client/SWGBigram.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGCitation.h" => samples/client/wordnik-api-objc/client/SWGCitation.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGCitation.m" => samples/client/wordnik-api-objc/client/SWGCitation.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGContentProvider.h" => samples/client/wordnik-api-objc/client/SWGContentProvider.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGContentProvider.m" => samples/client/wordnik-api-objc/client/SWGContentProvider.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGDate.h" => samples/client/wordnik-api-objc/client/SWGDate.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGDate.m" => samples/client/wordnik-api-objc/client/SWGDate.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGDefinition.h" => samples/client/wordnik-api-objc/client/SWGDefinition.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGDefinition.m" => samples/client/wordnik-api-objc/client/SWGDefinition.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGDefinitionSearchResults.h" => samples/client/wordnik-api-objc/client/SWGDefinitionSearchResults.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGDefinitionSearchResults.m" => samples/client/wordnik-api-objc/client/SWGDefinitionSearchResults.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGExample.h" => samples/client/wordnik-api-objc/client/SWGExample.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGExample.m" => samples/client/wordnik-api-objc/client/SWGExample.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGExampleSearchResults.h" => samples/client/wordnik-api-objc/client/SWGExampleSearchResults.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGExampleSearchResults.m" => samples/client/wordnik-api-objc/client/SWGExampleSearchResults.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGExampleUsage.h" => samples/client/wordnik-api-objc/client/SWGExampleUsage.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGExampleUsage.m" => samples/client/wordnik-api-objc/client/SWGExampleUsage.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGFacet.h" => samples/client/wordnik-api-objc/client/SWGFacet.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGFacet.m" => samples/client/wordnik-api-objc/client/SWGFacet.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGFacetValue.h" => samples/client/wordnik-api-objc/client/SWGFacetValue.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGFacetValue.m" => samples/client/wordnik-api-objc/client/SWGFacetValue.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGFile.h" => samples/client/wordnik-api-objc/client/SWGFile.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGFile.m" => samples/client/wordnik-api-objc/client/SWGFile.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGFrequency.h" => samples/client/wordnik-api-objc/client/SWGFrequency.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGFrequency.m" => samples/client/wordnik-api-objc/client/SWGFrequency.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGFrequencySummary.h" => samples/client/wordnik-api-objc/client/SWGFrequencySummary.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGFrequencySummary.m" => samples/client/wordnik-api-objc/client/SWGFrequencySummary.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGLabel.h" => samples/client/wordnik-api-objc/client/SWGLabel.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGLabel.m" => samples/client/wordnik-api-objc/client/SWGLabel.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGNote.h" => samples/client/wordnik-api-objc/client/SWGNote.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGNote.m" => samples/client/wordnik-api-objc/client/SWGNote.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGObject.h" => samples/client/wordnik-api-objc/client/SWGObject.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGObject.m" => samples/client/wordnik-api-objc/client/SWGObject.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGRelated.h" => samples/client/wordnik-api-objc/client/SWGRelated.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGRelated.m" => samples/client/wordnik-api-objc/client/SWGRelated.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGScoredWord.h" => samples/client/wordnik-api-objc/client/SWGScoredWord.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGScoredWord.m" => samples/client/wordnik-api-objc/client/SWGScoredWord.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGScrabbleScoreResult.h" => samples/client/wordnik-api-objc/client/SWGScrabbleScoreResult.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGScrabbleScoreResult.m" => samples/client/wordnik-api-objc/client/SWGScrabbleScoreResult.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGSentence.h" => samples/client/wordnik-api-objc/client/SWGSentence.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGSentence.m" => samples/client/wordnik-api-objc/client/SWGSentence.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGSimpleDefinition.h" => samples/client/wordnik-api-objc/client/SWGSimpleDefinition.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGSimpleDefinition.m" => samples/client/wordnik-api-objc/client/SWGSimpleDefinition.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGSimpleExample.h" => samples/client/wordnik-api-objc/client/SWGSimpleExample.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGSimpleExample.m" => samples/client/wordnik-api-objc/client/SWGSimpleExample.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGStringValue.h" => samples/client/wordnik-api-objc/client/SWGStringValue.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGStringValue.m" => samples/client/wordnik-api-objc/client/SWGStringValue.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGSyllable.h" => samples/client/wordnik-api-objc/client/SWGSyllable.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGSyllable.m" => samples/client/wordnik-api-objc/client/SWGSyllable.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGTextPron.h" => samples/client/wordnik-api-objc/client/SWGTextPron.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGTextPron.m" => samples/client/wordnik-api-objc/client/SWGTextPron.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGUser.h" => samples/client/wordnik-api-objc/client/SWGUser.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGUser.m" => samples/client/wordnik-api-objc/client/SWGUser.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordApi.h" => samples/client/wordnik-api-objc/client/SWGWordApi.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordApi.m" => samples/client/wordnik-api-objc/client/SWGWordApi.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordList.h" => samples/client/wordnik-api-objc/client/SWGWordList.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordList.m" => samples/client/wordnik-api-objc/client/SWGWordList.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordListApi.h" => samples/client/wordnik-api-objc/client/SWGWordListApi.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordListApi.m" => samples/client/wordnik-api-objc/client/SWGWordListApi.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordListWord.h" => samples/client/wordnik-api-objc/client/SWGWordListWord.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordListWord.m" => samples/client/wordnik-api-objc/client/SWGWordListWord.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordListsApi.h" => samples/client/wordnik-api-objc/client/SWGWordListsApi.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordListsApi.m" => samples/client/wordnik-api-objc/client/SWGWordListsApi.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordObject.h" => samples/client/wordnik-api-objc/client/SWGWordObject.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordObject.m" => samples/client/wordnik-api-objc/client/SWGWordObject.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordOfTheDay.h" => samples/client/wordnik-api-objc/client/SWGWordOfTheDay.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordOfTheDay.m" => samples/client/wordnik-api-objc/client/SWGWordOfTheDay.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordSearchResult.h" => samples/client/wordnik-api-objc/client/SWGWordSearchResult.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordSearchResult.m" => samples/client/wordnik-api-objc/client/SWGWordSearchResult.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordSearchResults.h" => samples/client/wordnik-api-objc/client/SWGWordSearchResults.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordSearchResults.m" => samples/client/wordnik-api-objc/client/SWGWordSearchResults.m (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordsApi.h" => samples/client/wordnik-api-objc/client/SWGWordsApi.h (100%) rename "samples/client/wordnik-api\aobjc/client/SWGWordsApi.m" => samples/client/wordnik-api-objc/client/SWGWordsApi.m (100%) rename "samples/client/wordnik-api\aphp/PHPWordnikApiCodegen.scala" => samples/client/wordnik-api-php/PHPWordnikApiCodegen.scala (100%) rename "samples/client/wordnik-api\aphp/README.md" => samples/client/wordnik-api-php/README.md (100%) rename "samples/client/wordnik-api\aphp/tests/BaseApiTest.php" => samples/client/wordnik-api-php/tests/BaseApiTest.php (100%) rename "samples/client/wordnik-api\aphp/wordnik/AccountApi.php" => samples/client/wordnik-api-php/wordnik/AccountApi.php (100%) diff --git "a/samples/client/wordnik-api\aobjc/Podfile" b/samples/client/wordnik-api-objc/Podfile similarity index 100% rename from "samples/client/wordnik-api\aobjc/Podfile" rename to samples/client/wordnik-api-objc/Podfile diff --git "a/samples/client/wordnik-api\aobjc/client/SWGAccountApi.h" b/samples/client/wordnik-api-objc/client/SWGAccountApi.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGAccountApi.h" rename to samples/client/wordnik-api-objc/client/SWGAccountApi.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGAccountApi.m" b/samples/client/wordnik-api-objc/client/SWGAccountApi.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGAccountApi.m" rename to samples/client/wordnik-api-objc/client/SWGAccountApi.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGApiClient.h" b/samples/client/wordnik-api-objc/client/SWGApiClient.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGApiClient.h" rename to samples/client/wordnik-api-objc/client/SWGApiClient.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGApiClient.m" b/samples/client/wordnik-api-objc/client/SWGApiClient.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGApiClient.m" rename to samples/client/wordnik-api-objc/client/SWGApiClient.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGApiTokenStatus.h" b/samples/client/wordnik-api-objc/client/SWGApiTokenStatus.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGApiTokenStatus.h" rename to samples/client/wordnik-api-objc/client/SWGApiTokenStatus.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGApiTokenStatus.m" b/samples/client/wordnik-api-objc/client/SWGApiTokenStatus.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGApiTokenStatus.m" rename to samples/client/wordnik-api-objc/client/SWGApiTokenStatus.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGAudioFile.h" b/samples/client/wordnik-api-objc/client/SWGAudioFile.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGAudioFile.h" rename to samples/client/wordnik-api-objc/client/SWGAudioFile.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGAudioFile.m" b/samples/client/wordnik-api-objc/client/SWGAudioFile.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGAudioFile.m" rename to samples/client/wordnik-api-objc/client/SWGAudioFile.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGAuthenticationToken.h" b/samples/client/wordnik-api-objc/client/SWGAuthenticationToken.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGAuthenticationToken.h" rename to samples/client/wordnik-api-objc/client/SWGAuthenticationToken.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGAuthenticationToken.m" b/samples/client/wordnik-api-objc/client/SWGAuthenticationToken.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGAuthenticationToken.m" rename to samples/client/wordnik-api-objc/client/SWGAuthenticationToken.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGBigram.h" b/samples/client/wordnik-api-objc/client/SWGBigram.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGBigram.h" rename to samples/client/wordnik-api-objc/client/SWGBigram.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGBigram.m" b/samples/client/wordnik-api-objc/client/SWGBigram.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGBigram.m" rename to samples/client/wordnik-api-objc/client/SWGBigram.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGCitation.h" b/samples/client/wordnik-api-objc/client/SWGCitation.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGCitation.h" rename to samples/client/wordnik-api-objc/client/SWGCitation.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGCitation.m" b/samples/client/wordnik-api-objc/client/SWGCitation.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGCitation.m" rename to samples/client/wordnik-api-objc/client/SWGCitation.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGContentProvider.h" b/samples/client/wordnik-api-objc/client/SWGContentProvider.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGContentProvider.h" rename to samples/client/wordnik-api-objc/client/SWGContentProvider.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGContentProvider.m" b/samples/client/wordnik-api-objc/client/SWGContentProvider.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGContentProvider.m" rename to samples/client/wordnik-api-objc/client/SWGContentProvider.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGDate.h" b/samples/client/wordnik-api-objc/client/SWGDate.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGDate.h" rename to samples/client/wordnik-api-objc/client/SWGDate.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGDate.m" b/samples/client/wordnik-api-objc/client/SWGDate.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGDate.m" rename to samples/client/wordnik-api-objc/client/SWGDate.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGDefinition.h" b/samples/client/wordnik-api-objc/client/SWGDefinition.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGDefinition.h" rename to samples/client/wordnik-api-objc/client/SWGDefinition.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGDefinition.m" b/samples/client/wordnik-api-objc/client/SWGDefinition.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGDefinition.m" rename to samples/client/wordnik-api-objc/client/SWGDefinition.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGDefinitionSearchResults.h" b/samples/client/wordnik-api-objc/client/SWGDefinitionSearchResults.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGDefinitionSearchResults.h" rename to samples/client/wordnik-api-objc/client/SWGDefinitionSearchResults.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGDefinitionSearchResults.m" b/samples/client/wordnik-api-objc/client/SWGDefinitionSearchResults.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGDefinitionSearchResults.m" rename to samples/client/wordnik-api-objc/client/SWGDefinitionSearchResults.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGExample.h" b/samples/client/wordnik-api-objc/client/SWGExample.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGExample.h" rename to samples/client/wordnik-api-objc/client/SWGExample.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGExample.m" b/samples/client/wordnik-api-objc/client/SWGExample.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGExample.m" rename to samples/client/wordnik-api-objc/client/SWGExample.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGExampleSearchResults.h" b/samples/client/wordnik-api-objc/client/SWGExampleSearchResults.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGExampleSearchResults.h" rename to samples/client/wordnik-api-objc/client/SWGExampleSearchResults.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGExampleSearchResults.m" b/samples/client/wordnik-api-objc/client/SWGExampleSearchResults.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGExampleSearchResults.m" rename to samples/client/wordnik-api-objc/client/SWGExampleSearchResults.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGExampleUsage.h" b/samples/client/wordnik-api-objc/client/SWGExampleUsage.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGExampleUsage.h" rename to samples/client/wordnik-api-objc/client/SWGExampleUsage.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGExampleUsage.m" b/samples/client/wordnik-api-objc/client/SWGExampleUsage.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGExampleUsage.m" rename to samples/client/wordnik-api-objc/client/SWGExampleUsage.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGFacet.h" b/samples/client/wordnik-api-objc/client/SWGFacet.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGFacet.h" rename to samples/client/wordnik-api-objc/client/SWGFacet.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGFacet.m" b/samples/client/wordnik-api-objc/client/SWGFacet.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGFacet.m" rename to samples/client/wordnik-api-objc/client/SWGFacet.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGFacetValue.h" b/samples/client/wordnik-api-objc/client/SWGFacetValue.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGFacetValue.h" rename to samples/client/wordnik-api-objc/client/SWGFacetValue.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGFacetValue.m" b/samples/client/wordnik-api-objc/client/SWGFacetValue.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGFacetValue.m" rename to samples/client/wordnik-api-objc/client/SWGFacetValue.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGFile.h" b/samples/client/wordnik-api-objc/client/SWGFile.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGFile.h" rename to samples/client/wordnik-api-objc/client/SWGFile.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGFile.m" b/samples/client/wordnik-api-objc/client/SWGFile.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGFile.m" rename to samples/client/wordnik-api-objc/client/SWGFile.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGFrequency.h" b/samples/client/wordnik-api-objc/client/SWGFrequency.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGFrequency.h" rename to samples/client/wordnik-api-objc/client/SWGFrequency.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGFrequency.m" b/samples/client/wordnik-api-objc/client/SWGFrequency.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGFrequency.m" rename to samples/client/wordnik-api-objc/client/SWGFrequency.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGFrequencySummary.h" b/samples/client/wordnik-api-objc/client/SWGFrequencySummary.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGFrequencySummary.h" rename to samples/client/wordnik-api-objc/client/SWGFrequencySummary.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGFrequencySummary.m" b/samples/client/wordnik-api-objc/client/SWGFrequencySummary.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGFrequencySummary.m" rename to samples/client/wordnik-api-objc/client/SWGFrequencySummary.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGLabel.h" b/samples/client/wordnik-api-objc/client/SWGLabel.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGLabel.h" rename to samples/client/wordnik-api-objc/client/SWGLabel.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGLabel.m" b/samples/client/wordnik-api-objc/client/SWGLabel.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGLabel.m" rename to samples/client/wordnik-api-objc/client/SWGLabel.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGNote.h" b/samples/client/wordnik-api-objc/client/SWGNote.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGNote.h" rename to samples/client/wordnik-api-objc/client/SWGNote.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGNote.m" b/samples/client/wordnik-api-objc/client/SWGNote.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGNote.m" rename to samples/client/wordnik-api-objc/client/SWGNote.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGObject.h" b/samples/client/wordnik-api-objc/client/SWGObject.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGObject.h" rename to samples/client/wordnik-api-objc/client/SWGObject.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGObject.m" b/samples/client/wordnik-api-objc/client/SWGObject.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGObject.m" rename to samples/client/wordnik-api-objc/client/SWGObject.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGRelated.h" b/samples/client/wordnik-api-objc/client/SWGRelated.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGRelated.h" rename to samples/client/wordnik-api-objc/client/SWGRelated.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGRelated.m" b/samples/client/wordnik-api-objc/client/SWGRelated.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGRelated.m" rename to samples/client/wordnik-api-objc/client/SWGRelated.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGScoredWord.h" b/samples/client/wordnik-api-objc/client/SWGScoredWord.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGScoredWord.h" rename to samples/client/wordnik-api-objc/client/SWGScoredWord.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGScoredWord.m" b/samples/client/wordnik-api-objc/client/SWGScoredWord.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGScoredWord.m" rename to samples/client/wordnik-api-objc/client/SWGScoredWord.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGScrabbleScoreResult.h" b/samples/client/wordnik-api-objc/client/SWGScrabbleScoreResult.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGScrabbleScoreResult.h" rename to samples/client/wordnik-api-objc/client/SWGScrabbleScoreResult.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGScrabbleScoreResult.m" b/samples/client/wordnik-api-objc/client/SWGScrabbleScoreResult.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGScrabbleScoreResult.m" rename to samples/client/wordnik-api-objc/client/SWGScrabbleScoreResult.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGSentence.h" b/samples/client/wordnik-api-objc/client/SWGSentence.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGSentence.h" rename to samples/client/wordnik-api-objc/client/SWGSentence.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGSentence.m" b/samples/client/wordnik-api-objc/client/SWGSentence.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGSentence.m" rename to samples/client/wordnik-api-objc/client/SWGSentence.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGSimpleDefinition.h" b/samples/client/wordnik-api-objc/client/SWGSimpleDefinition.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGSimpleDefinition.h" rename to samples/client/wordnik-api-objc/client/SWGSimpleDefinition.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGSimpleDefinition.m" b/samples/client/wordnik-api-objc/client/SWGSimpleDefinition.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGSimpleDefinition.m" rename to samples/client/wordnik-api-objc/client/SWGSimpleDefinition.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGSimpleExample.h" b/samples/client/wordnik-api-objc/client/SWGSimpleExample.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGSimpleExample.h" rename to samples/client/wordnik-api-objc/client/SWGSimpleExample.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGSimpleExample.m" b/samples/client/wordnik-api-objc/client/SWGSimpleExample.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGSimpleExample.m" rename to samples/client/wordnik-api-objc/client/SWGSimpleExample.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGStringValue.h" b/samples/client/wordnik-api-objc/client/SWGStringValue.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGStringValue.h" rename to samples/client/wordnik-api-objc/client/SWGStringValue.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGStringValue.m" b/samples/client/wordnik-api-objc/client/SWGStringValue.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGStringValue.m" rename to samples/client/wordnik-api-objc/client/SWGStringValue.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGSyllable.h" b/samples/client/wordnik-api-objc/client/SWGSyllable.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGSyllable.h" rename to samples/client/wordnik-api-objc/client/SWGSyllable.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGSyllable.m" b/samples/client/wordnik-api-objc/client/SWGSyllable.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGSyllable.m" rename to samples/client/wordnik-api-objc/client/SWGSyllable.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGTextPron.h" b/samples/client/wordnik-api-objc/client/SWGTextPron.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGTextPron.h" rename to samples/client/wordnik-api-objc/client/SWGTextPron.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGTextPron.m" b/samples/client/wordnik-api-objc/client/SWGTextPron.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGTextPron.m" rename to samples/client/wordnik-api-objc/client/SWGTextPron.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGUser.h" b/samples/client/wordnik-api-objc/client/SWGUser.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGUser.h" rename to samples/client/wordnik-api-objc/client/SWGUser.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGUser.m" b/samples/client/wordnik-api-objc/client/SWGUser.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGUser.m" rename to samples/client/wordnik-api-objc/client/SWGUser.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordApi.h" b/samples/client/wordnik-api-objc/client/SWGWordApi.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordApi.h" rename to samples/client/wordnik-api-objc/client/SWGWordApi.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordApi.m" b/samples/client/wordnik-api-objc/client/SWGWordApi.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordApi.m" rename to samples/client/wordnik-api-objc/client/SWGWordApi.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordList.h" b/samples/client/wordnik-api-objc/client/SWGWordList.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordList.h" rename to samples/client/wordnik-api-objc/client/SWGWordList.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordList.m" b/samples/client/wordnik-api-objc/client/SWGWordList.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordList.m" rename to samples/client/wordnik-api-objc/client/SWGWordList.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordListApi.h" b/samples/client/wordnik-api-objc/client/SWGWordListApi.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordListApi.h" rename to samples/client/wordnik-api-objc/client/SWGWordListApi.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordListApi.m" b/samples/client/wordnik-api-objc/client/SWGWordListApi.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordListApi.m" rename to samples/client/wordnik-api-objc/client/SWGWordListApi.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordListWord.h" b/samples/client/wordnik-api-objc/client/SWGWordListWord.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordListWord.h" rename to samples/client/wordnik-api-objc/client/SWGWordListWord.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordListWord.m" b/samples/client/wordnik-api-objc/client/SWGWordListWord.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordListWord.m" rename to samples/client/wordnik-api-objc/client/SWGWordListWord.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordListsApi.h" b/samples/client/wordnik-api-objc/client/SWGWordListsApi.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordListsApi.h" rename to samples/client/wordnik-api-objc/client/SWGWordListsApi.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordListsApi.m" b/samples/client/wordnik-api-objc/client/SWGWordListsApi.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordListsApi.m" rename to samples/client/wordnik-api-objc/client/SWGWordListsApi.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordObject.h" b/samples/client/wordnik-api-objc/client/SWGWordObject.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordObject.h" rename to samples/client/wordnik-api-objc/client/SWGWordObject.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordObject.m" b/samples/client/wordnik-api-objc/client/SWGWordObject.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordObject.m" rename to samples/client/wordnik-api-objc/client/SWGWordObject.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordOfTheDay.h" b/samples/client/wordnik-api-objc/client/SWGWordOfTheDay.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordOfTheDay.h" rename to samples/client/wordnik-api-objc/client/SWGWordOfTheDay.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordOfTheDay.m" b/samples/client/wordnik-api-objc/client/SWGWordOfTheDay.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordOfTheDay.m" rename to samples/client/wordnik-api-objc/client/SWGWordOfTheDay.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordSearchResult.h" b/samples/client/wordnik-api-objc/client/SWGWordSearchResult.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordSearchResult.h" rename to samples/client/wordnik-api-objc/client/SWGWordSearchResult.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordSearchResult.m" b/samples/client/wordnik-api-objc/client/SWGWordSearchResult.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordSearchResult.m" rename to samples/client/wordnik-api-objc/client/SWGWordSearchResult.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordSearchResults.h" b/samples/client/wordnik-api-objc/client/SWGWordSearchResults.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordSearchResults.h" rename to samples/client/wordnik-api-objc/client/SWGWordSearchResults.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordSearchResults.m" b/samples/client/wordnik-api-objc/client/SWGWordSearchResults.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordSearchResults.m" rename to samples/client/wordnik-api-objc/client/SWGWordSearchResults.m diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordsApi.h" b/samples/client/wordnik-api-objc/client/SWGWordsApi.h similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordsApi.h" rename to samples/client/wordnik-api-objc/client/SWGWordsApi.h diff --git "a/samples/client/wordnik-api\aobjc/client/SWGWordsApi.m" b/samples/client/wordnik-api-objc/client/SWGWordsApi.m similarity index 100% rename from "samples/client/wordnik-api\aobjc/client/SWGWordsApi.m" rename to samples/client/wordnik-api-objc/client/SWGWordsApi.m diff --git "a/samples/client/wordnik-api\aphp/PHPWordnikApiCodegen.scala" b/samples/client/wordnik-api-php/PHPWordnikApiCodegen.scala similarity index 100% rename from "samples/client/wordnik-api\aphp/PHPWordnikApiCodegen.scala" rename to samples/client/wordnik-api-php/PHPWordnikApiCodegen.scala diff --git "a/samples/client/wordnik-api\aphp/README.md" b/samples/client/wordnik-api-php/README.md similarity index 100% rename from "samples/client/wordnik-api\aphp/README.md" rename to samples/client/wordnik-api-php/README.md diff --git "a/samples/client/wordnik-api\aphp/tests/BaseApiTest.php" b/samples/client/wordnik-api-php/tests/BaseApiTest.php similarity index 100% rename from "samples/client/wordnik-api\aphp/tests/BaseApiTest.php" rename to samples/client/wordnik-api-php/tests/BaseApiTest.php diff --git "a/samples/client/wordnik-api\aphp/wordnik/AccountApi.php" b/samples/client/wordnik-api-php/wordnik/AccountApi.php similarity index 100% rename from "samples/client/wordnik-api\aphp/wordnik/AccountApi.php" rename to samples/client/wordnik-api-php/wordnik/AccountApi.php From 46f5fe06116604b114217f762fb5d57436ef31ee Mon Sep 17 00:00:00 2001 From: Martin Ehrnhoefer Date: Fri, 19 Sep 2014 18:24:53 +0200 Subject: [PATCH 028/325] #268 Windows path problem fixed --- .../java/com/wordnik/swagger/codegen/DefaultCodegen.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 0928dd364312..d616cafd943a 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -65,12 +65,15 @@ public class DefaultCodegen { public Map modelTemplateFiles() { return modelTemplateFiles; } + public String apiFileFolder() { - return outputFolder + File.separator + apiPackage().replaceAll("\\.", File.separator); + return outputFolder + "/" + apiPackage().replaceAll("\\.", "/"); } + public String modelFileFolder() { - return outputFolder + File.separator + modelPackage().replaceAll("\\.", File.separator); + return outputFolder + "/" + modelPackage().replaceAll("\\.", "/"); } + public Map additionalProperties() { return additionalProperties; } From db29ecc8d0e9a7b449239ef078c0c42ea0fbba4f Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Mon, 22 Sep 2014 16:44:01 -0700 Subject: [PATCH 029/325] added file from master --- README.md | 243 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 243 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 000000000000..2fce1d7471f2 --- /dev/null +++ b/README.md @@ -0,0 +1,243 @@ +# Swagger Code Generator + +[![Build Status](https://travis-ci.org/wordnik/swagger-codegen.png)](https://travis-ci.org/wordnik/swagger-codegen) + +## Overview +This is the swagger codegen project, which allows generation of client libraries automatically from a +Swagger-compliant server. + +## What's Swagger? + +The goal of Swaggerâ„¢ is to define a standard, language-agnostic interface to REST APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection. When properly defined via Swagger, a consumer can understand and interact with the remote service with a minimal amount of implementation logic. Similar to what interfaces have done for lower-level programming, Swagger removes the guesswork in calling the service. + + +Check out [Swagger-Spec](https://github.com/wordnik/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more. + + +## Compatability +The Swagger Specification has undergone 3 revisions since initial creation in 2010. The swagger-codegen project has the following compatibilies with the swagger specification: + +Swagger Codegen Version | Release Date | Swagger Spec compatability | Notes +----------------------- | ------------ | -------------------------- | ----- +2.1.0 (in development) | n/a | 2.0 | [branch develop_2.0](https://github.com/wordnik/swagger-codegen/tree/develop_2.0) +2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/wordnik/swagger-codegen/tree/v2.0.17) +1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/wordnik/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! + +* [Apache maven 3.0.3 or greater](http://maven.apache.org/) + +After cloning the project, you can build it from source with this command: + +``` +mvn package +``` + +### To generate a sample client library +You can build a client against Wordnik's [petstore](http://petstore.swagger.wordnik.com) API as follows: + +``` +./bin/scala-petstore.sh +``` + +This will run the script in [samples/client/petstore/ScalaPetstoreCodegen.scala](https://github.com/wordnik/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: + +``` +cd samples/client/petstore/scala +mvn package +``` + +Other languages have petstore samples, too: +``` +./bin/flash-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/wordnik/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. + +### 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. + +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. + +### Where is Javascript??? +See our [javascript library](http://github.com/wordnik/swagger.js)--it's completely dynamic and doesn't require +static code generation. +There is a third-party component called [swagger-js-codegen](https://github.com/wcandillon/swagger-js-codegen) that can generate angularjs or nodejs source code from a swagger specification. + + +#### Generating a client from flat files (i.e. no remote server calls) +If you don't want to call your server, you can save the swagger spec files into a directory and pass an argument +to the code generator like this: + +``` +-DfileMap=/path/to/resource-listing +``` + +Or for example: +``` +./bin/java-petstore-filemap.sh +``` + +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. + +### 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-core](https://github.com/wordnik/swagger-core/wiki). 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: + +``` +./bin/validate.sh http://petstore.swagger.wordnik.com/api/api-docs "specia-key" ./swagger-errors.html +``` + +### 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. + +``` +./bin/static-docs.sh +``` + +Will produce the output here: + +``` +https://github.com/wordnik/swagger-codegen/tree/master/samples/docs/swagger-static-docs +``` + +which is based on these templates: + +``` +https://github.com/wordnik/swagger-codegen/tree/master/src/main/resources/swagger-static +``` + +and looks like this + +![Image](https://raw.github.com/wordnik/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/wordnik/swagger-codegen/tree/master/samples/server-generator/node) + +* [ruby sinatra generator](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/sinatra) + +* [scala scalatra generator](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) + +* [java jax-rs generator](https://github.com/wordnik/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/wordnik/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 +``` + +Will read the 1.1 spec from wordnik developer and write it into the folder called `wordnik-developer`. + + +### To build the codegen library + +This will create the swagger-codegen library from source. + +``` +./sbt assembly +``` + +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! + +License +------- + +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 [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. From 394a064cc37d1dcfa9faad3049c2d09eba7a63d8 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Mon, 22 Sep 2014 16:44:19 -0700 Subject: [PATCH 030/325] added scripts --- bin/all-petstore.sh | 37 +++++++++++++++++++++++++++++++++ bin/android-java-petstore.sh | 32 ++++++++++++++++++++++++++++ bin/android-java-wordnik-api.sh | 32 ++++++++++++++++++++++++++++ bin/csharp-petstore.sh | 32 ++++++++++++++++++++++++++++ bin/flash-petstore.sh | 32 ++++++++++++++++++++++++++++ bin/java-petstore.sh | 27 ++++++++++++++++++++++++ bin/java-wordnik-api.sh | 26 +++++++++++++++++++++++ bin/php-petstore.sh | 32 ++++++++++++++++++++++++++++ bin/php-wordnik-api.sh | 32 ++++++++++++++++++++++++++++ bin/python-petstore.sh | 32 ++++++++++++++++++++++++++++ bin/python-wordnik-api.sh | 32 ++++++++++++++++++++++++++++ bin/python3-petstore.sh | 32 ++++++++++++++++++++++++++++ bin/python3-wordnik-api.sh | 32 ++++++++++++++++++++++++++++ bin/ruby-petstore.sh | 32 ++++++++++++++++++++++++++++ bin/runscala.sh | 32 ++++++++++++++++++++++++++++ bin/scala-async.sh | 31 +++++++++++++++++++++++++++ bin/scala-petstore.sh | 32 ++++++++++++++++++++++++++++ bin/scala-wordnik-api.sh | 32 ++++++++++++++++++++++++++++ bin/static-docs.sh | 32 ++++++++++++++++++++++++++++ bin/update-spec.sh | 31 +++++++++++++++++++++++++++ bin/validate.sh | 31 +++++++++++++++++++++++++++ 21 files changed, 663 insertions(+) create mode 100755 bin/all-petstore.sh create mode 100755 bin/android-java-petstore.sh create mode 100755 bin/android-java-wordnik-api.sh create mode 100755 bin/csharp-petstore.sh create mode 100755 bin/flash-petstore.sh create mode 100755 bin/java-petstore.sh create mode 100755 bin/java-wordnik-api.sh create mode 100755 bin/php-petstore.sh create mode 100755 bin/php-wordnik-api.sh create mode 100755 bin/python-petstore.sh create mode 100755 bin/python-wordnik-api.sh create mode 100755 bin/python3-petstore.sh create mode 100755 bin/python3-wordnik-api.sh create mode 100755 bin/ruby-petstore.sh create mode 100755 bin/runscala.sh create mode 100755 bin/scala-async.sh create mode 100755 bin/scala-petstore.sh create mode 100755 bin/scala-wordnik-api.sh create mode 100755 bin/static-docs.sh create mode 100755 bin/update-spec.sh create mode 100755 bin/validate.sh diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh new file mode 100755 index 000000000000..716db5bae155 --- /dev/null +++ b/bin/all-petstore.sh @@ -0,0 +1,37 @@ +#!/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/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/java-petstore.sh +./bin/objc-petstore.sh +./bin/php-petstore.sh +./bin/python-petstore.sh +./bin/python3-petstore.sh +./bin/ruby-petstore.sh +./bin/scala-petstore.sh diff --git a/bin/android-java-petstore.sh b/bin/android-java-petstore.sh new file mode 100755 index 000000000000..edde6205216f --- /dev/null +++ b/bin/android-java-petstore.sh @@ -0,0 +1,32 @@ +#!/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="$@ samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.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 $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/android-java-wordnik-api.sh b/bin/android-java-wordnik-api.sh new file mode 100755 index 000000000000..aba96fb90968 --- /dev/null +++ b/bin/android-java-wordnik-api.sh @@ -0,0 +1,32 @@ +#!/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/android-java/AndroidJavaPetstoreCodegen.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/csharp-petstore.sh b/bin/csharp-petstore.sh new file mode 100755 index 000000000000..0b38c046ce01 --- /dev/null +++ b/bin/csharp-petstore.sh @@ -0,0 +1,32 @@ +#!/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/flash-petstore.sh b/bin/flash-petstore.sh new file mode 100755 index 000000000000..37a591a9554e --- /dev/null +++ b/bin/flash-petstore.sh @@ -0,0 +1,32 @@ +#!/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/java-petstore.sh b/bin/java-petstore.sh new file mode 100755 index 000000000000..e895b18ee94d --- /dev/null +++ b/bin/java-petstore.sh @@ -0,0 +1,27 @@ +#!/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 + + +# 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.Codegen -i http://petstore.swagger.wordnik.com/v2/swagger.json -l java" + +java -cp $APP_DIR/target/*:$APP_DIR/target/lib/* $ags diff --git a/bin/java-wordnik-api.sh b/bin/java-wordnik-api.sh new file mode 100755 index 000000000000..c1888f07fb02 --- /dev/null +++ b/bin/java-wordnik-api.sh @@ -0,0 +1,26 @@ +#!/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 + +# 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.Codegen -i src/test/resources/wordnik.json -l java" + +java -cp $APP_DIR/target/*:$APP_DIR/target/lib/* $ags diff --git a/bin/php-petstore.sh b/bin/php-petstore.sh new file mode 100755 index 000000000000..07887a0775ce --- /dev/null +++ b/bin/php-petstore.sh @@ -0,0 +1,32 @@ +#!/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/php/PHPPetstoreCodegen.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/php-wordnik-api.sh b/bin/php-wordnik-api.sh new file mode 100755 index 000000000000..d03bfe04990f --- /dev/null +++ b/bin/php-wordnik-api.sh @@ -0,0 +1,32 @@ +#!/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 new file mode 100755 index 000000000000..370b7f429808 --- /dev/null +++ b/bin/python-petstore.sh @@ -0,0 +1,32 @@ +#!/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/python/PythonPetstoreCodegen.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/python-wordnik-api.sh b/bin/python-wordnik-api.sh new file mode 100755 index 000000000000..3af48e9675cc --- /dev/null +++ b/bin/python-wordnik-api.sh @@ -0,0 +1,32 @@ +#!/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 new file mode 100755 index 000000000000..a9fb758d9b7f --- /dev/null +++ b/bin/python3-petstore.sh @@ -0,0 +1,32 @@ +#!/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 new file mode 100755 index 000000000000..77ae679bcf95 --- /dev/null +++ b/bin/python3-wordnik-api.sh @@ -0,0 +1,32 @@ +#!/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 new file mode 100755 index 000000000000..a0f3fb742760 --- /dev/null +++ b/bin/ruby-petstore.sh @@ -0,0 +1,32 @@ +#!/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 new file mode 100755 index 000000000000..7e8572a6c5aa --- /dev/null +++ b/bin/runscala.sh @@ -0,0 +1,32 @@ +#!/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.sh b/bin/scala-async.sh new file mode 100755 index 000000000000..d9618767a20f --- /dev/null +++ b/bin/scala-async.sh @@ -0,0 +1,31 @@ +#!/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 new file mode 100755 index 000000000000..bb5a9b2afee7 --- /dev/null +++ b/bin/scala-petstore.sh @@ -0,0 +1,32 @@ +#!/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/scala/ScalaPetstoreCodegen.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/scala-wordnik-api.sh b/bin/scala-wordnik-api.sh new file mode 100755 index 000000000000..2c1703507b24 --- /dev/null +++ b/bin/scala-wordnik-api.sh @@ -0,0 +1,32 @@ +#!/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/scala/ScalaWordnikApiCodegen.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/static-docs.sh b/bin/static-docs.sh new file mode 100755 index 000000000000..af769fa79a8c --- /dev/null +++ b/bin/static-docs.sh @@ -0,0 +1,32 @@ +#!/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/update-spec.sh b/bin/update-spec.sh new file mode 100755 index 000000000000..5f5ea4ba78da --- /dev/null +++ b/bin/update-spec.sh @@ -0,0 +1,31 @@ +#!/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 new file mode 100755 index 000000000000..efa4a6cee83e --- /dev/null +++ b/bin/validate.sh @@ -0,0 +1,31 @@ +#!/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 From 5bc907f1d430e16ea2aa86bc7383ef62b92cc6cb Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 23 Sep 2014 09:14:25 -0700 Subject: [PATCH 031/325] added template variable --- .../com/wordnik/swagger/codegen/Codegen.java | 17 ++++++++++++++--- .../wordnik/swagger/codegen/CodegenConfig.java | 1 + .../wordnik/swagger/codegen/DefaultCodegen.java | 10 +++++++--- .../swagger/codegen/DefaultGenerator.java | 1 + 4 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index 17ab91180620..9fdc52a749c5 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -14,6 +14,7 @@ public class Codegen extends DefaultGenerator { options.addOption("l", "lang", true, "client language to generate"); 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"); ClientOptInput codegenInput = new ClientOptInput(); ClientOpts clientArgs = new ClientOpts(); @@ -29,10 +30,16 @@ public class Codegen extends DefaultGenerator { codegenInput.getConfig().setOutputDir(cmd.getOptionValue("o")); if (cmd.hasOption("i")) swagger = new SwaggerLoader().read(cmd.getOptionValue("i")); - + if (cmd.hasOption("t")) + clientArgs.getProperties().put("templateDir", + String.valueOf(cmd.getOptionValue("t"))); + if (cmd.hasOption("h")) { + usage(options); + return; + } } catch (Exception e) { - e.printStackTrace(); + usage(options); return; } @@ -40,7 +47,6 @@ public class Codegen extends DefaultGenerator { codegenInput .opts(clientArgs) .swagger(swagger); - new Codegen().opts(codegenInput).generate(); } catch (Exception e) { @@ -48,6 +54,11 @@ public class Codegen extends DefaultGenerator { } } + static void usage(Options options) { + HelpFormatter formatter = new HelpFormatter(); + formatter.printHelp( "Codegen", options ); + } + static CodegenConfig getConfig(String name) { if("objc".equals(name)) return new ObjcClientCodegen(); diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java index 808b893913a6..5bb8e2e9e3f7 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -20,6 +20,7 @@ public interface CodegenConfig { String escapeReservedWord(String name); String getTypeDeclaration(Property p); String getTypeDeclaration(String name); + void processOpts(); Set reservedWords(); diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index d616cafd943a..329ffb9d941c 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -22,6 +22,12 @@ public class DefaultCodegen { 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; @@ -214,10 +220,8 @@ public class DefaultCodegen { String inner = getSwaggerType(ap.getItems()); return "new ArrayList<" + inner + ">() "; } - else { - // System.out.println("unhandled property default value"); + else return "null"; - } } /** diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 6c5a1e76a73b..04b8ea802418 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -32,6 +32,7 @@ public class DefaultGenerator implements Generator { throw new RuntimeException("missing swagger input or config!"); } try { + config.processOpts(); Map models = null; Map operations = null; From ba94dc3d68db13a29d53b483306c0fcb61c90c10 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 23 Sep 2014 21:44:09 -0700 Subject: [PATCH 032/325] added subclass for ArrayModel support #273, removed path param brackets for auto-generated operationId #274 --- .../com/wordnik/swagger/codegen/Codegen.java | 1 - .../wordnik/swagger/codegen/CodegenModel.java | 1 + .../swagger/codegen/CodegenProperty.java | 2 +- .../swagger/codegen/DefaultCodegen.java | 42 +++++++++++++++---- .../swagger/codegen/DefaultGenerator.java | 12 +++--- src/main/resources/JavaJaxRS/model.mustache | 3 +- 6 files changed, 44 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index 9fdc52a749c5..96872fb2efee 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -42,7 +42,6 @@ public class Codegen extends DefaultGenerator { usage(options); return; } - try{ codegenInput .opts(clientArgs) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index b774ea5450eb..4cd6c74dd9e2 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -6,6 +6,7 @@ import com.wordnik.swagger.models.properties.*; import java.util.*; class CodegenModel { + public String parent; public String name, classname, description; public String defaultValue; public List vars = new ArrayList(); diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java index e1ff535362f7..ecc2008c5be3 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java @@ -7,7 +7,7 @@ import java.util.*; public class CodegenProperty { public String baseName, complexType, getter, setter, description, datatype, - name, min, max, defaultValue, baseType; + name, min, max, defaultValue, baseType, containerType; public Double minimum, maximum, exclusiveMinimum, exclusiveMaximum; public Boolean hasMore = null, required = null, secondaryParam = null; public Boolean isPrimitiveType, isContainer, isNotContainer; diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 329ffb9d941c..0f867e91149b 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -12,6 +12,7 @@ public class DefaultCodegen { 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(); @@ -153,7 +154,6 @@ public class DefaultCodegen { ); typeMapping = new HashMap(); - typeMapping.put("Array", "List"); typeMapping.put("array", "List"); typeMapping.put("List", "List"); typeMapping.put("boolean", "Boolean"); @@ -169,6 +169,9 @@ public class DefaultCodegen { typeMapping.put("object", "Object"); typeMapping.put("integer", "Integer"); + instantiationTypes = new HashMap(); + instantiationTypes.put("array", "ArrayList"); + reservedWords = new HashSet ( Arrays.asList( "abstract", "continue", "for", "new", "switch", "assert", @@ -196,6 +199,21 @@ public class DefaultCodegen { 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 "HashMap"; + } + else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "ArrayList<" + inner + ">"; + } + else + return null; + } + public String toDefaultValue(Property p) { if(p instanceof StringProperty) return "null"; @@ -290,16 +308,24 @@ public class DefaultCodegen { m.name = name; m.description = model.getDescription(); m.classname = toModelName(name); - int count = 0; if(model instanceof ArrayModel) { ArrayModel am = (ArrayModel) model; ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); CodegenProperty cp = fromProperty(name, arrayProperty); - m.vars.add(cp); + // m.vars.add(cp); + if(cp.complexType != null && !defaultIncludes.contains(cp.complexType)) + m.imports.add(cp.complexType); + m.parent = cp.baseType; + String containerType = cp.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; @@ -389,9 +415,11 @@ public class DefaultCodegen { if(p instanceof ArrayProperty) { property.isContainer = true; + property.containerType = "array"; ArrayProperty ap = (ArrayProperty) p; CodegenProperty cp = fromProperty("inner", ap.getItems()); - property.baseType = cp.baseType; + + property.baseType = toInstantiationType(p); if(!languageSpecificPrimitives.contains(cp.baseType)) property.complexType = cp.baseType; } @@ -409,7 +437,8 @@ public class DefaultCodegen { String operationId = operation.getOperationId(); if(operationId == null) { - operationId = path.replaceAll("/", "") + "_" + httpMethod; + path = path.replaceAll("\\{", ""); + path = path.replaceAll("\\}", ""); String[] parts = (path + "/" + httpMethod).split("/"); StringBuilder builder = new StringBuilder(); for(int i = 0; i < parts.length; i++) { @@ -596,7 +625,6 @@ public class DefaultCodegen { name = getTypeDeclaration(name); } p.dataType = name; - } } p.paramName = toParamName(bp.getName()); diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 04b8ea802418..8c08ad288ef7 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -247,13 +247,11 @@ public class DefaultGenerator implements Generator { Set allImports = new HashSet(); for(String key: definitions.keySet()) { Model mm = definitions.get(key); - if(mm instanceof ModelImpl) { - CodegenModel cm = config.fromModel(key, (ModelImpl) mm); - Map mo = new HashMap(); - mo.put("model", cm); - models.add(mo); - allImports.addAll(cm.imports); - } + 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); diff --git a/src/main/resources/JavaJaxRS/model.mustache b/src/main/resources/JavaJaxRS/model.mustache index 938daf4d5f67..49406020a0ba 100644 --- a/src/main/resources/JavaJaxRS/model.mustache +++ b/src/main/resources/JavaJaxRS/model.mustache @@ -8,7 +8,7 @@ package {{package}}; /** * {{description}} **/{{/description}} -public class {{classname}} { {{#vars}} +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}} /**{{#description}} * {{{description}}}{{/description}} * required: {{required}}{{#minimum}} @@ -33,6 +33,7 @@ public class {{classname}} { {{#vars}} 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(); From 2dd73872a449927411b2b844733dd187ecfa851d Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 26 Sep 2014 09:38:07 -0700 Subject: [PATCH 033/325] updated with tests --- bin/android-java-petstore.sh | 9 +- bin/java-petstore-filemap.sh | 2 +- bin/java-petstore.sh | 2 +- bin/objc-petstore.sh | 2 +- samples/client/petstore/android-java/pom.xml | 5 +- samples/client/petstore/java/pom.xml | 5 +- samples/client/petstore/objc/Podfile | 3 +- .../client/petstore/objc/client/SWGCategory.h | 8 +- .../client/petstore/objc/client/SWGCategory.m | 26 +- .../client/petstore/objc/client/SWGOrder.h | 29 +- .../client/petstore/objc/client/SWGOrder.m | 70 +- samples/client/petstore/objc/client/SWGPet.h | 30 +- samples/client/petstore/objc/client/SWGPet.m | 74 +- .../client/petstore/objc/client/SWGPetApi.h | 103 ++- .../client/petstore/objc/client/SWGPetApi.m | 640 +++++++----------- .../client/petstore/objc/client/SWGStoreApi.h | 41 +- .../client/petstore/objc/client/SWGStoreApi.m | 255 +++---- samples/client/petstore/objc/client/SWGTag.h | 8 +- samples/client/petstore/objc/client/SWGTag.m | 26 +- samples/client/petstore/objc/client/SWGUser.h | 36 +- samples/client/petstore/objc/client/SWGUser.m | 70 +- .../client/petstore/objc/client/SWGUserApi.h | 108 +-- .../client/petstore/objc/client/SWGUserApi.m | 503 +++++++------- .../com/wordnik/swagger/codegen/Codegen.java | 2 + .../wordnik/swagger/codegen/CodegenModel.java | 2 +- .../swagger/codegen/DefaultCodegen.java | 43 +- .../codegen/languages/JavaClientCodegen.java | 5 +- .../codegen/languages/ObjcClientCodegen.java | 12 +- src/main/resources/JavaJaxRS/model.mustache | 10 +- src/main/resources/objc/model-body.mustache | 3 +- 30 files changed, 981 insertions(+), 1151 deletions(-) diff --git a/bin/android-java-petstore.sh b/bin/android-java-petstore.sh index edde6205216f..312953e7d813 100755 --- a/bin/android-java-petstore.sh +++ b/bin/android-java-petstore.sh @@ -18,15 +18,10 @@ if [ ! -d "${APP_DIR}" ]; then 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="$@ samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" +ags="$@ com.wordnik.swagger.codegen.Codegen -i src/test/resources/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 -cp $APP_DIR/target/*:$APP_DIR/target/lib/* $ags diff --git a/bin/java-petstore-filemap.sh b/bin/java-petstore-filemap.sh index bedec4ab2c7f..fbe0f86c2105 100755 --- a/bin/java-petstore-filemap.sh +++ b/bin/java-petstore-filemap.sh @@ -21,6 +21,6 @@ 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.Codegen -i src/test/resources/petstore.json -l java" +ags="$@ com.wordnik.swagger.codegen.Codegen -i src/test/resources/petstore.json -l java -o samples/client/petstore/java" java -cp $APP_DIR/target/*:$APP_DIR/target/lib/* $ags diff --git a/bin/java-petstore.sh b/bin/java-petstore.sh index e895b18ee94d..69c1faf9e6eb 100755 --- a/bin/java-petstore.sh +++ b/bin/java-petstore.sh @@ -22,6 +22,6 @@ 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.Codegen -i http://petstore.swagger.wordnik.com/v2/swagger.json -l java" +ags="$@ com.wordnik.swagger.codegen.Codegen -i http://petstore.swagger.wordnik.com/v2/swagger.json -l java -o samples/client/petstore/java" java -cp $APP_DIR/target/*:$APP_DIR/target/lib/* $ags diff --git a/bin/objc-petstore.sh b/bin/objc-petstore.sh index 683b1a8371dc..164eb72f11e6 100755 --- a/bin/objc-petstore.sh +++ b/bin/objc-petstore.sh @@ -21,6 +21,6 @@ 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.Codegen -i src/test/resources/petstore.json -l objc" +ags="$@ com.wordnik.swagger.codegen.Codegen -i src/test/resources/petstore.json -l objc -o samples/client/petstore/objc" java -cp $APP_DIR/target/*:$APP_DIR/target/lib/* $ags diff --git a/samples/client/petstore/android-java/pom.xml b/samples/client/petstore/android-java/pom.xml index 8415a2b66cfe..2e7f6d8c612d 100644 --- a/samples/client/petstore/android-java/pom.xml +++ b/samples/client/petstore/android-java/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 - swagger-petstore + swagger-client jar - swagger-petstore + swagger-client 1.0.0 scm:git:git@github.com:wordnik/swagger-mustache.git @@ -149,4 +149,3 @@ 4.0 - diff --git a/samples/client/petstore/java/pom.xml b/samples/client/petstore/java/pom.xml index 2f685c3927b8..4561705d08dc 100644 --- a/samples/client/petstore/java/pom.xml +++ b/samples/client/petstore/java/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 - swagger-petstore + swagger-client jar - swagger-petstore + swagger-client 1.0.0 scm:git:git@github.com:wordnik/swagger-mustache.git @@ -167,4 +167,3 @@ 4.8.1 - diff --git a/samples/client/petstore/objc/Podfile b/samples/client/petstore/objc/Podfile index 36e97d70a75d..0db992d7436f 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' +xcodeproj '/.xcodeproj' pod 'AFNetworking', '~> 1.0' - diff --git a/samples/client/petstore/objc/client/SWGCategory.h b/samples/client/petstore/objc/client/SWGCategory.h index 7443279dc278..474f70c37c4c 100644 --- a/samples/client/petstore/objc/client/SWGCategory.h +++ b/samples/client/petstore/objc/client/SWGCategory.h @@ -5,15 +5,13 @@ @interface SWGCategory : SWGObject @property(nonatomic) NSNumber* _id; - @property(nonatomic) NSString* name; - - (id) _id: (NSNumber*) _id - name: (NSString*) name; + + 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..8e1ab7845a67 100644 --- a/samples/client/petstore/objc/client/SWGCategory.m +++ b/samples/client/petstore/objc/client/SWGCategory.m @@ -4,32 +4,34 @@ @implementation SWGCategory -(id)_id: (NSNumber*) _id - name: (NSString*) name -{ - __id = _id; - _name = name; - return self; + name: (NSString*) name { + + __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"] = [(SWGObject*)__id asDictionary]; + if(_name != nil) + dict[@"name"] = [(SWGObject*)_name asDictionary]; + + NSDictionary* output = [dict copy]; return output; } @end - diff --git a/samples/client/petstore/objc/client/SWGOrder.h b/samples/client/petstore/objc/client/SWGOrder.h index c1486966e244..b356595f828e 100644 --- a/samples/client/petstore/objc/client/SWGOrder.h +++ b/samples/client/petstore/objc/client/SWGOrder.h @@ -1,29 +1,34 @@ #import #import "SWGObject.h" #import "SWGDate.h" +#import "SWGMap.h" @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; - +@property(nonatomic) NSString* status; +@property(nonatomic) NSNumber* complete; +@property(nonatomic) SWGMap* keyValuePairs; - (id) _id: (NSNumber*) _id - petId: (NSNumber*) petId - quantity: (NSNumber*) quantity - status: (NSString*) status - shipDate: (SWGDate*) shipDate; + + petId: (NSNumber*) petId + + quantity: (NSNumber*) quantity + + shipDate: (SWGDate*) shipDate + + status: (NSString*) status + + complete: (NSNumber*) complete + + keyValuePairs: (SWGMap*) keyValuePairs; + - (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..ca9ede3c98b2 100644 --- a/samples/client/petstore/objc/client/SWGOrder.m +++ b/samples/client/petstore/objc/client/SWGOrder.m @@ -6,61 +6,53 @@ -(id)_id: (NSNumber*) _id petId: (NSNumber*) petId quantity: (NSNumber*) quantity - status: (NSString*) status shipDate: (SWGDate*) shipDate -{ - __id = _id; - _petId = petId; - _quantity = quantity; - _status = status; - _shipDate = shipDate; - return self; + status: (NSString*) status + complete: (NSNumber*) complete + keyValuePairs: (SWGMap*) keyValuePairs { + + __id = _id; + _petId = petId; + _quantity = quantity; + _shipDate = shipDate; + _status = status; + _complete = complete; + _keyValuePairs = keyValuePairs; + + 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"]; + + _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([_shipDate isKindOfClass:[NSArray class]]){ - NSMutableArray * array = [[NSMutableArray alloc] init]; - for( SWGDate *shipDate in (NSArray*)_shipDate) { - [array addObject:[(SWGObject*)shipDate asDictionary]]; - } - dict[@"shipDate"] = array; - } - else if(_shipDate && [_shipDate isKindOfClass:[SWGDate class]]) { - NSString * dateString = [(SWGDate*)_shipDate toString]; - if(dateString){ - dict[@"shipDate"] = dateString; - } - } - else { - if(_shipDate != nil) dict[@"shipDate"] = [(SWGObject*)_shipDate asDictionary]; - } - } + if(__id != nil) + dict[@"id"] = [(SWGObject*)__id asDictionary]; + if(_petId != nil) + dict[@"petId"] = [(SWGObject*)_petId asDictionary]; + if(_quantity != nil) + dict[@"quantity"] = [(SWGObject*)_quantity asDictionary]; + if(_status != nil) + dict[@"status"] = [(SWGObject*)_status asDictionary]; + if(_complete != nil) + dict[@"complete"] = [(SWGObject*)_complete asDictionary]; + 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..9143a1e2b411 100644 --- a/samples/client/petstore/objc/client/SWGPet.h +++ b/samples/client/petstore/objc/client/SWGPet.h @@ -1,33 +1,31 @@ #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; /* the identifier for the pet */ @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]*/ - +@property(nonatomic) NSString* status; - (id) _id: (NSNumber*) _id - category: (SWGCategory*) category - name: (NSString*) name - photoUrls: (NSArray*) photoUrls - tags: (NSArray*) tags - status: (NSString*) status; + + 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..c49eb99937b4 100644 --- a/samples/client/petstore/objc/client/SWGPet.m +++ b/samples/client/petstore/objc/client/SWGPet.m @@ -8,35 +8,35 @@ name: (NSString*) name photoUrls: (NSArray*) photoUrls tags: (NSArray*) tags - status: (NSString*) status -{ - __id = _id; - _category = category; - _name = name; - _photoUrls = photoUrls; - _tags = tags; - _status = status; - return self; + status: (NSString*) status { + + __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 category_dict = dict[@"category"]; - if(category_dict != nil) - _category = [[SWGCategory alloc]initWithValues:category_dict]; - _name = dict[@"name"]; - _photoUrls = dict[@"photoUrls"]; + __id = dict[@"id"]; + + _name = dict[@"name"]; + + + 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]; + SWGTag* d = [[SWGTag alloc] initWithValues:dict]; [objs addObject:d]; } @@ -49,37 +49,20 @@ 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([_category isKindOfClass:[NSArray class]]){ - NSMutableArray * array = [[NSMutableArray alloc] init]; - for( SWGCategory *category in (NSArray*)_category) { - [array addObject:[(SWGObject*)category asDictionary]]; - } - dict[@"category"] = array; - } - else if(_category && [_category isKindOfClass:[SWGDate class]]) { - NSString * dateString = [(SWGDate*)_category toString]; - if(dateString){ - dict[@"category"] = dateString; - } - } - else { - if(_category != nil) dict[@"category"] = [(SWGObject*)_category asDictionary]; - } - } - if(_name != nil) dict[@"name"] = _name ; - if(_photoUrls != nil) dict[@"photoUrls"] = _photoUrls ; - if(_tags != nil){ + if(__id != nil) + dict[@"id"] = [(SWGObject*)__id asDictionary]; + if(_name != nil) + dict[@"name"] = [(SWGObject*)_name asDictionary]; + if(_tags != nil){ if([_tags isKindOfClass:[NSArray class]]){ NSMutableArray * array = [[NSMutableArray alloc] init]; for( SWGTag *tags in (NSArray*)_tags) { @@ -94,13 +77,14 @@ } } 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"] = [(SWGObject*)_status asDictionary]; + + 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..66baf5541824 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.h +++ b/samples/client/petstore/objc/client/SWGPetApi.h @@ -1,7 +1,5 @@ #import #import "SWGPet.h" -#import "SWGFile.h" - @interface SWGPetApi: NSObject @@ -13,91 +11,68 @@ +(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 - */ --(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 - */ --(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body - 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; +-(NSNumber*) addPetWithCompletionBlock : (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 + */ --(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 + + */ +-(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 + + */ +-(NSNumber*) getPetByIdWithCompletionBlock : (NSNumber*) petId + completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock; + +/** + + Deletes a pet + + + @param petId Pet id to delete + + */ +-(NSNumber*) deletePetWithCompletionBlock : (NSNumber*) petId + + 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..82bc422801b2 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -2,13 +2,11 @@ #import "SWGFile.h" #import "SWGApiClient.h" #import "SWGPet.h" -#import "SWGFile.h" - @implementation SWGPetApi -static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; +static NSString * basePath = @""; +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static SWGPetApi* singletonAPI = nil; @@ -52,281 +50,9 @@ 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,121 +60,29 @@ 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* 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(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); - }]; -} - --(NSNumber*) updatePetWithCompletionBlock:(SWGPet*) body - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", 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* 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); - } + + + id bodyDictionary = nil; + + + - if(body == nil) { - // error - } SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + + return [client stringWithCompletionBlock:requestUrl method:@"PUT" queryParams:queryParams @@ -464,11 +98,65 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; completionBlock(nil); }]; + } --(NSNumber*) findPetsByStatusWithCompletionBlock:(NSString*) status - completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock{ +-(NSNumber*) addPetWithCompletionBlock:(SWGPet*) body + + completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", 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:@"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:(NSArray*) status + completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock + { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByStatus", basePath]; @@ -476,19 +164,25 @@ 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 @@ -498,24 +192,36 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; responseContentType: responseContentType completionBlock: ^(NSDictionary *data, NSError *error) { if (error) { - completionBlock(nil, error);return; + 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]; + + + SWGPet* d = [[SWGPet alloc]initWithValues: dict]; + [objs addObject:d]; } completionBlock(objs, nil); } - }]; + + + + }]; + + } --(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,19 +229,25 @@ 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 @@ -545,22 +257,144 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; responseContentType: responseContentType completionBlock: ^(NSDictionary *data, NSError *error) { if (error) { - completionBlock(nil, error);return; + 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]; + + + SWGPet* d = [[SWGPet alloc]initWithValues: dict]; + [objs addObject:d]; } completionBlock(objs, nil); } - }]; + + + + }]; + + + + +} + +-(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; + + + + + 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:(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]; + + + id bodyDictionary = nil; + + + + + 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); + }]; + } -@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..c9539c9964e0 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.h +++ b/samples/client/petstore/objc/client/SWGStoreApi.h @@ -2,7 +2,6 @@ #import "SWGOrder.h" - @interface SWGStoreApi: NSObject -(void) addHeader:(NSString*)value forKey:(NSString*)key; @@ -12,29 +11,35 @@ +(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 + Place an order for a pet + + + @param body order placed for purchasing the pet + */ --(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId - completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; +-(NSNumber*) placeOrderWithCompletionBlock : (SWGOrder*) body + + completionHandler: (void (^)(NSError* error))completionBlock; +/** + + 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 + + */ +-(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 + 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 - */ --(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId - completionHandler: (void (^)(NSError* error))completionBlock; - -/** - - Place an order for a pet - @param body order placed for purchasing the pet */ --(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body - completionHandler: (void (^)(NSError* error))completionBlock; +-(NSNumber*) deleteOrderWithCompletionBlock : (NSString*) orderId -@end + 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..eb1ce893d447 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 = @""; +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static SWGStoreApi* singletonAPI = nil; @@ -51,88 +50,9 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; } --(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; - 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]; - - 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*) placeOrderWithCompletionBlock:(SWGOrder*) body - completionHandler: (void (^)(NSError* error))completionBlock{ +-(NSNumber*) placeOrderWithCompletionBlock:(SWGOrder*) body + + completionHandler: (void (^)(NSError* error))completionBlock { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath]; @@ -140,50 +60,29 @@ 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]]){ - 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); - } + + + id bodyDictionary = nil; + + + - if(body == nil) { - // error - } SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + + return [client stringWithCompletionBlock:requestUrl method:@"POST" queryParams:queryParams @@ -199,9 +98,121 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; completionBlock(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; + + + + + 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; + + + + + 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); + }]; + + } -@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..7936df1f6701 100644 --- a/samples/client/petstore/objc/client/SWGTag.h +++ b/samples/client/petstore/objc/client/SWGTag.h @@ -5,15 +5,13 @@ @interface SWGTag : SWGObject @property(nonatomic) NSNumber* _id; - @property(nonatomic) NSString* name; - - (id) _id: (NSNumber*) _id - name: (NSString*) name; + + 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..115e712c0fb7 100644 --- a/samples/client/petstore/objc/client/SWGTag.m +++ b/samples/client/petstore/objc/client/SWGTag.m @@ -4,32 +4,34 @@ @implementation SWGTag -(id)_id: (NSNumber*) _id - name: (NSString*) name -{ - __id = _id; - _name = name; - return self; + name: (NSString*) name { + + __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"] = [(SWGObject*)__id asDictionary]; + if(_name != nil) + dict[@"name"] = [(SWGObject*)_name asDictionary]; + + 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..bd19dc2077cb 100644 --- a/samples/client/petstore/objc/client/SWGUser.h +++ b/samples/client/petstore/objc/client/SWGUser.h @@ -5,33 +5,31 @@ @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]*/ - +@property(nonatomic) NSNumber* userStatus; - (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; + + 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..947d43a31d95 100644 --- a/samples/client/petstore/objc/client/SWGUser.m +++ b/samples/client/petstore/objc/client/SWGUser.m @@ -4,56 +4,64 @@ @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; + userStatus: (NSNumber*) userStatus { + + __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"] = [(SWGObject*)__id asDictionary]; + if(_username != nil) + dict[@"username"] = [(SWGObject*)_username asDictionary]; + if(_firstName != nil) + dict[@"firstName"] = [(SWGObject*)_firstName asDictionary]; + if(_lastName != nil) + dict[@"lastName"] = [(SWGObject*)_lastName asDictionary]; + if(_email != nil) + dict[@"email"] = [(SWGObject*)_email asDictionary]; + if(_password != nil) + dict[@"password"] = [(SWGObject*)_password asDictionary]; + if(_phone != nil) + dict[@"phone"] = [(SWGObject*)_phone asDictionary]; + if(_userStatus != nil) + dict[@"userStatus"] = [(SWGObject*)_userStatus asDictionary]; + + 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..b2a2f8d2a7bf 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.h +++ b/samples/client/petstore/objc/client/SWGUserApi.h @@ -2,7 +2,6 @@ #import "SWGUser.h" - @interface SWGUserApi: NSObject -(void) addHeader:(NSString*)value forKey:(NSString*)key; @@ -12,76 +11,93 @@ +(NSString*) getBasePath; /** - Updated user + Create 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 body Created user object - @param username The name that needs to be fetched. Use user1 for testing. */ --(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username - completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock; +-(NSNumber*) createUserWithCompletionBlock : (SWGUser*) body + completionHandler: (void (^)(NSError* error))completionBlock; +/** + + Creates list of users with given input array + + + @param body List of user object + + */ +-(NSNumber*) createUsersWithArrayInputWithCompletionBlock : (NSArray*) body + + completionHandler: (void (^)(NSError* error))completionBlock; +/** + + Creates list of users with given input array + + + @param body List of user object + + */ +-(NSNumber*) createUsersWithListInputWithCompletionBlock : (NSArray*) body + + completionHandler: (void (^)(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; +-(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; +-(NSNumber*) logoutUserWithCompletionBlock : + +(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; /** - Create user + Updated user This can only be done by the logged in user. - @param body Created user object - */ --(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body - completionHandler: (void (^)(NSError* error))completionBlock; + @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; /** - Creates list of users with given input array + Delete user + This can only be done by the logged in user. + + @param username The name that needs to be deleted - @param body List of user object */ --(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray*) body - completionHandler: (void (^)(NSError* error))completionBlock; +-(NSNumber*) deleteUserWithCompletionBlock : (NSString*) username -/** - - Creates list of users with given list input - - @param body List of user object - */ --(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray*) body - completionHandler: (void (^)(NSError* error))completionBlock; - -@end + 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..531532a54dcb 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 = @""; +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static SWGUserApi* singletonAPI = nil; @@ -51,66 +50,41 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; } --(NSNumber*) updateUserWithCompletionBlock:(NSString*) username - body:(SWGUser*) body - completionHandler: (void (^)(NSError* error))completionBlock{ +-(NSNumber*) createUserWithCompletionBlock:(SWGUser*) body + + completionHandler: (void (^)(NSError* error))completionBlock { - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user", 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* 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); - } + + + id bodyDictionary = nil; + + + - if(username == nil) { - // error - } - if(body == nil) { - // error - } SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + + return [client stringWithCompletionBlock:requestUrl - method:@"PUT" + method:@"POST" queryParams:queryParams body:bodyDictionary headerParams:headerParams @@ -124,32 +98,45 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; completionBlock(nil); }]; + } --(NSNumber*) deleteUserWithCompletionBlock:(NSString*) username - completionHandler: (void (^)(NSError* error))completionBlock{ +-(NSNumber*) createUsersWithArrayInputWithCompletionBlock:(NSArray*) body + + completionHandler: (void (^)(NSError* error))completionBlock { - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithArray", 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* 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" + method:@"POST" queryParams:queryParams body:bodyDictionary headerParams:headerParams @@ -163,53 +150,66 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; completionBlock(nil); }]; + } --(NSNumber*) getUserByNameWithCompletionBlock:(NSString*) username - completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock{ +-(NSNumber*) createUsersWithListInputWithCompletionBlock:(NSArray*) body + + completionHandler: (void (^)(NSError* error))completionBlock { - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithList", 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* 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) { + + + + + + + return [client stringWithCompletionBlock:requestUrl + method:@"POST" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { if (error) { - completionBlock(nil, error);return; + completionBlock(error); + return; } - SWGUser *result = nil; - if (data) { - result = [[SWGUser alloc]initWithValues: data]; - } - completionBlock(result , nil);}]; + completionBlock(nil); + }]; + } --(NSNumber*) loginUserWithCompletionBlock:(NSString*) username - password:(NSString*) password - completionHandler: (void (^)(NSString* output, NSError* error))completionBlock{ +-(NSNumber*) loginUserWithCompletionBlock:(NSString*) username + password:(NSString*) password + completionHandler: (void (^)(NSString* output, NSError* error))completionBlock + { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/login", basePath]; @@ -217,44 +217,53 @@ 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(username != nil) - queryParams[@"username"] = username; - if(password != 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); - }]; + + + + + + 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{ +-(NSNumber*) logoutUserWithCompletionBlock: + + (void (^)(NSError* error))completionBlock { NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/logout", basePath]; @@ -262,14 +271,29 @@ 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; - SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + id bodyDictionary = nil; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + + + return [client stringWithCompletionBlock:requestUrl method:@"GET" queryParams:queryParams @@ -285,64 +309,105 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; completionBlock(nil); }]; + } --(NSNumber*) createUserWithCompletionBlock:(SWGUser*) body - completionHandler: (void (^)(NSError* error))completionBlock{ +-(NSNumber*) getUserByNameWithCompletionBlock:(NSString*) username + completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock + { - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user", basePath]; + 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* 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); - } + + + id bodyDictionary = nil; + + + - if(body == 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*) 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; + + + + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + + + return [client stringWithCompletionBlock:requestUrl - method:@"POST" + method:@"PUT" queryParams:queryParams body:bodyDictionary headerParams:headerParams @@ -356,64 +421,46 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; completionBlock(nil); }]; + } --(NSNumber*) createUsersWithArrayInputWithCompletionBlock:(NSArray*) body - completionHandler: (void (^)(NSError* error))completionBlock{ +-(NSNumber*) deleteUserWithCompletionBlock:(NSString*) username + + completionHandler: (void (^)(NSError* error))completionBlock { - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithArray", basePath]; + 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* 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); - } + + + id bodyDictionary = nil; + + + - if(body == nil) { - // error - } SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + + return [client stringWithCompletionBlock:requestUrl - method:@"POST" + method:@"DELETE" queryParams:queryParams body:bodyDictionary headerParams:headerParams @@ -427,80 +474,10 @@ static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; completionBlock(nil); }]; - -} - --(NSNumber*) createUsersWithListInputWithCompletionBlock:(NSArray*) body - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithList", 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); - } - - 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); - }]; } -@end +@end \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index 96872fb2efee..8d6282fa5662 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -61,6 +61,8 @@ public class Codegen extends DefaultGenerator { static CodegenConfig getConfig(String name) { if("objc".equals(name)) return new ObjcClientCodegen(); + else if("android".equals(name)) + return new AndroidClientCodegen(); else if("java".equals(name)) return new JavaClientCodegen(); else if("jaxrs".equals(name)) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index 4cd6c74dd9e2..7dcb491dda19 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -5,7 +5,7 @@ import com.wordnik.swagger.models.properties.*; import java.util.*; -class CodegenModel { +public class CodegenModel { public String parent; public String name, classname, description; public String defaultValue; diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 0f867e91149b..71aa90917c64 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -155,6 +155,7 @@ public class DefaultCodegen { typeMapping = new HashMap(); typeMapping.put("array", "List"); + typeMapping.put("map", "Map"); typeMapping.put("List", "List"); typeMapping.put("boolean", "Boolean"); typeMapping.put("string", "String"); @@ -189,8 +190,10 @@ public class DefaultCodegen { importMapping.put("File", "java.io.File"); importMapping.put("Date", "java.util.Date"); importMapping.put("Timestamp", "java.sql.Timestamp"); - importMapping.put("Array", "java.util.*"); - importMapping.put("ArrayList", "java.util.*"); + 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.*"); @@ -231,8 +234,11 @@ public class DefaultCodegen { return "null"; else if (p instanceof LongProperty) return "null"; - else if (p instanceof MapProperty) - 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()); @@ -329,13 +335,22 @@ public class DefaultCodegen { } else { ModelImpl impl = (ModelImpl) model; + // Json.prettyPrint(impl); for(String key: impl.getProperties().keySet()) { Property prop = impl.getProperties().get(key); + if(prop == null) { System.out.println("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); } @@ -363,7 +378,6 @@ public class DefaultCodegen { } } } - return m; } @@ -377,7 +391,6 @@ public class DefaultCodegen { property.setter = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); property.defaultValue = toDefaultValue(p); - property.required = p.getRequired(); String type = getSwaggerType(p); @@ -419,7 +432,17 @@ public class DefaultCodegen { ArrayProperty ap = (ArrayProperty) p; CodegenProperty cp = fromProperty("inner", ap.getItems()); - property.baseType = toInstantiationType(p); + property.baseType = getSwaggerType(p); + if(!languageSpecificPrimitives.contains(cp.baseType)) + property.complexType = cp.baseType; + } + 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; } @@ -606,10 +629,10 @@ public class DefaultCodegen { ArrayModel impl = (ArrayModel) model; CodegenModel cm = fromModel(bp.getName(), impl); // get the single property - CodegenProperty cp = fromProperty("inner", impl.getItems()); - + ArrayProperty ap = new ArrayProperty().items(impl.getItems()); + CodegenProperty cp = fromProperty("inner", ap); imports.add(cp.baseType); - p.dataType = getTypeDeclaration(typeMapping.get(impl.getType())); + p.dataType = cp.datatype; p.isContainer = true; } else{ diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 8ec271fad1e1..1bf0d5e92f80 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -69,7 +69,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; } else if (p instanceof MapProperty) { - throw new RuntimeException("not supported yet"); + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; } return super.getTypeDeclaration(p); } diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index 1182575c0938..79be19f80911 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -10,6 +10,7 @@ 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 ObjcClientCodegen() { super(); @@ -22,7 +23,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { modelPackage = ""; defaultIncludes = new HashSet( - Arrays.asList("bool", + Arrays.asList( + "bool", "int", "NSString", "NSObject", @@ -124,7 +126,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return Character.toUpperCase(type.charAt(0)) + type.substring(1); } else { - return "SWG" + Character.toUpperCase(type.charAt(0)) + type.substring(1); + return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1); } } @@ -149,16 +151,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String toModelFilename(String name) { - return "SWG" + initialCaps(name); + return PREFIX + initialCaps(name); } @Override public String toApiName(String name) { - return "SWG" + initialCaps(name) + "Api"; + return PREFIX + initialCaps(name) + "Api"; } public String toApiFilename(String name) { - return "SWG" + initialCaps(name) + "Api"; + return PREFIX + initialCaps(name) + "Api"; } @Override diff --git a/src/main/resources/JavaJaxRS/model.mustache b/src/main/resources/JavaJaxRS/model.mustache index 49406020a0ba..3836a0ad9273 100644 --- a/src/main/resources/JavaJaxRS/model.mustache +++ b/src/main/resources/JavaJaxRS/model.mustache @@ -2,16 +2,18 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} + +import com.wordnik.swagger.annotations.*; {{#models}} {{#model}}{{#description}} /** * {{description}} **/{{/description}} +@ApiModel(description = "{{{description}}}") public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}} /**{{#description}} - * {{{description}}}{{/description}} - * required: {{required}}{{#minimum}} + * {{{description}}}{{/description}}{{#minimum}} * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} **/ @@ -20,7 +22,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars} //{{^min}}public enum {{name}}Enum { {{#values}} {{.}}, {{/values}} }; {{/min}}{{/allowableValues}}{{/vars}} - {{#vars}}public {{{datatype}}} {{getter}}() { + {{#vars}} + @ApiModelProperty(required = {{required}}, value = "{{{description}}}") + public {{{datatype}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatype}}} {{name}}) { diff --git a/src/main/resources/objc/model-body.mustache b/src/main/resources/objc/model-body.mustache index 190d9bfc308d..4d739ed6473a 100644 --- a/src/main/resources/objc/model-body.mustache +++ b/src/main/resources/objc/model-body.mustache @@ -16,7 +16,8 @@ { self = [super init]; if(self) { - {{#vars}}{{#isPrimitiveType}}_{{name}} = dict[@"{{baseName}}"];{{/isPrimitiveType}}{{#complexType}} + {{#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]]; From eb6c09bfce0afaecb42d1fb4c561ba20ca2afd6c Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 26 Sep 2014 09:39:39 -0700 Subject: [PATCH 034/325] merged from #271 --- .../com/wordnik/swagger/codegen/CodegenProperty.java | 11 ++++++++--- .../com/wordnik/swagger/codegen/DefaultCodegen.java | 3 +++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java index ecc2008c5be3..8461310a298b 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java @@ -1,13 +1,18 @@ package com.wordnik.swagger.codegen; -import com.wordnik.swagger.models.*; -import com.wordnik.swagger.models.properties.*; - import java.util.*; public class CodegenProperty { public String baseName, complexType, getter, setter, description, datatype, 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; + public Double minimum, maximum, exclusiveMinimum, exclusiveMaximum; public Boolean hasMore = null, required = null, secondaryParam = null; public Boolean isPrimitiveType, isContainer, isNotContainer; diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 71aa90917c64..9a3999963f6b 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -412,6 +412,9 @@ public class DefaultCodegen { 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; From 64aa948445abb851a14bd2df7319372f53f5b009 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 26 Sep 2014 10:25:44 -0700 Subject: [PATCH 035/325] added android client --- .../languages/AndroidClientCodegen.java | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java new file mode 100644 index 000000000000..dd475d944b21 --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java @@ -0,0 +1,95 @@ +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 = "com.wordnik.api"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/java"; + + public AndroidClientCodegen() { + super(); + outputFolder = "generated-code/android"; + modelTemplateFiles.put("model.mustache", ".java"); + apiTemplateFiles.put("api.mustache", ".java"); + templateDir = "android-java"; + apiPackage = "com.wordnik.api"; + modelPackage = "com.wordnik.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") + ); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replaceAll("\\.", File.separator); + } + + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replaceAll("\\.", File.separator); + } + + @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 From 108880cbe95b8fe77f0059f870332a2a0a7954b7 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 26 Sep 2014 13:56:12 -0700 Subject: [PATCH 036/325] updated README --- README.md | 161 +++++++++++++----------------------------------------- 1 file changed, 38 insertions(+), 123 deletions(-) diff --git a/README.md b/README.md index 2fce1d7471f2..fb93a73c441b 100644 --- a/README.md +++ b/README.md @@ -3,8 +3,7 @@ [![Build Status](https://travis-ci.org/wordnik/swagger-codegen.png)](https://travis-ci.org/wordnik/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? @@ -43,86 +42,47 @@ mvn package You can build a client against Wordnik's [petstore](http://petstore.swagger.wordnik.com) 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/wordnik/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 -cp ./target/*:./target/lib/* com.wordnik.swagger.codegen.Codegen \ + -i http://petstore.swagger.wordnik.com/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 + -i,--input-spec location of the swagger spec, as URL or file + -l,--lang client language to generate + -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/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/wordnik/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 `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/wordnik/swagger.js)--it's completely dynamic and doesn't require @@ -135,7 +95,7 @@ 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 ./src/test/resources/petstore.json ``` Or for example: @@ -143,94 +103,49 @@ Or for example: ./bin/java-petstore-filemap.sh ``` -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. +Great for creating libraries on your ci server, from the [Swagger Editor](http://editor.swagger.wordnik.com)... or while coding on an airplane. ### 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-core](https://github.com/wordnik/swagger-core/wiki). 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: -``` -./bin/validate.sh http://petstore.swagger.wordnik.com/api/api-docs "specia-key" ./swagger-errors.html -``` +http://online.swagger.io/validator/debug?url=http://petstore.swagger.wordnik.com/v2/swagger.json ### 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. -``` -./bin/static-docs.sh -``` - -Will produce the output here: - -``` -https://github.com/wordnik/swagger-codegen/tree/master/samples/docs/swagger-static-docs -``` - -which is based on these templates: - -``` -https://github.com/wordnik/swagger-codegen/tree/master/src/main/resources/swagger-static -``` - -and looks like this - -![Image](https://raw.github.com/wordnik/swagger-codegen/master/samples/docs/swagger-static-docs/static-docs.png) +#### Not yet migrated to this branch ### To build a server stub You can also use the codegen to generate a server for a couple different frameworks. Take a look here: +#### Not yet migrated to this branch * [javascript node.js Server generator](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/node) +#### Not yet migrated to this branch * [ruby sinatra generator](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/sinatra) +#### Not yet migrated to this branch * [scala scalatra generator](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) -* [java jax-rs generator](https://github.com/wordnik/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/wordnik/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 -``` - -Will read the 1.1 spec from wordnik developer and write it into the folder called `wordnik-developer`. +* java jax-rs +To do so, just use the `-l jaxrs` flag when reading a spec file~ ### 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 Wordnik, Inc. +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. From 7006c2f6e96502ab16c578896a3ac1e73246082b Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 26 Sep 2014 13:59:07 -0700 Subject: [PATCH 037/325] updated README --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index fb93a73c441b..ed8244004ca8 100644 --- a/README.md +++ b/README.md @@ -119,18 +119,19 @@ http://online.swagger.io/validator/debug?url=http://petstore.swagger.wordnik.com You can also use the codegen to generate a server for a couple different frameworks. Take a look here: +### node.js #### Not yet migrated to this branch -* [javascript node.js Server generator](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/node) +### rails-grape #### Not yet migrated to this branch -* [ruby sinatra generator](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/sinatra) + +### scala scalatra #### Not yet migrated to this branch -* [scala scalatra generator](https://github.com/wordnik/swagger-codegen/tree/master/samples/server-generator/scalatra) -* java jax-rs +### java jax-rs -To do so, just use the `-l jaxrs` flag when reading a spec file~ +To do so, just use the `-l jaxrs` flag when reading a spec file ### To build the codegen library From f2b03d2930674ff6744ba9b05b355fde76393f35 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 26 Sep 2014 14:21:43 -0700 Subject: [PATCH 038/325] added test files --- README.md | 1 + src/test/resources/petstore.json | 722 ++++++++++++++++++++++++ src/test/scala/Java/JavaModelTest.scala | 209 +++++++ src/test/scala/Objc/ObjcModelTest.scala | 218 +++++++ 4 files changed, 1150 insertions(+) create mode 100644 src/test/resources/petstore.json create mode 100644 src/test/scala/Java/JavaModelTest.scala create mode 100644 src/test/scala/Objc/ObjcModelTest.scala diff --git a/README.md b/README.md index ed8244004ca8..6118d3e9852d 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ mvn package Other languages have petstore samples, too: ``` +./bin/android-petstore.sh ./bin/java-petstore.sh ./bin/objc-petstore.sh ``` diff --git a/src/test/resources/petstore.json b/src/test/resources/petstore.json new file mode 100644 index 000000000000..ae078d34351e --- /dev/null +++ b/src/test/resources/petstore.json @@ -0,0 +1,722 @@ +{ + "swagger": 2.0, + "info": { + "description": "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", + "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" + } + }, + "basePath": "/v2", + "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" + } + } + }, + "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" + } + } + } + }, + "/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": [ + { + "in": "query", + "name": "status", + "description": "Status values that need to be considered for filter", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "default" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid status value" + } + } + } + }, + "/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": [ + { + "in": "query", + "name": "tags", + "description": "Tags to filter by", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "default" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid tag value" + } + } + } + }, + "/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": [ + { + "in": "path", + "name": "petId", + "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" + } + } + }, + "delete": { + "tags": [ + "pet" + ], + "summary": "Deletes a pet", + "description": "", + "operationId": "deletePet", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "path", + "name": "petId", + "description": "Pet id to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid pet value" + } + } + } + }, + "/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": { + "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": [ + { + "in": "path", + "name": "orderId", + "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": [ + { + "in": "path", + "name": "orderId", + "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": "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": [ + { + "in": "query", + "name": "username", + "description": "The user name for login", + "required": false, + "type": "string" + }, + { + "in": "query", + "name": "password", + "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": [ + { + "in": "path", + "name": "username", + "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": [ + { + "in": "path", + "name": "username", + "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": [ + { + "in": "path", + "name": "username", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid username supplied" + } + } + } + } + }, + "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", + "position": 0 + } + } + }, + "Category": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "Pet": { + "description": "A single pet in the store", + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "description": "the identifier for the pet", + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "Category" + }, + "name": { + "type": "string", + "example": "doggie", + "position": 0 + }, + "photoUrls": { + "type": "array", + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "items": { + "$ref": "Tag" + } + }, + "status": { + "type": "string", + "position": 0 + } + } + }, + "Tag": { + "required": [ "id", "name" ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + } + }, + "Order": { + "required": [ "id" ], + "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", + "position": 0 + }, + "complete": { + "type": "boolean" + }, + "keyValuePairs": { + "type": "object", + "additionalProperties": { + "type": "string" + } + } + } + } + } +} \ No newline at end of file diff --git a/src/test/scala/Java/JavaModelTest.scala b/src/test/scala/Java/JavaModelTest.scala new file mode 100644 index 000000000000..79ade48d0ae6 --- /dev/null +++ b/src/test/scala/Java/JavaModelTest.scala @@ -0,0 +1,209 @@ +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 wiht 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) + } +} \ No newline at end of file diff --git a/src/test/scala/Objc/ObjcModelTest.scala b/src/test/scala/Objc/ObjcModelTest.scala new file mode 100644 index 000000000000..454fbedea1c6 --- /dev/null +++ b/src/test/scala/Objc/ObjcModelTest.scala @@ -0,0 +1,218 @@ +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 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).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) + +Json.prettyPrint(cm) + 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).required should equal (false) + vars.get(1).isContainer should equal (true) + vars.get(1).containerType should equal ("array") + } + + it should "convert a model wiht 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).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 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).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 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 ("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 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("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) + } +} \ No newline at end of file From ba45641801c1e825a8ba51cdb0f76dd844d71851 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 26 Sep 2014 22:52:27 -0700 Subject: [PATCH 039/325] updated for objc tests --- .../com/wordnik/swagger/codegen/Codegen.java | 20 +-- .../swagger/codegen/DefaultCodegen.java | 6 + .../swagger/codegen/DefaultGenerator.java | 1 + .../codegen/languages/ObjcClientCodegen.java | 12 +- src/main/resources/objc/SWGApiClient.m | 2 +- src/main/resources/objc/model-body.mustache | 46 ++++--- src/test/scala/Java/JavaModelTest.scala | 2 +- src/test/scala/Objc/ObjcModelTest.scala | 119 ++++++++---------- 8 files changed, 116 insertions(+), 92 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index 8d6282fa5662..32f48eeddc00 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -16,8 +16,8 @@ public class Codegen extends DefaultGenerator { 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"); - ClientOptInput codegenInput = new ClientOptInput(); - ClientOpts clientArgs = new ClientOpts(); + ClientOptInput clientOptInput = new ClientOptInput(); + ClientOpts clientOpts = new ClientOpts(); Swagger swagger = null; CommandLine cmd = null; @@ -25,14 +25,16 @@ public class Codegen extends DefaultGenerator { CommandLineParser parser = new BasicParser(); cmd = parser.parse(options, args); if (cmd.hasOption("l")) - codegenInput.setConfig(getConfig(cmd.getOptionValue("l"))); + clientOptInput.setConfig(getConfig(cmd.getOptionValue("l"))); + if (cmd.hasOption("o")) - codegenInput.getConfig().setOutputDir(cmd.getOptionValue("o")); + clientOptInput.getConfig().setOutputDir(cmd.getOptionValue("o")); if (cmd.hasOption("i")) swagger = new SwaggerLoader().read(cmd.getOptionValue("i")); - if (cmd.hasOption("t")) - clientArgs.getProperties().put("templateDir", + if (cmd.hasOption("t")) { + clientOpts.getProperties().put("templateDir", String.valueOf(cmd.getOptionValue("t"))); + } if (cmd.hasOption("h")) { usage(options); return; @@ -43,10 +45,10 @@ public class Codegen extends DefaultGenerator { return; } try{ - codegenInput - .opts(clientArgs) + clientOptInput + .opts(clientOpts) .swagger(swagger); - new Codegen().opts(codegenInput).generate(); + new Codegen().opts(clientOptInput).generate(); } catch (Exception e) { e.printStackTrace(); diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 9a3999963f6b..53ec1b311e9f 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -438,6 +438,8 @@ public class DefaultCodegen { 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; @@ -448,11 +450,15 @@ public class DefaultCodegen { 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; } diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 8c08ad288ef7..321e9b83ddf1 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -23,6 +23,7 @@ public class DefaultGenerator implements Generator { this.swagger = opts.getSwagger(); ClientOpts clientOpts = opts.getOpts(); this.config = opts.getConfig(); + this.config.additionalProperties().putAll(clientOpts.getProperties()); return this; } diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index 79be19f80911..fd515cc94ff2 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -29,7 +29,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { "NSString", "NSObject", "NSArray", - "NSNumber") + "NSNumber", + "NSDictionary") ); languageSpecificPrimitives = new HashSet( Arrays.asList( @@ -60,6 +61,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { 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"); @@ -71,7 +73,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { Arrays.asList( "NSNumber", "NSObject", - "NSString") + "NSString", + "NSDictionary") ); supportingFiles.add(new SupportingFile("SWGObject.h", sourceFolder, "SWGObject.h")); @@ -139,6 +142,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { return modelPackage() + "." + name; } + @Override + public String toDefaultValue(Property p) { + return null; + } + @Override public String apiFileFolder() { return outputFolder + File.separator + sourceFolder; diff --git a/src/main/resources/objc/SWGApiClient.m b/src/main/resources/objc/SWGApiClient.m index 1c48412bc5aa..0b8be93ab5db 100644 --- a/src/main/resources/objc/SWGApiClient.m +++ b/src/main/resources/objc/SWGApiClient.m @@ -6,7 +6,7 @@ @implementation SWGApiClient static long requestId = 0; -static bool offlineState = true; +static bool offlineState = false; static NSMutableSet * queuedRequests = nil; static bool cacheEnabled = false; static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; diff --git a/src/main/resources/objc/model-body.mustache b/src/main/resources/objc/model-body.mustache index 4d739ed6473a..6ffe52eb1b13 100644 --- a/src/main/resources/objc/model-body.mustache +++ b/src/main/resources/objc/model-body.mustache @@ -17,17 +17,14 @@ self = [super init]; if(self) { {{#vars}}{{#isPrimitiveType}}_{{name}} = dict[@"{{baseName}}"];{{/isPrimitiveType}} - {{#complexType}} - id {{name}}_dict = dict[@"{{baseName}}"];{{#isContainer}} + {{#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]; [objs addObject:d]; } - _{{{name}}} = [[NSArray alloc] initWithArray:objs]; } else { @@ -36,37 +33,56 @@ } else { _{{name}} = [[NSArray alloc] init]; - } - {{/isContainer}} + }{{/isContainer}} {{#isNotContainer}}if({{name}}_dict != nil) _{{name}} = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{complexType}}} {{/instantiationType}} alloc]initWithValues:{{name}}_dict]; - {{/isNotContainer}}{{/complexType}}{{/vars}} + {{/isNotContainer}} + {{/complexType}}{{/vars}} } return self; } -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; - {{#vars}}{{#complexType}}if(_{{name}} != nil){ + {{#vars}}{{#complexType}} + if(_{{name}} != nil){ + {{#isContainer}} if([_{{name}} isKindOfClass:[NSArray class]]){ - NSMutableArray * array = [[NSMutableArray alloc] init]; - for( {{complexType}} *{{name}} in (NSArray*)_{{name}}) { + NSMutableArray * array = [[NSMutableArray alloc] init]; + for( {{complexType}} *{{name}} in _{{name}}) { [array addObject:[(SWGObject*){{name}} asDictionary]]; } dict[@"{{name}}"] = array; } - else if(_{{name}} && [_{{name}} isKindOfClass:[SWGDate class]]) { + {{/isContainer}} + {{^isContainer}} + if(_{{name}} && [_{{name}} isKindOfClass:[SWGDate class]]) { NSString * dateString = [(SWGDate*)_{{name}} toString]; if(dateString){ - dict[@"{{name}}"] = dateString; + dict[@"{{name}}"] = dateString; } } else { - if(_{{name}} != nil) dict[@"{{baseName}}"] = [(SWGObject*)_{{name}} asDictionary]; + if(_{{name}} != nil) + dict[@"{{baseName}}"] = [(SWGObject*)_{{name}} asDictionary]; + } + {{/isContainer}} + } + {{/complexType}} + {{#isPrimitiveType}}{{#isNotContainer}} + if(_{{name}} != nil) + dict[@"{{baseName}}"] = _{{name}}; + {{/isNotContainer}} + {{#isContainer}} + if(_{{name}} != nil) { + if([_{{name}} isKindOfClass:[NSArray class]]) { + dict[@"_{{name}}"] = [[NSArray alloc] initWithArray: (NSArray*) _{{name}} copyItems:true]; + } + else if([_{{name}} isKindOfClass:[NSDictionary class]]) { + dict[@"{{name}}"] = [[NSDictionary alloc] initWithDictionary:(NSDictionary*)_{{name}} copyItems:true]; } } - {{/complexType}}{{#isPrimitiveType}}if(_{{name}} != nil) - dict[@"{{baseName}}"] = [(SWGObject*)_{{name}} asDictionary]; + {{/isContainer}} {{/isPrimitiveType}}{{/vars}} NSDictionary* output = [dict copy]; return output; diff --git a/src/test/scala/Java/JavaModelTest.scala b/src/test/scala/Java/JavaModelTest.scala index 79ade48d0ae6..c2004b0f9694 100644 --- a/src/test/scala/Java/JavaModelTest.scala +++ b/src/test/scala/Java/JavaModelTest.scala @@ -96,7 +96,7 @@ class JavaModelTest extends FlatSpec with Matchers { vars.get(1).isContainer should equal (true) } - it should "convert a model wiht a map property" in { + it should "convert a model with a map property" in { val model = new ModelImpl() .description("a sample model") .property("translations", new MapProperty() diff --git a/src/test/scala/Objc/ObjcModelTest.scala b/src/test/scala/Objc/ObjcModelTest.scala index 454fbedea1c6..70364e9375aa 100644 --- a/src/test/scala/Objc/ObjcModelTest.scala +++ b/src/test/scala/Objc/ObjcModelTest.scala @@ -36,7 +36,7 @@ class ObjcModelTest extends FlatSpec with Matchers { 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).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) @@ -46,7 +46,7 @@ class ObjcModelTest extends FlatSpec with Matchers { 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).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) @@ -54,14 +54,16 @@ class ObjcModelTest extends FlatSpec with Matchers { 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).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) } @@ -77,7 +79,6 @@ class ObjcModelTest extends FlatSpec with Matchers { val codegen = new ObjcClientCodegen() val cm = codegen.fromModel("sample", model) -Json.prettyPrint(cm) cm.name should be ("sample") cm.classname should be ("SWGSample") cm.description should be ("a sample model") @@ -87,7 +88,7 @@ Json.prettyPrint(cm) 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).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) @@ -100,12 +101,13 @@ Json.prettyPrint(cm) // vars.get(1).defaultValue should be ("null") vars.get(1).baseType should be ("NSArray") vars.get(1).hasMore should be (null) - vars.get(1).required should equal (false) - vars.get(1).isContainer should equal (true) 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 wiht a map property" in { + it should "convert a model with a map property" in { val model = new ModelImpl() .description("a sample model") .property("translations", new MapProperty() @@ -115,25 +117,23 @@ Json.prettyPrint(cm) 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.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).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) + 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 properties" in { + it should "convert a model with complex property" in { val model = new ModelImpl() .description("a sample model") .property("children", new RefProperty("#/definitions/Children")) @@ -147,15 +147,12 @@ Json.prettyPrint(cm) 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) + 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 { @@ -167,23 +164,20 @@ Json.prettyPrint(cm) 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.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 ("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) + 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 { @@ -195,24 +189,21 @@ Json.prettyPrint(cm) 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("Map", "List", "Children")).size should be (3) + 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 ("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) + 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) } } \ No newline at end of file From 530ebe1f7dd5564c664c1824d1a4c20587dbc8c3 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 27 Sep 2014 09:13:26 -0700 Subject: [PATCH 040/325] added map, list model types with tests --- .../swagger/codegen/CodegenConfig.java | 1 + .../swagger/codegen/DefaultCodegen.java | 101 +++++++++++------- .../swagger/codegen/DefaultGenerator.java | 8 +- .../codegen/languages/JavaClientCodegen.java | 2 + .../codegen/languages/ObjcClientCodegen.java | 23 +++- src/main/resources/Java/model.mustache | 21 ++-- src/main/resources/Java/pom.mustache | 19 ++-- src/main/resources/objc/model-header.mustache | 2 +- src/test/resources/petstore.json | 6 -- src/test/scala/Java/JavaModelTest.scala | 33 ++++++ src/test/scala/Objc/ObjcModelTest.scala | 34 +++++- 11 files changed, 184 insertions(+), 66 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java index 5bb8e2e9e3f7..d97d2b49c13f 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -33,6 +33,7 @@ public interface CodegenConfig { CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation); Set defaultIncludes(); Map typeMapping(); + Map instantiationTypes(); Map importMapping(); Map apiTemplateFiles(); Map modelTemplateFiles(); diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 53ec1b311e9f..c715cfe6b41a 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -45,6 +45,9 @@ public class DefaultCodegen { public Map typeMapping() { return typeMapping; } + public Map instantiationTypes() { + return instantiationTypes; + } public Set reservedWords() { return reservedWords; } @@ -171,7 +174,6 @@ public class DefaultCodegen { typeMapping.put("integer", "Integer"); instantiationTypes = new HashMap(); - instantiationTypes.put("array", "ArrayList"); reservedWords = new HashSet ( Arrays.asList( @@ -206,12 +208,12 @@ public class DefaultCodegen { if (p instanceof MapProperty) { MapProperty ap = (MapProperty) p; String inner = getSwaggerType(ap.getAdditionalProperties()); - return "HashMap"; + return instantiationTypes.get("map") + ""; } else if (p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; String inner = getSwaggerType(ap.getItems()); - return "ArrayList<" + inner + ">"; + return instantiationTypes.get("array") + "<" + inner + ">"; } else return null; @@ -319,11 +321,12 @@ public class DefaultCodegen { ArrayModel am = (ArrayModel) model; ArrayProperty arrayProperty = new ArrayProperty(am.getItems()); CodegenProperty cp = fromProperty(name, arrayProperty); - // m.vars.add(cp); if(cp.complexType != null && !defaultIncludes.contains(cp.complexType)) m.imports.add(cp.complexType); - m.parent = cp.baseType; + 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; @@ -335,46 +338,62 @@ public class DefaultCodegen { } else { ModelImpl impl = (ModelImpl) model; - // Json.prettyPrint(impl); - for(String key: impl.getProperties().keySet()) { - Property prop = impl.getProperties().get(key); - - if(prop == null) { - System.out.println("null property for " + key); + 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); } - 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(impl.getProperties() != null) { + for(String key: impl.getProperties().keySet()) { + Property prop = impl.getProperties().get(key); + + if(prop == null) { + System.out.println("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 && !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.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); + if(cp.baseType != null && + !languageSpecificPrimitives.contains(cp.baseType) && + !defaultIncludes.contains(cp.baseType)) + m.imports.add(cp.baseType); + } } } } diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 321e9b83ddf1..27251a1cedc8 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -262,10 +262,16 @@ public class DefaultGenerator implements Generator { String m = config.importMapping().get(i); if(m == null) m = config.toModelImport(i); - if(m != null) { + 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); diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 1bf0d5e92f80..654186d65e72 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -45,6 +45,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { "Long", "Float") ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); } @Override diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index fd515cc94ff2..19bc95fe32d6 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -30,7 +30,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { "NSObject", "NSArray", "NSNumber", - "NSDictionary") + "NSDictionary", + "NSMutableArray", + "NSMutableDictionary") ); languageSpecificPrimitives = new HashSet( Arrays.asList( @@ -77,6 +79,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { "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")); @@ -88,6 +93,22 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { 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)) diff --git a/src/main/resources/Java/model.mustache b/src/main/resources/Java/model.mustache index 938daf4d5f67..0d60aedd0683 100644 --- a/src/main/resources/Java/model.mustache +++ b/src/main/resources/Java/model.mustache @@ -2,25 +2,29 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} + +import com.wordnik.swagger.annotations.*; {{#models}} {{#model}}{{#description}} /** * {{description}} **/{{/description}} -public class {{classname}} { {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}} - * required: {{required}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ +@ApiModel(description = "{{{description}}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}} private {{{datatype}}} {{name}} = {{{defaultValue}}};{{#allowableValues}} //{{^min}}public enum {{name}}Enum { {{#values}} {{.}}, {{/values}} }; {{/min}}{{/allowableValues}}{{/vars}} - {{#vars}}public {{{datatype}}} {{getter}}() { + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty(required = {{required}}, value = "{{{description}}}") + public {{{datatype}}} {{getter}}() { return {{name}}; } public void {{setter}}({{{datatype}}} {{name}}) { @@ -33,6 +37,7 @@ public class {{classname}} { {{#vars}} 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(); diff --git a/src/main/resources/Java/pom.mustache b/src/main/resources/Java/pom.mustache index 1e2dd35d0691..5e71517d8a5b 100644 --- a/src/main/resources/Java/pom.mustache +++ b/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,14 @@ test - + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + + 1.5.0-SNAPSHOT 1.7 2.1.4 2.3 diff --git a/src/main/resources/objc/model-header.mustache b/src/main/resources/objc/model-header.mustache index 9dc5f15f4e84..de4b085e000e 100644 --- a/src/main/resources/objc/model-header.mustache +++ b/src/main/resources/objc/model-header.mustache @@ -6,7 +6,7 @@ {{#models}} {{#model}} -@interface {{classname}} : SWGObject +@interface {{classname}} : {{^parent}}SWGObject{{/parent}}{{#parent}}{{parent}}{{/parent}} {{#vars}} @property(nonatomic) {{datatype}} {{name}}; {{#description}}/* {{{description}}} {{#isNotRequired}}[optional]{{/isNotRequired}} */{{/description}}{{newline}} diff --git a/src/test/resources/petstore.json b/src/test/resources/petstore.json index ae078d34351e..9f8fb0e47aff 100644 --- a/src/test/resources/petstore.json +++ b/src/test/resources/petstore.json @@ -709,12 +709,6 @@ }, "complete": { "type": "boolean" - }, - "keyValuePairs": { - "type": "object", - "additionalProperties": { - "type": "string" - } } } } diff --git a/src/test/scala/Java/JavaModelTest.scala b/src/test/scala/Java/JavaModelTest.scala index c2004b0f9694..7e1cd7093400 100644 --- a/src/test/scala/Java/JavaModelTest.scala +++ b/src/test/scala/Java/JavaModelTest.scala @@ -206,4 +206,37 @@ class JavaModelTest extends FlatSpec with Matchers { 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) + } } \ No newline at end of file diff --git a/src/test/scala/Objc/ObjcModelTest.scala b/src/test/scala/Objc/ObjcModelTest.scala index 70364e9375aa..198fc019e84d 100644 --- a/src/test/scala/Objc/ObjcModelTest.scala +++ b/src/test/scala/Objc/ObjcModelTest.scala @@ -63,7 +63,6 @@ class ObjcModelTest extends FlatSpec with Matchers { vars.get(2).required should equal (false) vars.get(2).isNotContainer should equal (true) - (cm.imports.asScala.toSet & Set("SWGDate")).size should be (1) } @@ -206,4 +205,37 @@ class ObjcModelTest extends FlatSpec with Matchers { 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) + } } \ No newline at end of file From 9e5576d3fead6fd672cdf47fecf66fb1491b2a5b Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 27 Sep 2014 16:50:36 -0700 Subject: [PATCH 041/325] added empty var check --- src/main/java/com/wordnik/swagger/codegen/CodegenModel.java | 1 + .../java/com/wordnik/swagger/codegen/DefaultCodegen.java | 6 +++++- src/main/resources/objc/model-body.mustache | 5 +++-- src/main/resources/objc/model-header.mustache | 3 ++- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index 7dcb491dda19..776cce9cdc74 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -11,4 +11,5 @@ public class CodegenModel { public String defaultValue; public List vars = new ArrayList(); public Set imports = new HashSet(); + public Boolean hasVars, emptyVars; } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index c715cfe6b41a..e06497f79001 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -353,7 +353,8 @@ public class DefaultCodegen { m.imports.add(containerType); } } - if(impl.getProperties() != null) { + if(impl.getProperties() != null && impl.getProperties().size() > 0) { + m.hasVars = true; for(String key: impl.getProperties().keySet()) { Property prop = impl.getProperties().get(key); @@ -396,6 +397,9 @@ public class DefaultCodegen { } } } + else { + m.emptyVars = true; + } } return m; } diff --git a/src/main/resources/objc/model-body.mustache b/src/main/resources/objc/model-body.mustache index 6ffe52eb1b13..43555d48a19e 100644 --- a/src/main/resources/objc/model-body.mustache +++ b/src/main/resources/objc/model-body.mustache @@ -3,15 +3,16 @@ #import "SWGDate.h" #import "{{classname}}.h" -@implementation {{classname}} +@implementation {{classname}}{{#parent}}: {{parent}}{{/parent}} +{{#hasVars}} -(id){{#vars}}{{name}}: ({{datatype}}) {{name}}{{^hasMore}} { {{/hasMore}} {{/vars}} {{#vars}}_{{name}} = {{name}}; {{/vars}} return self; } - +{{/hasVars}} -(id) initWithValues:(NSDictionary*)dict { self = [super init]; diff --git a/src/main/resources/objc/model-header.mustache b/src/main/resources/objc/model-header.mustache index de4b085e000e..e8dc61316e05 100644 --- a/src/main/resources/objc/model-header.mustache +++ b/src/main/resources/objc/model-header.mustache @@ -11,10 +11,11 @@ {{#vars}} @property(nonatomic) {{datatype}} {{name}}; {{#description}}/* {{{description}}} {{#isNotRequired}}[optional]{{/isNotRequired}} */{{/description}}{{newline}} {{/vars}} +{{#hasVars}} - (id) {{#vars}}{{name}}: ({{datatype}}) {{name}}{{#hasMore}} {{/hasMore}}{{^hasMore}};{{/hasMore}} {{/vars}} -{{newline}} +{{/hasVars}} - (id) initWithValues: (NSDictionary*)dict; - (NSDictionary*) asDictionary; {{newline}} From 2729070d7fa48b595efdecf6e9163dc79cd472d9 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 27 Sep 2014 16:59:08 -0700 Subject: [PATCH 042/325] updated android sample --- .../AndroidJavaPetstoreCodegen.scala | 50 -- samples/client/petstore/android-java/pom.xml | 13 +- .../java/com/wordnik/client/ApiException.java | 2 +- .../java/com/wordnik/client/ApiInvoker.java | 1 - .../java/com/wordnik/client/HttpPatch.java | 2 +- .../java/com/wordnik/client/JsonUtil.java | 1 - .../java/com/wordnik/client/api/PetApi.java | 245 ++++++++++ .../{petstore => client}/api/StoreApi.java | 112 +++-- .../{petstore => client}/api/UserApi.java | 449 ++++++++++-------- .../{petstore => client}/model/Category.java | 27 +- .../java/com/wordnik/client/model/Order.java | 123 +++++ .../java/com/wordnik/client/model/Orders.java | 23 + .../{petstore => client}/model/Pet.java | 63 ++- .../{petstore => client}/model/Tag.java | 27 +- .../{petstore => client}/model/User.java | 79 ++- .../java/com/wordnik/petstore/api/PetApi.java | 320 ------------- .../com/wordnik/petstore/model/Order.java | 66 --- 17 files changed, 850 insertions(+), 753 deletions(-) delete mode 100644 samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala create mode 100644 samples/client/petstore/android-java/src/main/java/com/wordnik/client/api/PetApi.java rename samples/client/petstore/android-java/src/main/java/com/wordnik/{petstore => client}/api/StoreApi.java (70%) rename samples/client/petstore/android-java/src/main/java/com/wordnik/{petstore => client}/api/UserApi.java (72%) rename samples/client/petstore/android-java/src/main/java/com/wordnik/{petstore => client}/model/Category.java (63%) create mode 100644 samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Order.java create mode 100644 samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Orders.java rename samples/client/petstore/android-java/src/main/java/com/wordnik/{petstore => client}/model/Pet.java (61%) rename samples/client/petstore/android-java/src/main/java/com/wordnik/{petstore => client}/model/Tag.java (64%) rename samples/client/petstore/android-java/src/main/java/com/wordnik/{petstore => client}/model/User.java (72%) delete mode 100644 samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/PetApi.java delete mode 100644 samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Order.java 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 2e7f6d8c612d..41e811f2112e 100644 --- a/samples/client/petstore/android-java/pom.xml +++ b/samples/client/petstore/android-java/pom.xml @@ -107,6 +107,11 @@ + + com.wordnik + swagger-annotations + ${swagger-annotations-version} + com.fasterxml.jackson.core jackson-core @@ -140,8 +145,14 @@ test - + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + + 1.5.0-SNAPSHOT 2.1.4 4.8.1 1.0.0 diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiException.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiException.java index a0131b5cf8c4..9a1f62b3061e 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiException.java +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiException.java @@ -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/petstore/android-java/src/main/java/com/wordnik/client/ApiInvoker.java index 1536a1f1c582..2ca01b656781 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/ApiInvoker.java @@ -281,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/com/wordnik/client/HttpPatch.java index 07c94381d3b4..3243cc901a7d 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/HttpPatch.java +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/HttpPatch.java @@ -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/com/wordnik/client/JsonUtil.java index 3d96fa3ac71c..b761cc4bf44a 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/JsonUtil.java +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/JsonUtil.java @@ -18,4 +18,3 @@ public class JsonUtil { return mapper; } } - diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/api/PetApi.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/api/PetApi.java new file mode 100644 index 000000000000..538edecb81cd --- /dev/null +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/api/PetApi.java @@ -0,0 +1,245 @@ +package com.wordnik.client.api; + +import com.wordnik.client.ApiException; +import com.wordnik.client.ApiInvoker; +import com.wordnik.client.model.Pet; + +import java.util.*; +import java.io.File; + +public class PetApi { + String basePath = ""; + 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 { + + + // 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, null, 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 { + + + // 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, null, 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 { + + + // 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, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "Pet", Pet.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public List findPetsByTags (List tags) throws ApiException { + + + // 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, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "Pet", Pet.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + + + public Pet getPetById (Long petId) throws ApiException { + + + // 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, null, 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 deletePet (Long petId) throws ApiException { + + + // 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, "DELETE", queryParams, null, 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/client/api/StoreApi.java similarity index 70% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/StoreApi.java rename to samples/client/petstore/android-java/src/main/java/com/wordnik/client/api/StoreApi.java index 6ec0d4d7e2cd..33edba2abd53 100644 --- 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/client/api/StoreApi.java @@ -1,13 +1,14 @@ -package com.wordnik.petstore.api; +package com.wordnik.client.api; import com.wordnik.client.ApiException; import com.wordnik.client.ApiInvoker; -import com.wordnik.petstore.model.Order; +import com.wordnik.client.model.Order; + import java.util.*; import java.io.File; public class StoreApi { - String basePath = "http://petstore.swagger.wordnik.com/api"; + String basePath = ""; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public void addHeader(String key, String value) { @@ -26,12 +27,11 @@ public class StoreApi { return basePath; } - //error info- code: 400 reason: "Invalid order" model: - public void placeOrder (Order body) throws ApiException { - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } + + + public void placeOrder (Order body) throws ApiException { + + // create path and map variables String path = "/store/order".replaceAll("\\{format\\}","json"); @@ -39,10 +39,14 @@ public class StoreApi { 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, null, headerParams, contentType); if(response != null){ return ; } @@ -58,13 +62,11 @@ public class StoreApi { } } } - //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 { - // verify required params are set - if(orderId == null ) { - throw new ApiException(400, "missing required params"); - } + + + public Order getOrderById (String orderId) throws ApiException { + + // create path and map variables String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); @@ -72,6 +74,45 @@ public class StoreApi { 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 (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 { + + + // 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 { @@ -91,38 +132,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 { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, 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/client/api/UserApi.java similarity index 72% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/UserApi.java rename to samples/client/petstore/android-java/src/main/java/com/wordnik/client/api/UserApi.java index a489a79836ca..697455f93274 100644 --- 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/client/api/UserApi.java @@ -1,13 +1,15 @@ -package com.wordnik.petstore.api; +package com.wordnik.client.api; import com.wordnik.client.ApiException; import com.wordnik.client.ApiInvoker; -import com.wordnik.petstore.model.User; +import com.wordnik.client.model.User; +import java.util.*; + import java.util.*; import java.io.File; public class UserApi { - String basePath = "http://petstore.swagger.wordnik.com/api"; + String basePath = ""; ApiInvoker apiInvoker = ApiInvoker.getInstance(); public void addHeader(String key, String value) { @@ -26,24 +28,26 @@ public class UserApi { 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 { - // verify required params are set - if(username == null || body == null ) { - throw new ApiException(400, "missing required params"); - } + + + public void createUser (User body) throws ApiException { + + // 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(); + + + + String contentType = "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams, contentType); if(response != null){ return ; } @@ -59,13 +63,155 @@ 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 { - // verify required params are set - if(username == null ) { - throw new ApiException(400, "missing required params"); + + + public void createUsersWithArrayInput (List body) throws ApiException { + + + // 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, null, 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 { + + + // 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, null, 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 { + + + // 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, null, 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 { + + + // 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, null, 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 { + + // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); @@ -73,6 +219,80 @@ public class UserApi { 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 (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 { + + + // 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, null, 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 { + + + // 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 { @@ -92,194 +312,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 { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, 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 { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, 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 { - // 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, null, 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 { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, 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 { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, 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 { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, 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/model/Category.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Category.java similarity index 63% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Category.java rename to samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Category.java index a2dc94401c9f..5a0a18d40a5b 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Category.java +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Category.java @@ -1,12 +1,21 @@ -package com.wordnik.petstore.model; +package com.wordnik.client.model; -import com.fasterxml.jackson.annotation.JsonProperty; -public class Category { - @JsonProperty("id") +import com.wordnik.swagger.annotations.*; + + +@ApiModel(description = "") +public class Category { private Long id = null; - @JsonProperty("name") + + //public enum idEnum { }; + private String name = null; + + + /** + **/ + @ApiModelProperty(required = false, value = "") public Long getId() { return id; } @@ -14,6 +23,10 @@ public class Category { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") public String getName() { return name; } @@ -21,14 +34,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/client/model/Order.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Order.java new file mode 100644 index 000000000000..42bceaade96f --- /dev/null +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Order.java @@ -0,0 +1,123 @@ +package com.wordnik.client.model; + +import java.util.Date; +import java.util.Map; +import java.util.*; + +import com.wordnik.swagger.annotations.*; + + +@ApiModel(description = "") +public class Order { + private Long id = null; + + //public enum idEnum { }; + + private Long petId = null; + + //public enum petIdEnum { }; + + private Integer quantity = null; + + //public enum quantityEnum { }; + + private Date shipDate = null; + private String status = null; + private Boolean complete = null; + private Map keyValuePairs = new HashMap() ; + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + public String getStatus() { + return status; + } + public void setStatus(String status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") + public Map getKeyValuePairs() { + return keyValuePairs; + } + public void setKeyValuePairs(Map keyValuePairs) { + this.keyValuePairs = keyValuePairs; + } + + + + @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(" keyValuePairs: ").append(keyValuePairs).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Orders.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Orders.java new file mode 100644 index 000000000000..5100efe8042d --- /dev/null +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Orders.java @@ -0,0 +1,23 @@ +package com.wordnik.client.model; + +import java.util.Map; +import java.util.HashMap; +import com.wordnik.client.model.Orders; + +import com.wordnik.swagger.annotations.*; + + +@ApiModel(description = "") +public class Orders extends HashMap { + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Orders {\n"); + sb.append(" " + super.toString()).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/client/petstore/android-java/src/main/java/com/wordnik/client/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/client/petstore/android-java/src/main/java/com/wordnik/client/model/Pet.java index 5f68e4df203f..b98f2c63cc7b 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Pet.java +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Pet.java @@ -1,25 +1,32 @@ -package com.wordnik.petstore.model; - -import com.fasterxml.jackson.annotation.JsonProperty; +package com.wordnik.client.model; +import com.wordnik.client.model.Category; +import com.wordnik.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 */ - @JsonProperty("id") + +import com.wordnik.swagger.annotations.*; + + +/** + * A single pet in the store + **/ +@ApiModel(description = "A single pet in the store") +public class Pet { private Long id = null; - @JsonProperty("category") + + //public enum idEnum { }; + 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 List photoUrls = new ArrayList() ; + private List tags = new ArrayList() ; private String status = null; + + + /** + * the identifier for the pet + **/ + @ApiModelProperty(required = false, value = "the identifier for the pet") public Long getId() { return id; } @@ -27,6 +34,10 @@ public class Pet { this.id = id; } + + /** + **/ + @ApiModelProperty(required = false, value = "") public Category getCategory() { return category; } @@ -34,6 +45,10 @@ public class Pet { this.category = category; } + + /** + **/ + @ApiModelProperty(required = true, value = "") public String getName() { return name; } @@ -41,6 +56,10 @@ public class Pet { this.name = name; } + + /** + **/ + @ApiModelProperty(required = true, value = "") public List getPhotoUrls() { return photoUrls; } @@ -48,6 +67,10 @@ public class Pet { this.photoUrls = photoUrls; } + + /** + **/ + @ApiModelProperty(required = false, value = "") public List getTags() { return tags; } @@ -55,6 +78,10 @@ public class Pet { this.tags = tags; } + + /** + **/ + @ApiModelProperty(required = false, value = "") public String getStatus() { return status; } @@ -62,10 +89,13 @@ public class Pet { 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"); @@ -76,4 +106,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/client/petstore/android-java/src/main/java/com/wordnik/client/model/Tag.java similarity index 64% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Tag.java rename to samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Tag.java index 52407da12671..8c9101e60b00 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Tag.java +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Tag.java @@ -1,12 +1,21 @@ -package com.wordnik.petstore.model; +package com.wordnik.client.model; -import com.fasterxml.jackson.annotation.JsonProperty; -public class Tag { - @JsonProperty("id") +import com.wordnik.swagger.annotations.*; + + +@ApiModel(description = "") +public class Tag { private Long id = null; - @JsonProperty("name") + + //public enum idEnum { }; + private String name = null; + + + /** + **/ + @ApiModelProperty(required = true, value = "") public Long getId() { return id; } @@ -14,6 +23,10 @@ public class Tag { this.id = id; } + + /** + **/ + @ApiModelProperty(required = true, value = "") public String getName() { return name; } @@ -21,14 +34,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/client/petstore/android-java/src/main/java/com/wordnik/client/model/User.java similarity index 72% rename from samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/User.java rename to samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/User.java index 117dd216308d..cf20c0006735 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/User.java +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/User.java @@ -1,25 +1,30 @@ -package com.wordnik.petstore.model; +package com.wordnik.client.model; -import com.fasterxml.jackson.annotation.JsonProperty; -public class User { - @JsonProperty("id") +import com.wordnik.swagger.annotations.*; + + +@ApiModel(description = "") +public class User { private Long id = null; - @JsonProperty("firstName") - private String firstName = null; - @JsonProperty("username") + + //public enum idEnum { }; + 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; + + //public enum userStatusEnum { }; + + + + /** + **/ + @ApiModelProperty(required = false, value = "") public Long getId() { return id; } @@ -27,13 +32,10 @@ public class User { this.id = id; } - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - + + /** + **/ + @ApiModelProperty(required = false, value = "") public String getUsername() { return username; } @@ -41,6 +43,21 @@ public class User { this.username = username; } + + /** + **/ + @ApiModelProperty(required = false, value = "") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(required = false, value = "") public String getLastName() { return lastName; } @@ -48,6 +65,10 @@ public class User { this.lastName = lastName; } + + /** + **/ + @ApiModelProperty(required = false, value = "") public String getEmail() { return email; } @@ -55,6 +76,10 @@ public class User { this.email = email; } + + /** + **/ + @ApiModelProperty(required = false, value = "") public String getPassword() { return password; } @@ -62,6 +87,10 @@ public class User { this.password = password; } + + /** + **/ + @ApiModelProperty(required = false, value = "") public String getPhone() { return phone; } @@ -69,6 +98,10 @@ public class User { this.phone = phone; } + + /** + **/ + @ApiModelProperty(required = false, value = "") public Integer getUserStatus() { return userStatus; } @@ -76,13 +109,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 +128,3 @@ public class User { return sb.toString(); } } - 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 d1cb4ed07871..000000000000 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/PetApi.java +++ /dev/null @@ -1,320 +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; - -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; - } - - //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 { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, 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: 405 reason: "Invalid input" model: - public void updatePetWithForm (String petId, String name, String status) throws ApiException { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, 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 pet value" model: - public void deletePet (String petId) throws ApiException { - // 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 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; - } - } - } - //error info- code: 400 reason: "Invalid tag value" model: - public List partialUpdate (String petId, Pet body) throws ApiException { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "PATCH", queryParams, body, 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 addPet (Pet body) throws ApiException { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, 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: - //error info- code: 405 reason: "Validation exception" model: - public void updatePet (Pet body) throws ApiException { - // 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 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; - } - } - } - //error info- code: 400 reason: "Invalid status value" model: - public List findPetsByStatus (String status) throws ApiException { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, 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 { - // 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 contentType = "application/json"; - - try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, 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 { - // create path and map variables - String path = "/pet/uploadImage".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, null, 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/model/Order.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Order.java deleted file mode 100644 index 28e1e74d27a3..000000000000 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/model/Order.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.wordnik.petstore.model; - -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.Date; -public class Order { - @JsonProperty("id") - 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 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(); - } -} - From f04827c6d3518733442a14e4723d59819859fb48 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 27 Sep 2014 17:00:03 -0700 Subject: [PATCH 043/325] updated android sample --- .../java/com/wordnik/client/model/Order.java | 28 ------------------- .../java/com/wordnik/client/model/Orders.java | 23 --------------- 2 files changed, 51 deletions(-) delete mode 100644 samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Orders.java diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Order.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Order.java index 42bceaade96f..084eae46fd9e 100644 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Order.java +++ b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Order.java @@ -1,8 +1,6 @@ package com.wordnik.client.model; import java.util.Date; -import java.util.Map; -import java.util.*; import com.wordnik.swagger.annotations.*; @@ -23,8 +21,6 @@ public class Order { private Date shipDate = null; private String status = null; - private Boolean complete = null; - private Map keyValuePairs = new HashMap() ; /** @@ -82,28 +78,6 @@ public class Order { } - /** - **/ - @ApiModelProperty(required = false, value = "") - public Boolean getComplete() { - return complete; - } - public void setComplete(Boolean complete) { - this.complete = complete; - } - - - /** - **/ - @ApiModelProperty(required = false, value = "") - public Map getKeyValuePairs() { - return keyValuePairs; - } - public void setKeyValuePairs(Map keyValuePairs) { - this.keyValuePairs = keyValuePairs; - } - - @Override public String toString() { @@ -115,8 +89,6 @@ public class Order { 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(" keyValuePairs: ").append(keyValuePairs).append("\n"); sb.append("}\n"); return sb.toString(); } diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Orders.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Orders.java deleted file mode 100644 index 5100efe8042d..000000000000 --- a/samples/client/petstore/android-java/src/main/java/com/wordnik/client/model/Orders.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.wordnik.client.model; - -import java.util.Map; -import java.util.HashMap; -import com.wordnik.client.model.Orders; - -import com.wordnik.swagger.annotations.*; - - -@ApiModel(description = "") -public class Orders extends HashMap { - - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Orders {\n"); - sb.append(" " + super.toString()).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} From 48f05b41e4a1dab7c2844773ce098a7a3ec08557 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sat, 27 Sep 2014 17:00:30 -0700 Subject: [PATCH 044/325] updated android sample --- .../languages/AndroidClientCodegen.java | 8 ++-- .../resources/android-java/model.mustache | 37 +++++++++++-------- src/main/resources/android-java/pom.mustache | 13 ++++++- 3 files changed, 39 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java index dd475d944b21..f2a357aefc01 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java @@ -7,7 +7,7 @@ import java.util.*; import java.io.File; public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.api"; + protected String invokerPackage = "com.wordnik.client"; protected String groupId = "com.wordnik"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; @@ -19,8 +19,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); templateDir = "android-java"; - apiPackage = "com.wordnik.api"; - modelPackage = "com.wordnik.model"; + apiPackage = "com.wordnik.client.api"; + modelPackage = "com.wordnik.client.model"; additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put("groupId", groupId); @@ -47,6 +47,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi "Long", "Float") ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); } @Override diff --git a/src/main/resources/android-java/model.mustache b/src/main/resources/android-java/model.mustache index afa4a4957556..0d60aedd0683 100644 --- a/src/main/resources/android-java/model.mustache +++ b/src/main/resources/android-java/model.mustache @@ -1,21 +1,29 @@ 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}} +import com.wordnik.swagger.annotations.*; +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@ApiModel(description = "{{{description}}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars}} + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{#allowableValues}} + + //{{^min}}public enum {{name}}Enum { {{#values}} {{.}}, {{/values}} }; + {{/min}}{{/allowableValues}}{{/vars}} {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty(required = {{required}}, value = "{{{description}}}") public {{{datatype}}} {{getter}}() { return {{name}}; } @@ -29,10 +37,9 @@ public class {{classname}} { public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); - {{#vars}} - sb.append(" {{name}}: ").append({{name}}).append("\n"); - {{/vars}} - sb.append("}\n"); + {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); + {{/vars}}sb.append("}\n"); return sb.toString(); } } diff --git a/src/main/resources/android-java/pom.mustache b/src/main/resources/android-java/pom.mustache index 61caa2dd0f7e..11641082eeef 100644 --- a/src/main/resources/android-java/pom.mustache +++ b/src/main/resources/android-java/pom.mustache @@ -107,6 +107,11 @@ + + com.wordnik + swagger-annotations + ${swagger-annotations-version} + com.fasterxml.jackson.core jackson-core @@ -140,8 +145,14 @@ test - + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + + 1.5.0-SNAPSHOT 2.1.4 4.8.1 1.0.0 From d714f097eba5537e64a917db7b9fc3e5dc7ecde1 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sun, 28 Sep 2014 00:50:47 -0700 Subject: [PATCH 045/325] updated static template --- .../com/wordnik/swagger/codegen/Codegen.java | 2 + .../swagger/codegen/DefaultGenerator.java | 20 ++++-- .../codegen/languages/JavaClientCodegen.java | 6 +- .../codegen/languages/StaticDocCodegen.java | 64 +++++++++++++++++++ .../resources/swagger-static/index.mustache | 4 +- .../resources/swagger-static/model.mustache | 2 +- src/test/resources/petstore.json | 3 - 7 files changed, 85 insertions(+), 16 deletions(-) create mode 100644 src/main/java/com/wordnik/swagger/codegen/languages/StaticDocCodegen.java diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index 32f48eeddc00..eee6208f1e95 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -69,6 +69,8 @@ public class Codegen extends DefaultGenerator { return new JavaClientCodegen(); else if("jaxrs".equals(name)) return new JaxRSServerCodegen(); + else if("static".equals(name)) + return new StaticDocCodegen(); else throw new RuntimeException("unsupported client type"); } diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 27251a1cedc8..6772421abf35 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -35,7 +35,7 @@ public class DefaultGenerator implements Generator { try { config.processOpts(); Map models = null; - Map operations = null; + List allOperations = new ArrayList(); // models Map definitions = swagger.getDefinitions(); @@ -66,11 +66,12 @@ public class DefaultGenerator implements Generator { Map> paths = processPaths(swagger.getPaths()); for(String tag : paths.keySet()) { List ops = paths.get(tag); - - operations = processOperations(config, tag, ops); - operations.put("baseName", tag); - operations.put("modelPackage", config.modelPackage()); - operations.putAll(config.additionalProperties()); + Map operation = processOperations(config, tag, ops); + operation.put("baseName", tag); + operation.put("modelPackage", config.modelPackage()); + operation.putAll(config.additionalProperties()); + operation.put("classname", config.toApiName(tag)); + allOperations.add(operation); for(String templateName : config.apiTemplateFiles().keySet()) { String suffix = config.apiTemplateFiles().get(templateName); String filename = config.apiFileFolder() + @@ -88,7 +89,7 @@ public class DefaultGenerator implements Generator { .defaultValue("") .compile(template); - writeToFile(filename, tmpl.execute(operations)); + writeToFile(filename, tmpl.execute(operation)); } } @@ -96,6 +97,11 @@ public class DefaultGenerator implements Generator { Map bundle = new HashMap(); bundle.putAll(config.additionalProperties()); bundle.put("apiPackage", config.apiPackage()); + + Map apis = new HashMap(); + apis.put("apis", allOperations); + + bundle.put("apiInfo", apis); for(SupportingFile support : config.supportingFiles()) { String outputFolder = config.outputFolder(); if(support.folder != null && !"".equals(support.folder)) diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 654186d65e72..00683fdd0e92 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -7,7 +7,7 @@ import java.util.*; import java.io.File; public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.api"; + protected String invokerPackage = "com.wordnik.client"; protected String groupId = "com.wordnik"; protected String artifactId = "swagger-client"; protected String artifactVersion = "1.0.0"; @@ -19,8 +19,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); templateDir = "Java"; - apiPackage = "com.wordnik.api"; - modelPackage = "com.wordnik.model"; + apiPackage = "com.wordnik.client.api"; + modelPackage = "com.wordnik.client.model"; additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put("groupId", groupId); diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/StaticDocCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/StaticDocCodegen.java new file mode 100644 index 000000000000..d10b9df31ff6 --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/languages/StaticDocCodegen.java @@ -0,0 +1,64 @@ +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 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/src/main/resources/swagger-static/index.mustache b/src/main/resources/swagger-static/index.mustache index 87d421244318..3cfbea753c85 100644 --- a/src/main/resources/swagger-static/index.mustache +++ b/src/main/resources/swagger-static/index.mustache @@ -33,12 +33,12 @@ {{#apis}}
diff --git a/src/main/resources/swagger-static/model.mustache b/src/main/resources/swagger-static/model.mustache index fd107aa1fef0..a9a39ab6e91c 100644 --- a/src/main/resources/swagger-static/model.mustache +++ b/src/main/resources/swagger-static/model.mustache @@ -5,7 +5,7 @@ {{#vars}}
  • {{name}} : {{datatype}} -
    {description}} +
    {{description}}
{{/vars}} diff --git a/src/test/resources/petstore.json b/src/test/resources/petstore.json index 9f8fb0e47aff..1f450a3b0975 100644 --- a/src/test/resources/petstore.json +++ b/src/test/resources/petstore.json @@ -706,9 +706,6 @@ "status": { "type": "string", "position": 0 - }, - "complete": { - "type": "boolean" } } } From c75a951668ec5c50accc03b34df31af95d0fc43d Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Sun, 28 Sep 2014 00:52:32 -0700 Subject: [PATCH 046/325] updated sample --- .../docs/assets/images/logo.png | Bin 14577 -> 25467 bytes samples/swagger-static-docs/docs/index.html | 99 ++++--- .../docs/models/Category.html | 19 +- .../docs/models/Order.html | 58 ++-- .../swagger-static-docs/docs/models/Pet.html | 63 ++-- .../swagger-static-docs/docs/models/Tag.html | 19 +- .../swagger-static-docs/docs/models/User.html | 85 +++--- .../docs/operations/PetApi.html | 277 +++++++----------- .../docs/operations/StoreApi.html | 79 +++-- .../docs/operations/UserApi.html | 240 ++++++++------- samples/swagger-static-docs/main.js | 1 - samples/swagger-static-docs/package.json | 1 - 12 files changed, 501 insertions(+), 440 deletions(-) diff --git a/samples/swagger-static-docs/docs/assets/images/logo.png b/samples/swagger-static-docs/docs/assets/images/logo.png index 209e5a473fc0fcb6dcda9eb4cb660f72008929fd..7a217967d009167cd41969270ef075ab07d8d3c7 100644 GIT binary patch literal 25467 zcmZvE2b*P8m3HM^w{p%o=Xk4b<(%WKx)pBaoO8ZaN)SYa5tJ~3j*?6$O;Cc$^U#ED zng+TXr0H(pnHim= z!;4=%k%8UN>-UNUj?=863YZnEpmFAYbSQ`ppaD|CxmR~U#iJm={*6buF%`v(Eb)el z0v9>=WQ51e$auDjQ?|=st5vk^8^7s<6)2+(C>8YoK6ma;j2tJrz;kMamw(r};L4O{ zLiBx%2$0A%q_gByu*L0M2VDY5igySR*FWC%ce_h(ea}`#V1Lb0g|ZAs8cVi67R0^o ztbl+pAMWEYT}HNivhBU681;$+maD*#%MHK$!|)s5wVCV^D)#$W;lZw7&@Z29;#a1F%1QI%WY2_s(QQB<$q zf)TK50a?>E#%AM-RA5eEhN|Vk1Q=%li)tOhyr&h5kIk#XzAGMKm99uNRVTcCkgnmg zH~C=D%D@$Gf>PSuEdCb1Pw!l*tEgs!hC#S5$4~DDtF*ttJqp}InhUi7jJYwMkAN3L zbl2m8z0Rm;&ZAD0lvM5*d9J83UqQ; zjJazs(;d9+XoOm*<1sEs>=d1lUwQ3^Vph+wPMjbv?692%b`rnB4CdArBOGi7tv~=( za+UA@@MK~w*tgz0&N*%#e)c24O=df@UI1>;t+fnnJHrq-<$-{N32rXelmX__0~q8_ zztIK;CN4cIMg){aOm+IKVN}db@{Hao8g^NU%Jkcf?3bH_-{u^g8QA0MJw}{Yp_0Uv ze^d^Gxp7oADSnN47IZ;abZS$unjjaS1PL1QD)X3*W=L&XJ-BYM1>6wUaR~J#Fq*6q z))rv>2_vT1x7vlX8mc|Ton3Dd1I+rl_5`RYsFk(GeE{sd8c5L=*FFFdltE2GIzD&^ z{Q1)-RZx}jzHfdVx^|Zxx(6{eEinoljzx2Sc_wBmCwwY-40<-03^YQLA#*YW^JWT= z2m7$2ANthXeX3ps3=GhKF`d;9ApkE;Oz-na`^Yqz` z&u2iUYC#DQpt&gm+|0~r^4aY=!x!$A1}=nT zb+BqxvSB5U%#W~GED+9F25C709nDyo7KL4O7BLvGWd*Yijf}ii^mZ9`QH~fncrsX4 ziQ=)xQ;Q`}?P6xU0|o=Y-aEeS3{OC05NBn+`OqKkegXXMH~0uoBu2Ck0{BC$PrCb- za${V0dL|!^J+1{;9q|FyM|Er!cyNNTV=*O#Bn+fOx4JPAF#)ODOkhVSXGo2RH%CMF zI&qZfm%hnsqk()wN?6QLdTDw?)@*c8T0a}R9%6R{$W7=KkxCpYh0j>9nCxCo}T3;`A>3=5kxWV>sd zHO9A(d-i#jLaX9|WooOrd^_~zzh~)x_yTCK2m~8?R@aUO%3z4^vHTq>6= z7`H$lK$y?O*PjA2JA>E159UOF3qNtKs43aW%%#Ari+9d~nabh4UjrvaG=SqFeDjS* z8G$kg%L*`mA&J8Q!{XY3;-Sy|6^QH8$3)+Hh!=qp2y37Q!aA6Qu;B9`f)!EYq7HJn zNnquGx0+=jeBoEn6aRDneRp=ic>g!rHCFaOg#{cA2|0-Xt8Cc7)KDqbwXfz?9k3Is zm?{SJUvGO&E`j|a>5v-?3ZT{p>!Yt-yMt%Y=lAmH=TX7$1aQ)Ei)mW|HzDK)DhN8>$+@ zkH9J<46YFq6#&1hgC z00x}PW|eR@*29GLPv?WMxG;gLJUU#8L5DnH0MdfNIpT*Eu*0%W%zTfx%t8|DqEZ;EEQ)mUov=V6gT9-KBfQ(Aex`&hXlfEMz$x zFyMj}&5Hc!`$HYvy@0Xcgc>?D>qJ$Tt>$673T6Y}e?=?i1KRoErH(rK!lB-fH+k@E!*>pPpwFrI)1Z{4o&2sqxW(63mH#stv|0_Jiy9QMP*=^or zQ*QkJ#S72e`t1&@f)zCj0ooy|D_GWSSuR3@{V_iVz%&c4#@_my#8GkGe4bmbx^lN_ zTMYOqVFZ15vyP+36MbNw1z%B<(qz1NJC8T!Hzgv6i`+h;(E1yTC9arDWLkK~0t8^jvJOGqjTaLEFnzqvV$L1qhCcdT;1QGtuH`ha zp5kZao`r!KKZ|Az>X}#1Yxf@V!_IvITsfr-a@Y$3tS4pJM-RZP6;CavyY?`XbSxf? zIgd)zF|RY;k%^!=2=G_;|J&{7#H&hwG^`clc5a&02$&&^Ns}Hl%`A?zvx)hDsp!xG zb>nFeun6IbRjOevA9qbcv8)82eiym`GCCX<#sry6X)Df*w@*wo80eY`PJn8zVh!K; zsVC2h3=<>8pY4K2RDfYK{m$HOc0-YSo=rB}n(-+xftt9Iyrs53Kk#V!FuwzbYD26L zSBTpP?`NxLLf9mfmRL3)pWT8m7=S8g8Mv`}faaUuX@crWEgENZfgDktSX?>`U`Ad8-^J&P7k9(ThSt>-+GQ~!Lc>|i8ix5J z-Bgh?3(E|NR6h~S({Y%w_x}CRfZ8uCMvU8bhUktXawAJZVdX-mA;5ZZPe=C*j35Xz zFGyc!R;pbYTR@$pup%JE5Qen~qM;ks0c4G90ay%^si2h*P#y$O*Y;qhv@lP=)*w?U z$l6!c!#k9l`M&id5LYN*(>0&22_uHmw?AQIc|-14Xl|Qd{?`{D347yvaBPcHyFPgipeVAy_G3}KHZ z9cx|#LsYR)GNS^*0C9D-Iq%-3-6KZDR@>%#cN{NiZiZaLYEjUo*G>}bW8Oe6L zYfNwqx1e4Dt6^EyA`@K*VfFFUWO)F~=U)c%@Yd&p@~^!Bc3oF5?5p*3%Bj~S#&SZ( z7|;M@sd%Se7umj^X`F2fTi# z=tWT}yF5`7@*~wccB8~EtO|eh=zzHsxURXwaP@TqJH3C0f#+T1PNIR|gH6adq}4yj zv4aUYZm}@+{zIUmxJ+(7rD`(D`X9JpZ`kM?51|tvr33MGiAETG5Wwf!<6;Px<*~*a zAgblqf&zX5rnC_Z{o?HDmnaU7G{|OJBb!@aG3=1p%y!_>EGQf~=E*=|4*E}9lM4p= z!cO-u9&iODtH|T?rn#d+Q0N4EXmSJOP&9LyJe4wE&dx_F=!Z1siC8dypNZ5n{_wI##xZKt*NnvX3o; z=s^GJHXJZw5(Unj0VsuJukj3KW`O`v!F(OSFHRyPe4u_^Je|k<8Vl-0wXu3WyAM>! zFmee7h7ZXO27D7>4Kp-m;9Cdk6uU~^n#<*p}d-}*xvzp(gE@E zF@q;P%01W|%ywEU=-qFE9MeIRc&3td91SUeEbVYP&fz2BP{95$Xt?IqIWE}HCQk4X z*J9>(&5reBTMeQBA+bye&uM->CLs(T1*q#Tzseekno6Cjfo3JMJb=#YKNF)CDj#w* zz%OK>v$3Fn)vM}Y%xE#D4IO5|BT)4_r#UL}=5l4Qzjuj6qk$(0z;lox8tNMeP$_4~ zHT>m;=V9-5?)dLgL$=0ur>S>>K-@)HJS&H_?pww}t&XxM;70rLDc z@BWpiPg`yY?r!ap7+ihWjEZ3BYC##Z4^%H1S6Nvat}~7kydo}DsTlY`TExkk1(<#T zD@()XYPm`wT$Sb{u=$XCd;9qSuo0r+uLfS6*XI3m+SMv&&9uAuZJT&^Z3tsDIR_k& z>clw?AUu~2cfz(}p+n0+XA#+&GvmVL7l@Z>XelljX1QlZa^fp@g7l&G;LZF?FRVZV zuB(_07LqZYl#x{f6Nsm$KTQUe#x2fb4D1>2 z6c4XLc+xhgQ>~3b5~v>e;?1nj(V5N_)1o@hFFq^xc`-P;kru}^`$gu1r`l<;$vtV| z(BU^9bAsZ@Ct!ZKIR;Ab`D2_c%>EC*{2lbMID_n&cLy0%yVW$j{s_YWa8@7^!jJ$9 zz97~;w_aLKW@XKvfB?4N>Dmsv6LjKl<4k(SJO(nr?gOS6naZ63@IO8BD${iqDYY_U z2zd*$#nu9vjF-ME7I@KEq`s#Z_sqx4KSku%c8v)1)e+u zx%R0LP%z}^^c2QO!xSw49T_%=diQ1RD&O_~eaDl-owP>zwP5%JTpPF9ta-%X8Rn_^ z?AjQgop2t_fJ>g}+E^An^N?ovSoLTzd#@{>d$5TB2~=J&D4qmmckmF&kZWM3AUl&Q z({-pywdcF?dENp84u#b|&`h<9CAABRaXBq&3;?w}88rLGTKF!WTmV;a{-I5lD+|Ba z%Zppwg#h*}mP!bh#aY)NJb~4hg?nNlw?nuNCf{?QPoJ`1=9mOK8zQJn<&;d*l^>@q z?(t0h;1y6Agt7k9j~)U8Gotts#r(dLBjyH7pHVCK}#WesCK@p$7+QG~UqMYq@uv&LoLrS1a zm$fSlG0RiX9?fvHmx1~WW=65FNUjKPLb+MqdyO3gaOWm5!PDKJd|L+13m-krTlyg% z-7h}jP0rBAXEr9A{r>M`_rEIs11RS9$_xFw;u*I7dGY#-G6K(cYvzsTHIuOj>S*9L zfKf9j+oI}Qd|)?pi*_4Mte+mEet#84@Y5;=mLF^1p3Ggsm|L>pw?%6HB?NHc};?|h!2!@Oeb%D!m zY;2+Cdre!Ww$_r#)#c3bsnv<;%)R9`{Eb)}8^c}+%;o8=@#wwfrIpQ+y|P&A9VM{o z&Weq;-m%F*lfS=qT+xw#p*BV%)aWovvdV`Vc=Ci!BX+Ud>7jrp~$`PG$Z&O1J_ zy1i8v8_O4I|C4o2@6DgSX=PJw3meShm8_i1>@00=JZhk~q;r06ddXBfzdXINiFcIe zI=Za^TF9c?D;mJaa`oX~^OR&TL4cW%VLlodZuG)|jAq1iG)Bp9TJ50l4uTs2I|%*^k-9tuc%v- zF)%>5Tn+pvgl2#kX#3FuFqik{Z`2}(uReicY*S`k_mmAR-~>`-bNxF$_WV{kiSyEP zJchc%Wd!zs%rK`si-HX?RP1b?MQVr5Fo7XR3y-w!CYAb$5gwgD`hsXK=F*eh-drf) z(J`sxsR_6^RD&nf7GXv~#tqCLpbp!Ky|?}jqZR&K3-AeGjK`4mSNs!we0|Cv@Bfhv ze_UX;7(aIxE;zG^G5weOzM95K_aOjtA0Giq_K3?hWbEki>hC>nBEd0|r^1|e)r?I4l` zQwG^$B)Ei*rcYQRK=Xv?oj|@GSmPHP;3_@L^>u2;C(*5sx2~_aLYd(g$IjHLQI2Vi}ue8S+J@VKy%{u0fe%$4b+ttSj1yGg`niv8riXKNG4*Agq2PK5kZ@WICG}2leDD>}T50N3M1wm|5(WiWQXA|tW=~>R zZ3OwaS?1fUe|xNjHNb-wI26@CvLgnVf#CLe3JJQ)Rcml%^M0%|0d;F@Uw ztS~drNgEds*YCOxs=vrzIOuqUd+;&0R1mPVpU}nP2g)Ed7aj+9Tz-&mifMOfw}-Yq zVEqpW7yz;1>d#KFYgqEUnR4}88w@<3nbYgQju3_isD$vHH9ViHSS{*8YYuE433?r? zV#a9!3>2HKpRfP=_Bjm9y2-iZAmd#4MEg2-D2QdC1*{BT?ik3*#hX-62tv^n9Ge$rdx91=>n`LX)dRZLxJez?dh)v6;lZmqe{0V~z)xY!V z_Ir=t`W+7>4HKFLqlK{=USHl}5Y(y%*Llc%{1OP5FDsZC;}&n;1@aXqUs%t!~Lv@UpjiT;av<$tCb+R)uE!Hq63i+xdu(!2v4Rbk*u(kigm* zWbV#_&T@5{F6DUX7cria8(3RFnp(~(?DNkwiSsmT80RjDbInV|%yPnKoJaGvbHnA5 za4f4R0>a1N|2aqxIjw&T3`wB4+8Rro#jl6A^R))Z{C__78}W7JiRQ-{n1rw+k7Ov^ zC8{S3nkNoW2H}%~ZXgxCT0ee})ENOwpi-Bj0uLvv2VmSjdnOeeAr3HWVv|(>L|8=s z<^FS=^NlBE=ys3@gH_+*H#g25WpdHL!lfT`@5&?;hbo2n`4f#5xR#>f8`<2rSG!BPw&8B(wPmik{t1;N4^Ea3j!qZ@GXZh z`#hjBIFZLVD@Pq~gC^Jleu*8!rd4t9v1)^M5r*yAf!N%YMNE}qbppUQsJa8@M8hhN zOt!3zHgQ3D8g21a^hv5LR z6Gs;FKFLtBDF7ZZdeIKn$qV?l`=Mp^$$f1CARePFo3i{T(3 z{>uGgxOl56wsu0`88t;dAp#b(Q}wP9#z{) zY%OBh}?+`csr*Ay=(VfO>_~wHHTX+x%R2OsO zz(mSu%ttR($-o3vXZ@{2W{_$wRp+CDsR4CqLEOLuV+*X5f%exyM#vGQ5&~p5i1uOa z_lbS}UeUr!GoqbU(7Trx9pU-lHtnYFs%^FTYxmi!^Ub?~r7YmK`0Aze&oaco){1Db z>IJtP*dH)+2Ze{=dd@QeX@zhC!7*FADb51^qU@OVSh)&j{RyqPL2b1LitTEQf8*KAHZt!o>1eXdC&8Z&Nr0LefTU-=iZkp|3c#~xa=BDgh zjW@n#o6eIE=qem7taW!*J+=o=$jxta9yUGmQlnB1Q_!5qMFM6B3xRp)V^Z=0Q*|Cu zI#@uoC@`bOQzKQ5{d!6W;B-5^6|p zp8oV{uFO~fdizljuyCmAQHH7&-0jO%OvSD7O5d8;ZU@$X(~AM;_vGj2vsXb;5J0tW zR2gh82jF{B+_R^XnP!1y7rMAW)eh`_$dMUTovq_`k`lQ?f%V?CFm24P02a->h3#R1 zeD><9<&yQkqpO85-aLSSJT(`OWI-2~Ey(fHYqn;vM6LfX0MOxYKW~8Is&Zh)CYu=PVn#@K77b2te4OK{KHgQx%M?c$H( zyEWtnhSW}CG<%gk22F#xeHb?9=NY-jFP*>(Y9F%82g|lWY&mZFjn^u`tB~n4$1aBd zc;9cp0Lwe4m`!ySUPm%|{|C^VS{?G@hLIR>kPpSuUg8=}Cu~nY$oYpr7Bzs?*$~&GKYaBr zFAwg2-_A}hpXJlMv(IlmFV|`hpwl47$BFA#9<}F&`NESEMyAN0RlfiMc%twF&JgzT zXl5GD!grl5opsjr=F2S@>R?3oql zK)wzrSQZUFT_*;NBZIs;T$vLHZ4Y4(eXOTKx``h({)_{#lm%&f%*fbsNYyIz<(Dr% zl@3iCIIW0Yv-;fa*23Q?mp7ptAUq{T#HI1@08DO<8#XeJdumdc0_$&VSUQ5`3N=Sm z863+!;tgX9r_S4svh#Xf`xpow8^aLZ!Y`yNTh97dHlZURz^o{+^*7j@x>Z~(9Nz%O zoX-j@JW2ZJ7`66DaoL}!nPgbXUMXPKH~2PIqkw)vSbZcb5a1$#zkKC~V3vh|EyYVg ztYBc>Lp|&+W5$sQ{1P^KcIL9A8rV`nCuC=T_45Mk3P?U=xCZpEzx)B1A)01|^W@~b zY=GUp#bcf0AAa={*in3S66+G+vR8Sy0Og#C2N&?+qo5{;39<_TYMIoC5B@<$exkr# zteb9EZ5*pvp6ze2tcQ;y|L5FK9_!hv;+=^Q=Q!;iz95ag17wwnW+*n9b}rA>IfKD> zZpwV~acJPP+b1~@puz{MNE~XZr5F_sg_npkzC9_E^+YcNhT6beLxQdUS3r9SenVUg{W%cZp-=-9z{O_UU4C@r z{9WGS;ofxtAddsPPN;Elt94=!6&_~b%NSfP^N+uN4GaW9(o^}fj&oiKi&vk$#XefTtpwBLRu@M^LJMq@xoX!b2HV$7qXgw7~7-0 zxws+bM}sOSi#Y7vd;8gjWipIn57JIy1MP{k--R1vX3LL3GvWpBoYscs8$Ph*-Sv=} z)b0~?mSJ@50eim_?KT)Zl(VK7tE`jFZ5~1CMSP4$Pz*y2IE&ieVpu7ukekne;?h7| zxj==4&szVYyLjWy-&HQw$r~>)WxC9dzYC?R1J?Wh5CP`X2i@~L4jbD(yPYfRkF5Cf zi?{dHglA&_ut2sUT&L=RonB9N`B|*;b=wyn&<8~oiho19JUR$-ugbwQ3i|3ZeVv_h ziGht4lSh6cWT|>Bjt~D|?Z7f`VV^nn%F*6LwwL2oqpfXs( zthP2*uE6?t6SsN(s6Cm6U|+w7CmmzUw`-Vz)oA^UYp#VO=KI56E?a+@$xt7EdIy&| zxUaK=ii~0$d;3A}y~f(%p8^ETtFM^RS)$nkz6BsV{hHms-^o+#EOs;2Ke-={$__)g z_*c}4j8U|U3;3YkIgxK1mh0dQ2;;88sZsz(a}Z+D|mN zOspvn(FO---o;?)Afuc7d|ZFL)3_K6gYz+~JCNvzR3|8)kP8MDAuim%V^QuAlqU;h zq>?4UOnvn8Ki|pQ7BclrI&h2Y;wGzeL5xf_1ju1L9S3=gaYZbLJsy56os3Z)BwKt<)6K`hfc4L^ z*B{a^scQ3qZ&@z6L*;ac4W6#(4^!!30tPY)d8TCrmM{yfY94xk%0M37gAMwP3s0~( z*!|H(Dil1a-hFv#6pGsc4D1bo^)HcZxg{0LPzBTa&zG%#?-FjNN1!6g6aj;tpj38+ z?Ur~{e`63D$^6Y7f*Ls|&qe`*^~GNyV4&+;ShRpr=3;L~gsbi9bZ6T0>UfF?m@oA* zSia&^ul0WGp+w{I&|K9n7baL{*+)R?2HH=*N^-3$8M;qw?rh52y+lUf!}AZSzEhcg z=ZEk*$aU_4Spm2pr!ujHnF-Z%9y|sC>-We7Mw*PPR`-f?qx&)N%2+Q6ed8D62D4;F zr$IboH1H5yYv%pI-r{8UyC;B{iyGF>JgubSJ+Nyy7w4B3!0oUU*nz5EU@`g5kdBH% z??h;w8}9)a4@yz6<>T*(3p_BbRy`&zF0og;%AQ%S>SoGLnB<@t`>LG`d!}y=5*6Yy zY=(9?nO~a9d;2Arg17D!y`w^&fnls}U!4`#9_hw-!oMhK9y*e*)KCPA2g5w8LLF6+ z5fvCjMS!ME40KwNl+M9h8wBbXpIN>Rf2-nYI4Pn;Z7)XKYqk zm4OfyB3N;8oEOkL{OQR@^0+_^g%g>sGU$OiZ5%K5U}-X2*d7vM;w8t+Pp=F&4Z{Ld zAH!N@^3eJ=iF~t5bL#k{!Wm_AFt5~*9%@c*aw`bg72{}OmSYM-2AfSVjsJ?9x zmoJ~@QU#2NX{S*JT)3y0eM4+u&R@C`k^<$!>br0^sDj;f`DY+5yWZ811tp-h24UfS z3HV8j+2Z?vMpjf~Q18Wa&`#OB(g0D1E-XRohGv#&*5?n_xiS_XeSOe_Y0pu8Vf`H> zV>-n33TD~(fYXFwlXb)Jh3dBc_{w+0FT7!aW}|qy98?#pT*)QANH98e@xeytcb@B2 zCmXz3r{^nsh7~leikvS>XKTelfSeTT|4E{eu>->NAkJO0n*rt#<_6KQ&(19A4PZ|J zUYrT|tN4tHPnerKr~z393Y{#_wMjOm>@1*%IpqSw3smJru)RWR2f<(bb845Uu)x9a zGtB;)t^BFEI+^-qU*izG!GNNqpW|6 z^%e5Ty>n0pmJ9bml|xn`%aE1yH=p6s$C%ADJ|27inUhfH>K4$PZ6+6bm}CG0OIPn5 z=2DF7_Tv+5eik{vA}WS36n$52iW;c8i5+L{&!Fq6_AK+ zxzMCb;uctq5wSk%ft+X%G?FnZi<7QHqv;=C3!#w zAdws_ry7QO4?4=7(o7fuQM@9i1?t1+&EQTar|eO2eu?etgY7QgCQj>0x8r*FL^xjv zlyxxBg13JN{U7(gG8@TiD9i@wAp39MwaM;e=%?N4=|1siC6z${oe!ulEF>_RapitO zAPi5H_5WKG#vuflU=tW2stJR|{poMxieWJ(OX8ur`4FfR;#$N++zohk#w#r0 z%MXb2i+?)Jy(Ay4dP5!k>1WSa|2_rh;FA4L>cK$H#P-ccptt$nEr<)mRAl}6!BJ(d z`1FNY!8W+w`uR&qP}bUl1~@0{8|bPMon3h0ReLe5e}57t?}%WnaOc65?BPX-E##!t zR5S(My4*X*wB+)nOuqg^gN}99rQeT;V!{07;b%O3p*8Ho>WAb(x;Rk|qY3a`9$Z#9 z6R`u)z`_K^AuM?TyCK_-5dcE0--p>6R$H7iyU+<@{r~&joHN#{kHf8JSp#R0#>xOZ zA>qvZGQ=w)iDO{WU;sO^-4}P1Pp-Iekui`pHKidK168N*u-BU)KpuA=X8rHS+&Vj_ zvlSEq30?u&`qG~O5v*8$L!68O+hOcqZu^Fri>QTEmkhl3)Rao@8XW)j@HuezF6hc@ zpy3XXuHF&MyMlC!d<>=C%NawQvZO$uynC7zTcjg&cM`aN$nT!XX~pZu+@h?@^1(>reNI zj}^`hod0GKc*8q!thOEog9o$){^vapj%UI;;-^b3z>8Py8E64R1Ptgw#^!xTHd*nW zO6i4r-grvAYbA|7_DnLPSZf0Lvc3Ti$h)^QG+E-9i&vEyvp;W2fNwNzfJlCqh`p*1+7X=Z^oOPzl_WS-5cn=&-Xk6y-N`D>6PJU! z#DxIP^~|37%EC%1+~kcLOg+$VJ^^!i{OkifQ2`qj2U{6h|Irv@QU+l#4u&J)S7IrnC`2Q`|IZOZm delta 14263 zcmV;oH%Q3)#sTqhA&F2 z93X%P&;TJILH3P~G_bR?0{`dreSZkD;Wa3?sq6ow{qGN${rsbS0YL2FV;{e0-*AZQ z06;hTMpCE%U^n%N?xjX<;!_Z_QlNnlmu}*~zi{Iw_W29&;bAe*Ut1SHywgXAI#|MQcIdY_U$Th<#GDYH z2=ceE`YkVuq#D})mNy4eEgT_cg`8(WG3HLc@pMe6lL5rMP`(zr$8wVo{ezSg3LR56>$&neqq!ZsYTJi~qLC6ugHX2>ioP ztX7;+T>I1hpAq9saK<=uoGDHUeH48Y-Gy#NKSDR78-O6X1>K15LEqiPzwP?d3mHl_ zy|U@yXkZDw=nrDHentH0??1d0^EczS1_o&cRbUTWMSxKFEPwd#9-OzV4*oAKF_7T{ zdkleG%fI9C+b)ba^sXw#5TgVA41J7Y$8ZBV%r@w81B@Pwfhv^#6UF}=jT{Kr@^KhObs40G+eGF_hRXbpW&Zg#`q_2;T}W zzz;-#B=m?fPy^aPADDn0z!o?HH?SM#a1aQG7Via#APJ;_3~&mZ0p~ywC;=7VD!2g} zKr?6souC`^f#+ZpOn^x+3+BOhu!bXQbP*H83b9Ar5N{+9 zi9lkIL?i{tK(di@$R(r_xsKdMT9HRcKk@>3gUle`kQEdfMUP@d@u9>~3MdVf0m>5P zi1I`QqM}d^KRWI?Q%ATnKI-E)#bi zSBtxk>&LyrE#dKaF1!q02XBif35 zrKzI1M>9Y(MYBrFL@P$CMQcmzM;lLjlD3q#iS{Y&B<(7JnIJ*XAvh932uXxILJgsV zFh*FQqoWh1)1=!;7fg4EE|2aS-9x%JbU*1?=%wk6=soCT=ugm>)8D6mLBBvG62*!7 zM1OZ8m3V?!No*&+BK}|?F~~DmF!(VXWGG;$XBc4k%t*^9#%RE}n=yegm+>a!Q^q+a zS|)KOBPKG_0j2_`+f2huOUxu@C1zXZaOOv7VKf{ zC)sbX53#Rs@NpP$_;VcNsNopkSmxy6)aUf)Oy{iSe9pPTCCFvM70Q*x)xb5*jp3H& z-pRd}`vP|d_Z$x^k2a4lPdd*Ho|n8RUTI!?-hI3!ygj^2eEfW7e35+leC>R5{D18H z`urjMIsEtdX9P$Bx&pxhIRY&L9|hS24Ftmk^8_CV&I|DhnG3}TT@vaQS{0TMb`nk& zt`!~^A&6**1c>B_w291%3W!>ZCW=;zz7(Ss(+~?1J1f>Dwk$3o?jn9fyg__gf>Xjm zB0-{BVoZ`KsV5mFSuFWX3MZu@6@MyqUaC(TC9NtQBwZl=R0buZCKD`kUZ!6bE2}9R zAzLgvEJrVAAQvlFE%!#AUEWGQS-wI3vx2CCyF!*im%=YaRmCvHQpHgv7Ns3Z$x2O1 z-;|}5eU%H8pQ#X4OjQo5G^%{vCbP|d+l6f-sw7ow)g!8Hs_Sa%Y815^wSO6PQFU+i zLiJ${Rt-CiOpS+{SWQFCgPP5nKeg1fs9HC)zG%y7hiX@8Pj8pl?!Ucs`#T+B9kR|P zoe5n*U2olsx)XXrdSty~y|?-z`hNOl`cno{1|bGl3_cqw8d3~z87>=X8SOW^Z;UoJ zGfp?|HDNJvGC61R%2e1i(0{brblyzWY@gYEbF8_gd6xOG1)qhlMWx034)q=TcRaA9 zw{);PXZhAj+KOV;WR0@kVSU^ie+(nHlF&11+@!ZXhE(QfYDVY}~oF?x}`ZhB+AUA(Kj*T}ZyV)BxY zg-@Z+yswe(S>IVdeZL&P8GjxBZ2zeMoq+6s=|G*p(}6QVdO^8CbHPTz=Yqe6n1>XF zEQi{LmWOVHxrEh*(|?3}hu@B1i3p8&u!nz7+@AhOnaH%ri72h8Gg0#tOG;TZ673n? zNM(gZZcmJ4%;A_fvAVGZu|M`Y@4Xqv92XJS6E7WqEPg7%G~x0-%s$_JZHYpONr`Xv z8|=Sy06E}upzWZ@!PJA3hs+LDBoUHAlb$3iCTAxvrnsaurGN6J9!h<8*z9n18bcZ- zZTN`xk)orRqrpdekEtBXKlUr#Fa2?bVn%MpTBdL2&&CvZMj8f31?%@PUKnTHRg-vpUPi57j*7< zfnh;yA#dTa!hhxSe&+`+=wGNQ;w#E1TDcf}apaQOrTSv=;@lEkNo>i7Qs>gH%Nmy} z%ec!j%GS#x$|ox9D;`v;S5{W>R-LRyRmW7%T=BTlch&f6V~t$RrCRpdjBDUp%(ai# zy{`}5u)NWBQ{!e$omgGrEz+&@dZa$Se!d~7VWQEkv48*ej@xZb+D*6a$lob%7HTfI z%XatVJ;J@zdmAkYElc+!@6WXcw!UlgY8!2LZGZM)=Y!r3%Z`Vgrk(9w23;)=bsjc9 z(t33JvBu+uZnf_E9@U;(PgI}W>Q(Elf2#hpu}`zFsegO_y#c*})Ele}xvzL%6~C5xT|1#Rarce!o1V80 zZ%5zxzMFj?{eEpS^#k!k?v%h(<+Sp2^Ni_C-^X1aCubvPSLf0`F@GxjEcvLuavJF-!d1t7Rnd5Ew(M$Exr04{(W^h{eK77kBXlfKf6|3R;E_>uHo16)}_{) zep&t++X&y-h$K_UTeSch-cbPo0DLQl`yw|0NPPeh82;KDZ82cEi$D&7>P7P^IjOHt?+uFI?V|1K!)%AGvQTlTR!-gG3w~Wh83Qe=k(#?}C_U)ir zMpy+~``h^0`q}yI46=`KpgQh%N^?Hpa(~vf$gSMHc2~VevuE4xPOon7r{qDOVc$`| zxBj04eg%<&WkbwE1Hz7mUy113vlzue(TH}V#>HgD7VNzecQ1Y*VI~o^pZ|c)L9at8 zNma>%DZdW$rzssVI_h#PJpD*UX=c~)FDLm<*=J>Dcjqvkamvjy?&bh zfq{ZSzi0B#em?IQ${r?_iNjaEh zU#DJ9KbmR&ST}op?%JoDpKHEU%wPT5{%w9yW2tbN|Hs{x=r!G6TpJrO{#aNmZU<4I z5g{PP$Wde%C4)*qO~Tr$4OYf2SS#!#?igMT|AFQ_tp`DfFh@5FGXO9WnSVr?HCXIP zRMsJ$Dh$}OfXzDpun@|aY;<{g^2rKe ziuOv|lu61{DmP&!n5i+Ty-+XK2-8&40$Pu>v$uQbi0gdOZPGic?`fc6$ZGh-s2gTO zs;Q5ezB!-yn#JgjCd+)QIDcz*8$DZbJEGmv&e!&j9U2@?Qf8wUsB5vf zy)1D&@j?j_`{WbV_Uj$6IOuf9H;I~@mQs*<<8XJ{%u$A8D(P++`+qZwk9VHST2Aem;oL8IAfM%&c!5r#%X#XB+@iY|r;6E1%t{mC{P(bYsuEWvUTt#4?`ld- zX>I4VnH$8L%60a)g6sD;WHpxFu5aqPGtxYL_h$>?K5wghn@YRb15yX*nCl$wYJFJ! zDCcovw||e#6OCTUr+-3yy!~7QT!Y-t_@9dmNe(NFsJ_s8sXuBuW;5>oD)e>AL@~^V z_4k^S`#*F|bIyc*Y@L(%bm@!I{M&Cg7t6ml|M&(59%tTQzA%0t0armwq3yzwB8;%2>K3~w9wDJ2@l*1aRD`sc^svl9 zSwY$Ra%6c#zEr_nVNNkyNmJ>Ka)ye!%G+%xRdrQo)y}FLs(;eR*EG?b*DBC9(_YwK zq+_M?L$_4VUVm>xzutgisBE}kRA(GxqGqye+F%xMu5G?*ad*c7OMNR~)n=V)V{S{d zeP&mne0qGZ_?_~P z32+P42@(p%2G4{%3B4Y6COkgEbB|%9OcWOdPg#n7OMiVD(-d2>HzO`8-YG$2A6Fuh zxN-nFNPCDSi91;&MJ83{uvVJ>5!0iV$L!KQGbouyj~AV|d9w4=aMon@m($BRYiEAt z{>mfdE1q*JNG+^6KU@SZN?fuorj+ECHeP;Fwo#!}=~s2Oy5}mW*;X5T?ZWlJoA|oz zx1#DVH-8M@rft%?6WV<4?!$YF_XS$b+oIa@9<+44?ZQ5kdSv@JzPqAlyqEjw?!L7S&|G<-h2u=w-gX8iv;BimdPaB2XQ6a(M_&q(a80VtIP zKuj5~A1wgb5dm=21Sqb2fV7jwjnhJQQDFmMv?8lQs|xQZAfp~z|ECh{Cv zMscI`P<}9*uAxTY-c1VafZmU;KtIC(j6B8zla6V^e8lo#t+7eiChQ_k5f_fTg8PJ5 z#K+=WXb3cJG}W{yS`XSg1U^CvoOyQ94bwZ(4-s97V+=kFGmKG;D@>`(jLZcrk}UNk z6Mxck)*#k3wrqB3_6HnZ9IKppT*vC}+yy=o{2mv66dZ;yM#}_E8fD4`>`LP2xz-N@Y2me?;tPeY$bR$bWGv zT&0Gyt8$8R@8mNSoVlQR(Wf}8w6koZQn&ix)z)j68)kLK>Wdn0H9cwm*g|YoZx8LL z?E3cDq~~JqLch^q#`EqG)JyrXov*?slHO*&zxbhZ`qRhnb8kLho%j5@xIkTe{at%G z^T)Fl=2eTe{p(e~hPLJpCZGV%v47&=*+B=Gg{K1BkpLtMse}9cUnnt@6)FZ*gnEQp zgnM=ybRxPMJ&K`&>&hNXF=hx$hc&>)W9zX?I5k{6?k*k+_tAy;IT{0+b2Q7eZnXCa zGK2y;M!Mtltn?R%GQ?&EJBBI7Bqjl-R%U+|B1;3wlNDhtXR~8lW3S?H=YJ$}wsY;{ zR^?vcxyeiAQ{`Lczax+&XfDJgG%8#!LKQUXZNH*ZsavjBre9`IZdhw{$M~Viu<4Z9 z4-3K$UP}cl18WDH0NXgbjDMZy?JFGW9NV1+ojidc3F<%nY(AL^2X2YDMX*oEAqaiS%1P_`m=1J;z?D@ zmAaamYgIQY>dNXf8zY__G2{cz?!r95jOW2s5IOL?RcEF61jb*Rh1>I8~@oGy~cI9gDt-evjeB zIAgLfPhi|Fu$kB)oG>m5*A7omqVWSX>NF*^?6g?~HbN1d65R-WDp8d<%}~VX%EZbv zz?{S4N)jS{W9?$Q#D0*&mvaY~8n-wP4=;&#o$mvGzd);CoqtfZaG6M{Xt~%`@dk-b z$q}hp=?z&{IVpKP1t-NYrNhcaDtER`sL`k^Yj|m%(7LBRuOp)CqL-=PX7IyE+IY7~ zu4$h+(ZXg&w&e?J5t}`>EjyX*Jsrv%7o3e<@?5{V+wH3J6xe;z8%s{|`Ru3RpAyg) zBoG`G(hhO$QWk7?h_9Ty$nyH76h)czj_0}j1Rc1#&MygP07=)q%? z8HSmcP9P`!PCd$2JY8^xHaFqym;AtU?+Sg+zbmr8c)wV&W>=a$`yp^PQ5r>i2r@2e;9*S9k2}Tz`F7@z}M8@TB8uQor87+OvkC zh!NozPe)_N*}91K8k01Qab;)n}P z&-C&7ef@vBU%!6cLw)M;_qg`2J;DKckI=bKCgH$7T6?J-?4z}h)?VVkUZQnhw)PTQ z>|P?aLM!E>D)+dl3YcH$_uA$Ya%&21zStvodj~BbMCq_-nyP4uieHzeXtJbfvi?NT zu~6|#QF@obFci&D6icxjZfKg(D4IOMdxDy#?Kywsx*9FQRr~{AHJ2)?#k?wuid@p9 zk|IeiMN(t{rs{u)K>*m45d&Gk28{8`vNXd|9OvTP4C`h%fpYs8JRx$qQN(8AZoTVD zwANd{OD?NYNh{^#VqOu8iY#ifs4A+<-8(^7>!iI zU&w@sZ$=kqdeGdhIXM~s6c;5b<-D3(6}f*U259-itS`iJUW|CUm~|6syN?z|enr+G zNx2oNkd`4#vRpO(o1tnB85^;U%rP)3vJ1mtxuE3IGDOWAWc*Ri8(?Ub?jAYYJ+yRr zf?k(TN!g^B&q`vMsCE`fvcYgCqo8=H3|&S=C%m>S`9e&nSMc;eMd^yZad*(d_=JD) zBbQM!i{*S;7Rwloj8Uno({mCB+j$vXrK+l>f=enYYiT7AW`cbJx<`s3`sXfQJB^mX zi(*zuFP3x5Qn?J}ZWpV+P0^UbDMck+Qgc})6yZVxJO(zTAw9ruTsw*uL`o^EtBX>4 zsa(!$XurEr<)+I-_pIcVR8d1W5bA&D!uxpy8dL#IexFRp(iq`j#7wa}!*vbs23g7q1_BC&dOOi^?gt#znoO3MjJ zA!{42mJ7pJa;}8hMnHL&&55 zPtBHKvLQ|cP6Or)TBtcRz@^zD93`BlutQw!V76ew(v5ODp#$bUhQTEYOwsVI9(J=>hF=UqFoMSXebv|XdGfraS*Wf&>~8p znw&1e5(xVCFEaEXm}448duVB{l^f;kin1?NW}GVbU`uvMN+(KAwdB^( zf`DW3H<{?})!z!|cIgHynaNo(w<^O~sC^PzLwA zdZRpC-r89SYZ@)^5O%PY8%4PU-P9Sdbaxsp;PH>fMo0R_eBJ;{a|T!d?}_JsoGz?6 z%DZ*Wqujnw^say7_hSEoj+RSOrCf1sc47KP>c(1e4bIoN+QVr*HD+L7n%jrH60O^O zn??)bluL@)RT=L8j#LBk6!He|IC97BNAKth#{=FF3nMnkoBV^nD?L*O0uT(!@v`ZWeeG^kdhi{rZ{>`6$eSUS(5x`uED>Ya0^fJ0%> z?fbJ+AG&|zmb-hy{VW`aYMKCP?VY@cicvF?fDD%9W8r}}-F(mc-}+I%+fy5-1)`um z=QGk;3aVL){X`RJp$Mg{z{>8FKa8v?cb&NJ4ae?s^WLp0@4OwmrlbbEa|_h%9HE~2wVK`5+l-e^g0Ir+AL;B!R0z&bdO=2lx=s<1t7Q7%;?9-Qc!96<|$ zH9jyoK6u!|BPfBFW?wl!b9N=OM4SawHIvUaX#SSuO$9MkNTyR?`_Y%M%av!@XsG|D z(PMuHM~-eN9qXBm#}AChCtjL9%Q4L~?kz~c3}JPl6zJtzSg^2*7Wf4lWnr!LKG#A# zy11$M0n6}?_WRTekA3Hv|5=5tMv?XXiCRg9qS0bUZzcxX?v= z{5|iz`%m9|{FGUVatr>+_<=LmUa}-_Er@@r7%o?T&j818PK}@tugnT|fnpkDDQBCY zE%u|EfZ~qLJWXc4W!Y%a0>=h@J(d`Y%d_x71n(@*cPxm$F)x<0c`I5y;a(V{Dk9h> zJ*XcRZ}Y274=c9Na>*(j+1n)1lH7mI2oNvJ!*q5T$6r_;?r;z-DV_OU0ZeYhLhJ6h%vf zW`j_y3u`KN7Byw4*&Z#l^+E=RRyetig%*VoqIS&2i3m=O4b8I89AAZvsQQ1RT{sfO z$^IFcK^1^YOLaNhglwSYa*_Q!PLjG#QwOr#rnYup*Xy4grxu-IJ|kl%j{R#pv|z>+ zwL(s|pJQ7wJ8TuSNgIYPn=#vpM$?6?)ReF6HfUjJ5%V};$$?dBOU2MsYg_BCs~856 z*lcT|7Qs4?Y9lrCglL9kwY+}@mkqngwuuOamT?>w-0+>g$T~<3ToTS-a=xf0NymsH zm#t}F6>xOiGV;d(I8firb`xv4)!}W>f@uUJVe5;X)rD0;=xG=hOIg;^;X}IXV1dYD zDPJMgxIxR}Sg1t~Q->}WC&bxjua#dGDiuX57iFzt2eQ0wJ*atc?p1%ye5*j%@P$%sYXyzag6QMmrBXq4a-yZvj{|6e{t!o7t(2KU z)^Uz(!>~H9sdR4D@|dORkT2-?unIB2(1o3PHhbAdXn|t6OpZdeklua}t4Sk$qa0tg zzAnikjHvtP$Dea6_~xaxB#r1-12< zqv_H9NsCsvnn|u?Q#-I&+?aF_u$)~xQ0e5*P>v^r0OK#q|uerv@Av^{p=-#C><4I5iNAuI5+s zrF>oYLNE?%yC)`3-2b|Fo;YwDl-cD>ikxd*PuW7YeWBjFZ+*+XC+{DM#54JHu9!1V z{?Hk&=F(Ar_|WJv6FIJszvt-qEzv+2=eqJ7$Fn?;YqK#!7&s3dA}*okqUzsQHE?Sb zR98PKx{-eXTGLp=;G;+If9#=8jPy_NEa!211rDnZW>8!gub=(FufGc~c=(@J(u1eB zA3XWN`~NZ)8AM};XVSfkSHJxI&s|PjwJeN5s(4=bz^M=2dHj@{cVnPEb^AM>IsL@H zKk;vnWlLGe_Sop*kG$jKL$NV9V!-?3)a?&^_0fONpP6~3GXI03fn&12|J)--#&4b) z-fYb%cVu9)FA{&->mPzp-dLLc%zu8mwunjs(0#}61vX}4kudBDeB^)6O z!SBT2;g3A{@!mkh+_Qn0M0)8fkA8k8anYOuB-ie` z>u-?5_OG@Qad7#UFa7+pkNm^Mxl6=3!jylLq>9H6+&0obY3`uV_79I9J2HCIi~&X+ z;P=L3ZwBj48MpxOohMH53}fa66r4k2N2i8wGD|1!Ck79lJa`h{aj4_~VnEU>H!ghk zTc7#W*{94Un&VXN+qto?W^RoZ8H&v{ZHJ!vX_Kpqk397s=Wkp?)_`_6PD5$@8ME^*@=5vq)!Yy>}YXNZ~DWIKjlmrT#YGuILoTexPIrj30;=2vJI zw@x1a@B@Dxi}ahHJA1!12G(*K#U#CfxqGsvwHrnrY_+~_q=fE(q3C1p`owF-ZpIg6 z%-L}ad*<>B*XAymAL9Pp^y%|+7tAt8rblA=sTY4@=?4@=`pNS@k~G;|L+F2v=dYi? zc>QHdwpZpZym0w^Hd`Dzx3VNo zCoT>248Wekv3#kVKRt0+OU^uZ z_8Ay^EZuk|6I(Z$OYkw_0b3e8)!+-dFaph-Uc-kF+Syo#4i(%CdIEn?-(kka4CemZ z9~>JzXs!wDnm_*Kx4-=87tt&#HP;6-Iu`0VFmx#7k1Ve)U7Wv|#j(*8d_*<@sN^GX z+*oXEd|(Rmj_HNVH*lVrEY`+E>%qf_KYVcTU^o=ZWK$RCE~fDz0epC9BU>_%sOrNH z{q23P{R0bBS7*;X_S=6SUYtFLDH@b`_~=&%Xzd2`jh;S!nH&t(boiZ$9~T$dfr2A2zez za;K!|Us~FDK?DsS&eE+`P*B0r2DBii&UwTp-)ur~BOB}gNj`{7Y+=NDL;@R9WkgjK z`As+9ZGj5i_&0xk`n4;I(}W&9|1Ar!7Pw7V-}Jmq9OHFEv@qo0s90P1*otJZ3Cwx% z@{8Bzt7e@@e`Nf)pU2GCYJ4Ny)UR#JsN`?qe%*u{xmtM+0{k8yEbf+6SLe>Zc=ZMJ z>g1|M*AlbYATQwiD7F$c!U8#P0_laEz0lXe;&&}^*^+AP5Ni zdPWB(EX7=$y^t;DHuWIO>o$VCw@MdnkW(YH0J!~(8kAA{3LLq%aD~{lOjk767Y)a1 z=U%2LJ8_FoR7L}lfVXN#1=#~Q^9o&W9?~XFs3X}z#>p{Urv+LUk2A?xyBuzW z7Ba+oli;s1jM}Vm<7j}Sh&8>MbFF=DpRPYPPThamw`iG|uv^N2nhAoz56km5gBS@o zANFrl$#H``w=15dJpMM0y4k8^=;g!#xN6)&T&zynC48%#op|nbTaOvQ+(1$s+iX~& z5zC$)d`@&b5GwJvi3m{@JT%7vuu2kVZtzjf+71>LCTDVQCl}~eEMF&sYMrP~gytVX z#lU}uMD6dn+XgMz*#sPs#nVFBUp+y-k0sb+@-RldCgv=~_oQa>%4JnH#wvH$kAi zK9MDtaS`D@;Mw0<_ zgYF=Um8}{cG|Fguv`A{s73ksZZiHx5-1!&?<6SrqZK7YWQBVs}&@+EU z0=<@mYx#8T?9dXYsUW(+5XP4#Rc%{nL3a)IvVv`MmL0l9Sx#q@mYDJ0Q7G|NiL*rN zWDpBF@X7Ie!ZYr?9U7=wXF?ekqC|} zmghllcsMd3SKALQaXK2ruB4&pP}F~4Wzt27i_7zH({M^x#266l<5}AaC6y}MLkrPq zD%2-9c)$r9AEpyC6*`O?n0(%K=li0;9;^rAPd_#gCXWsZ8-&Ry#VD~i7=729-{9~lT-UAP2)X>5OFGsn2= z#QlfHj-9)9I+2_$%OVbWeD>_qnNr?j6gMYn`5sWg+5Po5y#c;y0?QBfjUF98-X9&Z zWLPZaF3(>u`=MGQG!=we5e%}vAlE`iWfv_l7iahO#04D4;Yd?w7zXYu*ArJJhi@|1 z7K|H;jmIM+Fr?x+1nZ@lGiiUatH6miVlD}vqEppasP}^pKCC+^V&(&v8CY1Y1w!n=-kg~Znb`}J|88@#Y_mb4WrkoVZHzgH+1p~u#e+Vm6E1%H3LK!j_pcW(kM zh%g4mo=&LO--{Z)olVT zl19}+{hW`icvW&}{RXWSZT4Ru{o+r5`-4{ch1N^9l@coZ6TkWHmwxcMqF8oFu(Uvk z4ff%HR$BzrMzT9@87Y5(5ju>>h>$;5sLiW|C-_DQJTJfe!!NvW={NV>_V(e}NPlDq zu6~uQNN4Cs7gWiy`UWrv)kpVZ&)U+;{7iEC$=^Nx{KemvMG0%N)rndRVbw7@;>J;b z%^s&)DX)?DXC;#524XyOHkVDI8V+>jx|EWk$<1Ob!JupW^5tJ- z$(Be5%Cb}hrmv_kbn@`)43BpBrj=!Bt(Z-&EH2_Bo%nz;Dbt~XRadx=8#(4{=R2d5hm2V%vWiL|Tz?bi3XN9~%~094qVb7knY4=vp-C2{->b1r;gHzyl?06bFGO zdl$$*$Dq=ytHlQ0?hw}wRLG|lw2%xvS9D0g8QG3#^Ll;AkHJ36Z{=-=ZY;&EL+D^( zsw)uUBEzkJ8mK}`i)aBZTA+I;Jn)BX(vDmy`c-iQVPb!Hs(;GE2;?~VHm_FEf_T9& zA0_=^tLkW*l<$q?;BRc$?L{Bhti8Qn{aQy0xuHMo9d(ECNe(ASsYl)(f2L~Tehyl@ zQ`VTa&?5aIOAk!qOoFylojs1p7UZigcYpzNh}%H>ouFPwduV|SxLNs`p@SZ1sBJ1d zTU2^aJ_dg)Sb>fo@Ub4dyM64`vt6`M1_m%+go}^6q4w?rMi>Ikf}!G*9)F~DBU4@Q z96*cYi#<<6!oax4q3r6Cx@R6@@-{Hx4##=NhjVAxOS)wWMlhj&6jSCs!`2QFidGvL z79e4cbHW+4NVP#4MfHw*ps-?1_Ep#=qRJS$`-Xqry(2h*7L#n}ujXv<+n3K!u?aUw zP2M1%Aai^d?DhogQVi0gP_F(lPjnR3?+8?=nbT;YeX&&Egd69fC1&vT*3MDBOR&@{ zmQ<5=4NiI^LwrXo>@-@a3|bjYMaSF>N6%lwhZ-ES)7N9v?mq)mSl$_&@`U15M{sw7 zvJQWsWspfx;b8$LvV}{9GS0_zZhY(n7h2B~JEq+9;32Oc1|7$hiW;&yh8DVUxMC3> zM>=u2P{5~)oLIW7p?^0YK&t#bY<$Y&!CFKIG{D-rb+FBorlt`WpV4FfD12`a>U`^~ ztzjpgK;?xdffIj5kKvdxVs+b@nsrdNbg+L2uUI!7KjZ~$i_~>R1s}X?b`7VUmaPg}xFL*iQP|Er81O~2^2&mk zNr{j%5~mw<5Z!r!7pPE7z!|C-ZlQkx5_#Gsk*ct67i7yQn^c@&=7Nh|JitWbLONN_ zreu7G!*KNIn6a%=ck7MOzoA@DfDT3lsC>K^4r@f7j91nKJ09LOw2Yb>n4yQ^gG^rl zb~d$;mNQAQxTZ*Dc!H97O{ZZ45n;H(i$GXN51yO`9Irqne!8SL6+v^IZRr!Hrh znT7iKV2l%sYB4LXt;mI}jIX~L40Q@QXm=1_eF(y*R*C5d$5;Eqj5ow`5GG(mM$vAO zr%e{^ik4w6-h6M!8Tr)@ZsP+?u%E|woXS}_pH)hE1rW+Ocn!P#$cn_KR)UdkD-Fc} z#wZ2%L|Bj#M~(3ezRZJ3t}lPg;AkW`mEa+HX;>wUUn5yJ{dSFPRWn5wCITC@M_%Ck zeY_@XI3o|52)^4V<`jHkOcFH-A6>-Z(YVN1M?Mv1jCmXQk)01@2OaX^X=ryi3=l_D zu*j3AA;;MCL1akp@hHbX;aOcHM?zhS7U8{7Khn$zPhAWJ^MT;gd@g_Ns3F^2i6j7~ z61I8cv!=MiAG$Y^jtq8?J%)nNa2!pMEtX{X19<5Ah-B&=A%P0FGetting Started
- - + + + +
+
+ PetApi +
+
+ + + + +

Getting Started

@@ -80,4 +109,4 @@
- + \ No newline at end of file diff --git a/samples/swagger-static-docs/docs/models/Category.html b/samples/swagger-static-docs/docs/models/Category.html index 7917b84c824c..52e04b2072a3 100644 --- a/samples/swagger-static-docs/docs/models/Category.html +++ b/samples/swagger-static-docs/docs/models/Category.html @@ -1,12 +1,15 @@ +

Category

-
    -
  • id : long -
    {description}} -
  • -
-
    -
  • name : string -
    {description}} + +
      +
    • id : Long +
      +
    • +
    + +
      +
    • name : String +
    diff --git a/samples/swagger-static-docs/docs/models/Order.html b/samples/swagger-static-docs/docs/models/Order.html index c5c129ae6dbe..cea3cef3fd62 100644 --- a/samples/swagger-static-docs/docs/models/Order.html +++ b/samples/swagger-static-docs/docs/models/Order.html @@ -1,27 +1,39 @@ +

    Order

    -
      -
    • id : long -
      {description}} -
    • -
    -
      -
    • petId : long -
      {description}} -
    • -
    -
      -
    • quantity : int -
      {description}} -
    • -
    -
      -
    • status : string -
      {description}} -
    • -
    -
      -
    • shipDate : Date -
      {description}} + +
        +
      • id : Long +
        +
      • +
      + +
        +
      • petId : Long +
        +
      • +
      + +
        +
      • quantity : Integer +
        +
      • +
      + +
        +
      • shipDate : Date +
        +
      • +
      + +
        +
      • status : String +
        Order Status +
      • +
      + +
        +
      • complete : Boolean +
      diff --git a/samples/swagger-static-docs/docs/models/Pet.html b/samples/swagger-static-docs/docs/models/Pet.html index 4409c2ddddeb..b2c1c6d9feed 100644 --- a/samples/swagger-static-docs/docs/models/Pet.html +++ b/samples/swagger-static-docs/docs/models/Pet.html @@ -1,32 +1,39 @@ +

      Pet

      -
        -
      • id : long -
        {description}} -
      • -
      -
        -
      • category : Category -
        {description}} -
      • -
      -
        -
      • name : string -
        {description}} -
      • -
      -
        -
      • photoUrls : List[string] -
        {description}} -
      • -
      -
        -
      • tags : List[Tag] -
        {description}} -
      • -
      -
        -
      • status : string -
        {description}} + +
          +
        • id : Long +
          +
        • +
        + +
          +
        • category : Category +
          +
        • +
        + +
          +
        • name : String +
          +
        • +
        + +
          +
        • photoUrls : List +
          +
        • +
        + +
          +
        • tags : List +
          +
        • +
        + +
          +
        • status : String +
          pet status in the store
        diff --git a/samples/swagger-static-docs/docs/models/Tag.html b/samples/swagger-static-docs/docs/models/Tag.html index aa0705acd830..ba0314f1c41f 100644 --- a/samples/swagger-static-docs/docs/models/Tag.html +++ b/samples/swagger-static-docs/docs/models/Tag.html @@ -1,12 +1,15 @@ +

        Tag

        -
          -
        • id : long -
          {description}} -
        • -
        -
          -
        • name : string -
          {description}} + +
            +
          • id : Long +
            +
          • +
          + +
            +
          • name : String +
          diff --git a/samples/swagger-static-docs/docs/models/User.html b/samples/swagger-static-docs/docs/models/User.html index bf89f5a46bff..41f7e2376f17 100644 --- a/samples/swagger-static-docs/docs/models/User.html +++ b/samples/swagger-static-docs/docs/models/User.html @@ -1,42 +1,51 @@ +

          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}} + +
              +
            • id : Long +
              +
            • +
            + +
              +
            • username : String +
              +
            • +
            + +
              +
            • firstName : String +
              +
            • +
            + +
              +
            • lastName : String +
              +
            • +
            + +
              +
            • email : String +
              +
            • +
            + +
              +
            • password : String +
              +
            • +
            + +
              +
            • phone : String +
              +
            • +
            + +
              +
            • userStatus : Integer +
              User Status
            diff --git a/samples/swagger-static-docs/docs/operations/PetApi.html b/samples/swagger-static-docs/docs/operations/PetApi.html index c90614ad3e17..c64179cba9c6 100644 --- a/samples/swagger-static-docs/docs/operations/PetApi.html +++ b/samples/swagger-static-docs/docs/operations/PetApi.html @@ -1,191 +1,140 @@
            -

            PetApi

            -

            This is the PetApi API

            +

            +

            This is the API

            + + +

            updatePet

            +
            +

            +

            +

            URL

            + /pet +

            HTTP Method

            + PUT +

            Response Type

            +
            +

            Parameters

            +
              + +
              +
              body :  ()
              + +
              +

              Pet object that needs to be added to the store

              +
            + +
          + +

          addPet

          +
          +

          +

          +

          URL

          + /pet +

          HTTP Method

          + POST +

          Response Type

          +
          +

          Parameters

          +
            + +
            +
            body :  ()
            + +
            +

            Pet object that needs to be added to the store

            + + +
          + +

          findPetsByStatus

          +
          +

          +

          Multiple status values can be provided with comma seperated strings

          +

          URL

          + /pet/findByStatus +

          HTTP Method

          + GET +

          Response Type

          + +

          Parameters

          +
            + +
            +
            status :  ()
            + +
            +

            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

          + /pet/findByTags +

          HTTP Method

          + GET +

          Response Type

          + +

          Parameters

          +
            + +
            +
            tags :  ()
            + +
            +

            Tags to filter by

            + + +
          +

          getPetById


          -

          Returns a pet based on ID

          URL

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

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

          +

          URL

          + /pet/{petId}

          HTTP Method

          GET

          Response Type

          Parameters

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

            ID of pet that needs to be fetched

            -
          + +
        +

        deletePet


        -

        URL

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

        +

        URL

        + /pet/{petId}

        HTTP Method

        DELETE

        Response Type

        -
        +

        Parameters

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

          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

          - -
        - + +
      + + + \ No newline at end of file diff --git a/samples/swagger-static-docs/docs/operations/StoreApi.html b/samples/swagger-static-docs/docs/operations/StoreApi.html index fdca080c5640..9e7d9dd1eed8 100644 --- a/samples/swagger-static-docs/docs/operations/StoreApi.html +++ b/samples/swagger-static-docs/docs/operations/StoreApi.html @@ -1,59 +1,74 @@
      -

      StoreApi

      -

      This is the StoreApi API

      +

      +

      This is the API

      + + +

      placeOrder

      +
      +

      +

      +

      URL

      + /store/order +

      HTTP Method

      + POST +

      Response Type

      + +

      Parameters

      +
        + +
        +
        body :  ()
        + +
        +

        order placed for purchasing the pet

        +
      + +
    +

    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} +

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

    +

    URL

    + /store/order/{orderId}

    HTTP Method

    GET

    Response Type

    Parameters

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

      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} +

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

+

URL

+ /store/order/{orderId}

HTTP Method

DELETE

Response Type

-
+

Parameters

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

    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

    -
    -
- + + + + + \ No newline at end of file diff --git a/samples/swagger-static-docs/docs/operations/UserApi.html b/samples/swagger-static-docs/docs/operations/UserApi.html index addb63e48942..1c8fecf597a5 100644 --- a/samples/swagger-static-docs/docs/operations/UserApi.html +++ b/samples/swagger-static-docs/docs/operations/UserApi.html @@ -1,155 +1,191 @@
-

UserApi

-

This is the UserApi API

+

+

This is the API

-

updateUser

+ + +

createUser


-

This can only be done by the logged in user.

URL

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

This can only be done by the logged in user.

+

URL

+ /user

HTTP Method

- PUT + POST

Response Type

-
+

Parameters

    -
    -
    username : string (path)
    + +
    +
    body :  ()
    -

    name that need to be deleted

    +

    Created user object

    -
    -
    body :  
    User (body)
    - -
    -

    Updated user object

    -
    -
-

deleteUser

+ + + +

createUsersWithArrayInput


-

This can only be done by the logged in user.

URL

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

+

URL

+ /user/createWithArray

HTTP Method

- DELETE + POST

Response Type

-
+

Parameters

    -
    -
    username : string (path)
    + +
    +
    body :  ()
    -

    The name that needs to be deleted

    +

    List of user object

    -
+ + + +

createUsersWithListInput

+
+

+

+

URL

+ /user/createWithList +

HTTP Method

+ POST +

Response Type

+
+

Parameters

+
    + +
    +
    body :  ()
    + +
    +

    List of user object

    +
+ + + +

loginUser

+
+

+

+

URL

+ /user/login +

HTTP Method

+ GET +

Response Type

+ +

Parameters

+
    + +
    +
    username :  ()
    + +
    +

    The user name for login

    + + +
    +
    password :  ()
    + +
    +

    The password for login in clear text

    + + +
+ +

logoutUser

+
+

+

+

URL

+ /user/logout +

HTTP Method

+ GET +

Response Type

+
+

Parameters

+
    + +
+

getUserByName


-

URL

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

+

URL

+ /user/{username}

HTTP Method

GET

Response Type

Parameters

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

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

    +

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

    -
-

loginUser

+ + + +

updateUser


-

URL

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

This can only be done by the logged in user.

+

URL

+ /user/{username}

HTTP Method

- GET + PUT

Response Type

- +

Parameters

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

    The user name for login

    +

    name that need to be deleted

    -
    -
    password : string (query)
    + +
    +
    body :  ()
    -

    The password for login in clear text

    +

    Updated user object

    -
-

logoutUser

+ + + +

deleteUser


-

URL

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

This can only be done by the logged in user.

+

URL

+ /user/{username}

HTTP Method

- GET + DELETE

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)
    + +
    +
    username :  ()
    -

    Created user object

    +

    The name that needs to be deleted

    -
-

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

    -
    -
- + + + + + \ No newline at end of file diff --git a/samples/swagger-static-docs/main.js b/samples/swagger-static-docs/main.js index 06c3995110ed..45a7221546fb 100644 --- a/samples/swagger-static-docs/main.js +++ b/samples/swagger-static-docs/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/swagger-static-docs/package.json index a24f93457a8c..d728e9f00639 100644 --- a/samples/swagger-static-docs/package.json +++ b/samples/swagger-static-docs/package.json @@ -10,4 +10,3 @@ }, "license": "apache 2.0" } - From 89a009c41139d8d78a34977e971a2a05a2125d4c Mon Sep 17 00:00:00 2001 From: Martin Ehrnhoefer Date: Mon, 29 Sep 2014 16:26:06 +0200 Subject: [PATCH 047/325] [2.0 Spec] Implement Schema Object.example field see issue https://github.com/wordnik/swagger-core/issues/699, pull-request https://github.com/wordnik/swagger-core/pull/700 --- src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java | 2 ++ src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java index 8461310a298b..e2704637a71a 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java @@ -12,6 +12,8 @@ public class CodegenProperty { 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; diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index e06497f79001..0074e21d7dcf 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -412,7 +412,7 @@ public class DefaultCodegen { property.description = p.getDescription(); property.getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1); property.setter = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); - + property.example = p.getExample(); property.defaultValue = toDefaultValue(p); String type = getSwaggerType(p); From cb25eb6bc041174cfff1c41713a4915771f11087 Mon Sep 17 00:00:00 2001 From: Martin Ehrnhoefer Date: Tue, 30 Sep 2014 09:32:52 +0200 Subject: [PATCH 048/325] Windows path problem fixed (again) - #268 #269 --- .../wordnik/swagger/codegen/languages/JavaClientCodegen.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 00683fdd0e92..511e8d9ea9e9 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -56,11 +56,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replaceAll("\\.", File.separator); + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replaceAll("\\.", "/"); } public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replaceAll("\\.", File.separator); + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replaceAll("\\.", "/"); } @Override From ca06241307e1ddbdfe248b2305cb6ecf90e70b08 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 30 Sep 2014 05:09:47 -0700 Subject: [PATCH 049/325] updated scripts --- bin/objc-petstore.sh | 2 +- bin/static-docs.sh | 11 +++-------- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/bin/objc-petstore.sh b/bin/objc-petstore.sh index 164eb72f11e6..199ef4fb7ada 100755 --- a/bin/objc-petstore.sh +++ b/bin/objc-petstore.sh @@ -21,6 +21,6 @@ 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.Codegen -i src/test/resources/petstore.json -l objc -o samples/client/petstore/objc" +ags="$@ com.wordnik.swagger.codegen.Codegen -i src/test/resources/petstore.json -l objc -o samples/client/petstore/objc -t src/main/resources/objc" java -cp $APP_DIR/target/*:$APP_DIR/target/lib/* $ags diff --git a/bin/static-docs.sh b/bin/static-docs.sh index af769fa79a8c..f7a1e89c00d9 100755 --- a/bin/static-docs.sh +++ b/bin/static-docs.sh @@ -1,7 +1,6 @@ #!/bin/sh SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -22,11 +21,7 @@ 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" +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ com.wordnik.swagger.codegen.Codegen -i http://petstore.swagger.wordnik.com/v2/swagger.json -l static -o samples/swagger-static-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 +java -cp $APP_DIR/target/*:$APP_DIR/target/lib/* $ags From c05a3c3a99920fad4a02744baf24c8e5bdc57c47 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 30 Sep 2014 05:10:24 -0700 Subject: [PATCH 050/325] updated client --- .../client/petstore/objc/client/SWGOrders.h | 15 +++++++++++ .../client/petstore/objc/client/SWGOrders.m | 27 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 samples/client/petstore/objc/client/SWGOrders.h create mode 100644 samples/client/petstore/objc/client/SWGOrders.m diff --git a/samples/client/petstore/objc/client/SWGOrders.h b/samples/client/petstore/objc/client/SWGOrders.h new file mode 100644 index 000000000000..2acdc54b3be2 --- /dev/null +++ b/samples/client/petstore/objc/client/SWGOrders.h @@ -0,0 +1,15 @@ +#import +#import "SWGObject.h" +#import "NSDictionary.h" +#import "SWGOrders.h" +#import "NSMutableDictionary.h" + + +@interface SWGOrders : NSMutableDictionary + +- (id) + +- (id) initWithValues: (NSDictionary*)dict; +- (NSDictionary*) asDictionary; + +@end diff --git a/samples/client/petstore/objc/client/SWGOrders.m b/samples/client/petstore/objc/client/SWGOrders.m new file mode 100644 index 000000000000..8c919d1913dc --- /dev/null +++ b/samples/client/petstore/objc/client/SWGOrders.m @@ -0,0 +1,27 @@ +#import "SWGDate.h" +#import "SWGOrders.h" + +@implementation SWGOrders + +-(id) + + return self; +} + +-(id) initWithValues:(NSDictionary*)dict +{ + self = [super init]; + if(self) { + + } + return self; +} + +-(NSDictionary*) asDictionary { + NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; + + NSDictionary* output = [dict copy]; + return output; +} + +@end From 05e1d02341cef73813735a1928be53174034c65e Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 30 Sep 2014 06:06:01 -0700 Subject: [PATCH 051/325] added custom class loading for configurations --- .../com/wordnik/swagger/codegen/Codegen.java | 12 +++++++++++ .../swagger/codegen/DefaultGenerator.java | 21 +++++++++++++++---- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index eee6208f1e95..aafa9a85397d 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -71,6 +71,18 @@ public class Codegen extends DefaultGenerator { return new JaxRSServerCodegen(); else if("static".equals(name)) return new StaticDocCodegen(); + else if(name.indexOf(".") > 0) { + // 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); + } + } else throw new RuntimeException("unsupported client type"); } diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 6772421abf35..c739dbed7bfe 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -100,8 +100,8 @@ public class DefaultGenerator implements Generator { Map apis = new HashMap(); apis.put("apis", allOperations); - bundle.put("apiInfo", apis); + for(SupportingFile support : config.supportingFiles()) { String outputFolder = config.outputFolder(); if(support.folder != null && !"".equals(support.folder)) @@ -137,7 +137,6 @@ public class DefaultGenerator implements Generator { } public Map> processPaths(Map paths) { - // group by tag, create a Default grouping if none Map> ops = new HashMap>(); List tags = null; @@ -164,13 +163,27 @@ public class DefaultGenerator implements Generator { for(String tag : tags) { CodegenOperation co = config.fromOperation(resourcePath, httpMethod, operation); co.tags = new ArrayList(); - co.tags.add(tag); + co.tags.add(sanitizeTag(tag)); - config.addOperationToGroup(tag, resourcePath, operation, co, operations); + 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); From 2787fa82c606588095c75ce6fe9adfd544689db2 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 30 Sep 2014 06:11:51 -0700 Subject: [PATCH 052/325] added docs --- README.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/README.md b/README.md index 6118d3e9852d..e7dba82fea3f 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,43 @@ Or for example: Great for creating libraries on your ci server, from the [Swagger Editor](http://editor.swagger.wordnik.com)... 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: + +``` +$ ls -1 src/main/java/com/wordnik/swagger/codegen/languages/ +AndroidClientCodegen.java +JavaClientCodegen.java +JaxRSServerCodegen.java +ObjcClientCodegen.java +StaticDocCodegen.java +``` + +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 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: From 8cf9cb95f56e96e2fb58f245647a358eb4c28c73 Mon Sep 17 00:00:00 2001 From: Maneesh Sahu-SSI Date: Tue, 30 Sep 2014 21:57:21 -0700 Subject: [PATCH 053/325] Added support for Map --- .../swagger/codegen/languages/AndroidClientCodegen.java | 3 ++- .../wordnik/swagger/codegen/languages/JavaClientCodegen.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java index f2a357aefc01..0f6abef68030 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java @@ -45,7 +45,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi "Double", "Integer", "Long", - "Float") + "Float", + "Object") ); instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 00683fdd0e92..ae4c31c3da73 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -43,7 +43,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { "Double", "Integer", "Long", - "Float") + "Float", + "Object") ); instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); From 3971bbf334a76d6aecd106f4f5556d0dcaba1ec7 Mon Sep 17 00:00:00 2001 From: Martin Ehrnhoefer Date: Wed, 1 Oct 2014 16:56:46 +0200 Subject: [PATCH 054/325] [2.0 Spec] Java generator: Implement Enums #287 Very basic implementation --- .../java/com/wordnik/swagger/codegen/CodegenProperty.java | 1 + .../java/com/wordnik/swagger/codegen/DefaultCodegen.java | 6 +++++- src/main/resources/JavaJaxRS/model.mustache | 6 +++--- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java index e2704637a71a..cda9ab714d40 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java @@ -18,6 +18,7 @@ public class CodegenProperty { 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/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 0074e21d7dcf..971acd4a51b9 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -4,6 +4,7 @@ import com.wordnik.swagger.util.Json; import com.wordnik.swagger.models.*; import com.wordnik.swagger.models.parameters.*; import com.wordnik.swagger.models.properties.*; +import org.apache.commons.lang.StringUtils; import java.util.*; import java.io.File; @@ -441,6 +442,7 @@ public class DefaultCodegen { if(sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = _enum; + property.isEnum = true; // legacy support Map allowableValues = new HashMap(); @@ -449,7 +451,9 @@ public class DefaultCodegen { } } - property.datatype = getTypeDeclaration(p); + property.datatype = property.isEnum + ? StringUtils.capitalize(getTypeDeclaration(p)) + "Enum" + : getTypeDeclaration(p); property.baseType = getSwaggerType(p); if(p instanceof ArrayProperty) { diff --git a/src/main/resources/JavaJaxRS/model.mustache b/src/main/resources/JavaJaxRS/model.mustache index 3836a0ad9273..f6cb2b01cdf9 100644 --- a/src/main/resources/JavaJaxRS/model.mustache +++ b/src/main/resources/JavaJaxRS/model.mustache @@ -17,10 +17,10 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { {{#vars} * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} **/ - private {{{datatype}}} {{name}} = {{{defaultValue}}};{{#allowableValues}} + private {{{datatype}}} {{name}} = {{{defaultValue}}};{{#isEnum}} - //{{^min}}public enum {{name}}Enum { {{#values}} {{.}}, {{/values}} }; - {{/min}}{{/allowableValues}}{{/vars}} + public enum {{datatype}} { {{#_enum}}{{.}}{{^-last}}, {{/-last}}{{/_enum}} }; + {{/isEnum}}{{/vars}} {{#vars}} @ApiModelProperty(required = {{required}}, value = "{{{description}}}") From a80af33260f9b0f60a34b3ed839bef9f168eb24e Mon Sep 17 00:00:00 2001 From: Martin Ehrnhoefer Date: Wed, 1 Oct 2014 17:10:26 +0200 Subject: [PATCH 055/325] [2.0 Spec] Java generator: Implement Enums #287 Very basic implementation --- src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 971acd4a51b9..b181366bcdbe 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -452,7 +452,7 @@ public class DefaultCodegen { } property.datatype = property.isEnum - ? StringUtils.capitalize(getTypeDeclaration(p)) + "Enum" + ? StringUtils.capitalize(property.name) + "Enum" : getTypeDeclaration(p); property.baseType = getSwaggerType(p); From 31ca832bdfff7802f7dc7a13e208881c159c0806 Mon Sep 17 00:00:00 2001 From: Martin Ehrnhoefer Date: Wed, 1 Oct 2014 17:42:03 +0200 Subject: [PATCH 056/325] [2.0 Spec] Java generator: Implement Enums #287 Unittest --- src/test/scala/Java/JavaModelEnumTest.scala | 33 +++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 src/test/scala/Java/JavaModelEnumTest.scala diff --git a/src/test/scala/Java/JavaModelEnumTest.scala b/src/test/scala/Java/JavaModelEnumTest.scala new file mode 100644 index 000000000000..25232b699075 --- /dev/null +++ b/src/test/scala/Java/JavaModelEnumTest.scala @@ -0,0 +1,33 @@ +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("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 From 1bce51de7aa9b51159a7aea85af21e51cb9c7a94 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 1 Oct 2014 22:11:51 -0700 Subject: [PATCH 057/325] updated imports --- src/main/resources/Java/api.mustache | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/resources/Java/api.mustache b/src/main/resources/Java/api.mustache index ae1d030955bf..ce5e5f665a4a 100644 --- a/src/main/resources/Java/api.mustache +++ b/src/main/resources/Java/api.mustache @@ -3,6 +3,8 @@ package {{package}}; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiInvoker; +import {{modelPackage}}.*; + {{#imports}}import {{import}}; {{/imports}} @@ -11,7 +13,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}} { From ffda821f688267621ff99160543696258e6a2e30 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 1 Oct 2014 22:12:18 -0700 Subject: [PATCH 058/325] updated imports --- src/main/resources/android-java/api.mustache | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/resources/android-java/api.mustache b/src/main/resources/android-java/api.mustache index 90eac11961da..d60f8a3d34bb 100644 --- a/src/main/resources/android-java/api.mustache +++ b/src/main/resources/android-java/api.mustache @@ -2,10 +2,14 @@ package {{package}}; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiInvoker; + +import {{modelPackage}}.*; + {{#imports}}import {{import}}; {{/imports}} -import java.util.*; +import java.util.Map; +import java.util.HashMap; import java.io.File; {{#operations}} From 48f8e16fb007eda30517bd80fdea207757a0c6e0 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 1 Oct 2014 22:12:50 -0700 Subject: [PATCH 059/325] added models support per #291 --- .../wordnik/swagger/codegen/CodegenModel.java | 4 ++-- .../wordnik/swagger/codegen/DefaultCodegen.java | 2 ++ .../swagger/codegen/DefaultGenerator.java | 17 ++++++++++++----- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index 776cce9cdc74..f6e635abee54 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -7,9 +7,9 @@ import java.util.*; public class CodegenModel { public String parent; - public String name, classname, description; + public String name, classname, description, classVarName, modelJson; public String defaultValue; public List vars = new ArrayList(); public Set imports = new HashSet(); - public Boolean hasVars, emptyVars; + public Boolean hasVars, emptyVars, hasMoreModels; } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 0074e21d7dcf..2285af6acb98 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -316,6 +316,8 @@ public class DefaultCodegen { m.name = name; m.description = model.getDescription(); m.classname = toModelName(name); + m.classVarName = toVarName(name); + m.modelJson = Json.pretty(model); int count = 0; if(model instanceof ArrayModel) { ArrayModel am = (ArrayModel) model; diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index c739dbed7bfe..1d25a828f326 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -34,21 +34,22 @@ public class DefaultGenerator implements Generator { } try { config.processOpts(); - Map models = null; + // models = null; List allOperations = new ArrayList(); - + List allModels = new ArrayList(); // models Map definitions = swagger.getDefinitions(); for(String name: definitions.keySet()) { Model model = definitions.get(name); Map modelMap = new HashMap(); modelMap.put(name, model); - models = processModels(config, modelMap); + 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() { @@ -58,7 +59,6 @@ public class DefaultGenerator implements Generator { }) .defaultValue("") .compile(template); - writeToFile(filename, tmpl.execute(models)); } } @@ -101,6 +101,13 @@ public class DefaultGenerator implements Generator { Map apis = new HashMap(); apis.put("apis", allOperations); bundle.put("apiInfo", apis); + bundle.put("models", allModels); + + for(int i = 0; i < allModels.size() - 1; i++) { + HashMap cm = (HashMap) allModels.get(i); + CodegenModel m = cm.get("model"); + m.hasMoreModels = true; + } for(SupportingFile support : config.supportingFiles()) { String outputFolder = config.outputFolder(); From 3c2845aaa629ac8a25e623bb6a6219549551be94 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 1 Oct 2014 23:21:59 -0700 Subject: [PATCH 060/325] updated file locations --- src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 1d25a828f326..962c2fab482a 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -102,6 +102,7 @@ public class DefaultGenerator implements Generator { apis.put("apis", allOperations); bundle.put("apiInfo", apis); bundle.put("models", allModels); + bundle.put("apiFolder", config.apiPackage().replaceAll("\\.", File.separator)); for(int i = 0; i < allModels.size() - 1; i++) { HashMap cm = (HashMap) allModels.get(i); From 178d7d19c4f2dee36a7aba0c15a1c72c862afb72 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 1 Oct 2014 23:22:39 -0700 Subject: [PATCH 061/325] added files --- src/main/resources/nodejs/README.mustache | 10 +++++ src/main/resources/nodejs/api.mustache | 52 ++++++++++++++++++++++ src/main/resources/nodejs/main.mustache | 47 +++++++++++++++++++ src/main/resources/nodejs/models.mustache | 3 ++ src/main/resources/nodejs/package.mustache | 16 +++++++ 5 files changed, 128 insertions(+) create mode 100644 src/main/resources/nodejs/README.mustache create mode 100644 src/main/resources/nodejs/api.mustache create mode 100644 src/main/resources/nodejs/main.mustache create mode 100644 src/main/resources/nodejs/models.mustache create mode 100755 src/main/resources/nodejs/package.mustache diff --git a/src/main/resources/nodejs/README.mustache b/src/main/resources/nodejs/README.mustache new file mode 100644 index 000000000000..881e7dd92c57 --- /dev/null +++ b/src/main/resources/nodejs/README.mustache @@ -0,0 +1,10 @@ +# 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/src/main/resources/nodejs/api.mustache b/src/main/resources/nodejs/api.mustache new file mode 100644 index 000000000000..93560fbe2ad7 --- /dev/null +++ b/src/main/resources/nodejs/api.mustache @@ -0,0 +1,52 @@ +var swagger = require("swagger-node-express"); +var url = require("url"); +var errors = swagger.errors; +var params = swagger.params; + +/* add model includes */ + +function writeResponse (response, data) { + response.header('Access-Control-Allow-Origin', "*"); + response.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); + response.header("Access-Control-Allow-Headers", "Content-Type"); + response.header("Content-Type", "application/json; charset=utf-8"); + response.send(JSON.stringify(data)); +} + +exports.models = models = require("../models.js"); + +{{#operations}} +{{#operation}} +exports.{{nickname}} = { + 'spec': { + "description" : "Operations about pets", + "path" : "{{path}}", + "notes" : "{{{notes}}}", + "summary" : "{{{summary}}}", + "method": "{{httpMethod}}", + "params" : [{{#queryParams}} + 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}} + params.header("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}} + {{/headerParams}}]).concat([{{#bodyParams}} + params.body("body", "{{swaggerDataType}}", "{{description}}", {{#required}}{{required}}{{/required}}{{^required}}false{{/required}}) + {{/bodyParams}}]), + "type" : "{{returnType}}", + "responseMessages" : [errors.invalid('id'), errors.notFound('{{returnType}}')], + "nickname" : "{{nickname}}" + }, + 'action': function (req,res) { + {{#requiredParamCount}} + {{#requiredParams}} + if (!req.params.{{baseName}}) { + throw errors.invalid('{{baseName}}'); + } + {{/requiredParams}} + {{/requiredParamCount}} + writeResponse(res, {message: "how about implementing {{nickname}} as a {{httpMethod}} method?"}); + } +}; +{{/operation}} +{{/operations}} \ No newline at end of file diff --git a/src/main/resources/nodejs/main.mustache b/src/main/resources/nodejs/main.mustache new file mode 100644 index 000000000000..6005108643da --- /dev/null +++ b/src/main/resources/nodejs/main.mustache @@ -0,0 +1,47 @@ +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 {{classname}} = require("./{{apiFolder}}/{{classname}}.js"); +{{/apis}} +{{/apiInfo}} + +swagger.addModels(models) + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}}.add{{httpMethod}}({{classname}}.{{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/src/main/resources/nodejs/models.mustache b/src/main/resources/nodejs/models.mustache new file mode 100644 index 000000000000..133fe7c15159 --- /dev/null +++ b/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/src/main/resources/nodejs/package.mustache b/src/main/resources/nodejs/package.mustache new file mode 100755 index 000000000000..322dc8199669 --- /dev/null +++ b/src/main/resources/nodejs/package.mustache @@ -0,0 +1,16 @@ +{ + "name": "{{{artifactId}}}", + "description": "Wordnik node.js server generator", + "version": "{{{artifactVersion}}}", + "homepage": "{{{homepage}}}", + "main": "./{{codeDir}}/main.js", + "engines": { + "node": ">= 0.8.x" + }, + "dependencies": { + "swagger-node-express": ">= 2.0.x", + "connect": ">= 1.8.x", + "cors": "2.1.1", + "express": "3.x" + } +} \ No newline at end of file From d5d1eb2833c77f8f91be583a259077df857a9b79 Mon Sep 17 00:00:00 2001 From: Martin Ehrnhoefer Date: Thu, 2 Oct 2014 08:55:29 +0200 Subject: [PATCH 062/325] Windows path problem fixed see #268, #269, #288 --- src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 962c2fab482a..a93187ba9403 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -102,7 +102,7 @@ public class DefaultGenerator implements Generator { apis.put("apis", allOperations); bundle.put("apiInfo", apis); bundle.put("models", allModels); - bundle.put("apiFolder", config.apiPackage().replaceAll("\\.", File.separator)); + bundle.put("apiFolder", config.apiPackage().replaceAll("\\.", "/")); for(int i = 0; i < allModels.size() - 1; i++) { HashMap cm = (HashMap) allModels.get(i); From b834ba436f4157630a775e35b1d1848d45529afb Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 2 Oct 2014 00:10:15 -0700 Subject: [PATCH 063/325] added nodejs server --- .../com/wordnik/swagger/codegen/Codegen.java | 2 + .../swagger/codegen/DefaultCodegen.java | 6 +- .../languages/NodeJSServerCodegen.java | 71 +++++++++++++++++++ src/main/resources/nodejs/api.mustache | 10 +++ src/main/resources/nodejs/main.mustache | 11 +-- 5 files changed, 89 insertions(+), 11 deletions(-) create mode 100644 src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index aafa9a85397d..0f1ed5da507e 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -69,6 +69,8 @@ public class Codegen extends DefaultGenerator { return new JavaClientCodegen(); else if("jaxrs".equals(name)) return new JaxRSServerCodegen(); + else if("nodejs".equals(name)) + return new NodeJSServerCodegen(); else if("static".equals(name)) return new StaticDocCodegen(); else if(name.indexOf(".") > 0) { diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 445455000eb9..43f4a5837882 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -413,8 +413,8 @@ public class DefaultCodegen { property.name = toVarName(name); property.baseName = name; property.description = p.getDescription(); - property.getter = "get" + name.substring(0, 1).toUpperCase() + name.substring(1); - property.setter = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); + property.getter = "get" + initialCaps(name); + property.setter = "set" + initialCaps(name); property.example = p.getExample(); property.defaultValue = toDefaultValue(p); @@ -508,7 +508,7 @@ public class DefaultCodegen { if(builder.toString().length() == 0) part = Character.toLowerCase(part.charAt(0)) + part.substring(1); else - part = Character.toUpperCase(part.charAt(0)) + part.substring(1); + part = initialCaps(part); builder.append(part); } } diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java new file mode 100644 index 000000000000..b30db030087a --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java @@ -0,0 +1,71 @@ +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 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 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.js")); + + 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 String apiFileFolder() { + return outputFolder + File.separator + apiPackage().replaceAll("\\.", File.separator); + } + + public String modelFileFolder() { + return outputFolder + File.separator + modelPackage().replaceAll("\\.", File.separator); + } + + @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/src/main/resources/nodejs/api.mustache b/src/main/resources/nodejs/api.mustache index 93560fbe2ad7..82f0145ce8e3 100644 --- a/src/main/resources/nodejs/api.mustache +++ b/src/main/resources/nodejs/api.mustache @@ -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/src/main/resources/nodejs/main.mustache b/src/main/resources/nodejs/main.mustache index 6005108643da..59265d99d093 100644 --- a/src/main/resources/nodejs/main.mustache +++ b/src/main/resources/nodejs/main.mustache @@ -23,7 +23,7 @@ app.use(cors(corsOptions)); swagger.setAppHandler(app); swagger.configureSwaggerPaths("", "api-docs", "") -var models = require("./models.js"); +var models = require("./app/models.js"); {{#apiInfo}} {{#apis}} @@ -32,13 +32,8 @@ var {{classname}} = require("./{{apiFolder}}/{{classname}}.js"); {{/apiInfo}} swagger.addModels(models) - {{#apiInfo}} - {{#apis}} - {{#operations}} - {{#operation}}.add{{httpMethod}}({{classname}}.{{nickname}}){{newline}}{{/operation}} - {{/operations}} - {{/apis}}; - {{/apiInfo}} + {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}.add{{httpMethod}}({{classname}}.{{nickname}}){{/operation}}{{/operations}} + {{/apis}}{{/apiInfo}}; // configures the app swagger.configure("http://localhost:8002", "0.1"); From 67d28e8b3cf41a9b10112eac600820e239d55d64 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 2 Oct 2014 00:10:39 -0700 Subject: [PATCH 064/325] added test --- .../staticDocs/StaticOperationTest.scala | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 src/test/scala/staticDocs/StaticOperationTest.scala diff --git a/src/test/scala/staticDocs/StaticOperationTest.scala b/src/test/scala/staticDocs/StaticOperationTest.scala new file mode 100644 index 000000000000..f46201faa5b2 --- /dev/null +++ b/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 From e771ed3332d508129af5022c49461f7e04cdfade Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 2 Oct 2014 00:18:36 -0700 Subject: [PATCH 065/325] added scheme, host, basePath per #295 --- .../wordnik/swagger/codegen/DefaultGenerator.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index a93187ba9403..f560b660b153 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -34,7 +34,16 @@ public class DefaultGenerator implements Generator { } try { config.processOpts(); - // models = null; + + StringBuilder hostBuilder = new StringBuilder(); + if(swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { + hostBuilder.append(swagger.getSchemes().get(0)); + 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 @@ -67,6 +76,7 @@ public class DefaultGenerator implements Generator { 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()); From 5024e0bbda02d348cb6eacaf3e0c18baf07771d6 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 2 Oct 2014 00:32:15 -0700 Subject: [PATCH 066/325] added root checking per #279 --- src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 43f4a5837882..c923ca578d66 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -502,6 +502,10 @@ public class DefaultCodegen { path = path.replaceAll("\\}", ""); String[] parts = (path + "/" + httpMethod).split("/"); StringBuilder builder = new StringBuilder(); + if("/".equals(path)) { + // must be root path + builder.append("root"); + } for(int i = 0; i < parts.length; i++) { String part = parts[i]; if(part.length() > 0) { From b87bc2a908710b85a22f47bba747f854160c1786 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 10 Oct 2014 21:25:19 -0700 Subject: [PATCH 067/325] added scalatra --- src/main/java/com/wordnik/swagger/codegen/Codegen.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/wordnik/swagger/codegen/Codegen.java b/src/main/java/com/wordnik/swagger/codegen/Codegen.java index 0f1ed5da507e..67f1e445e2ed 100644 --- a/src/main/java/com/wordnik/swagger/codegen/Codegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/Codegen.java @@ -71,6 +71,8 @@ public class Codegen extends DefaultGenerator { return new JaxRSServerCodegen(); else if("nodejs".equals(name)) return new NodeJSServerCodegen(); + else if("scalatra".equals(name)) + return new ScalatraServerCodegen(); else if("static".equals(name)) return new StaticDocCodegen(); else if(name.indexOf(".") > 0) { From 97623af8df7c1353559a0e96e5c7fec60321c24c Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 10 Oct 2014 21:26:07 -0700 Subject: [PATCH 068/325] added apiInfo --- .../swagger/codegen/CodegenParameter.java | 2 +- .../swagger/codegen/DefaultCodegen.java | 2 + .../swagger/codegen/DefaultGenerator.java | 22 +++ .../languages/ScalatraServerCodegen.java | 152 ++++++++++++++++++ 4 files changed, 177 insertions(+), 1 deletion(-) create mode 100644 src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java diff --git a/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java index d8894fed3098..3c3fbd10e5bd 100644 --- a/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java +++ b/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java @@ -2,6 +2,6 @@ package com.wordnik.swagger.codegen; public class CodegenParameter { public Boolean hasMore = null, isContainer = null, secondaryParam = null; - public String baseName, paramName, dataType, collectionFormat, description; + public String baseName, paramName, dataType, collectionFormat, description, baseType; public Boolean isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam; } \ No newline at end of file diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index c923ca578d66..4b2783e34688 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -644,6 +644,8 @@ public class DefaultCodegen { Property inner = qp.getItems(); property = new ArrayProperty(inner); collectionFormat = qp.getCollectionFormat(); + CodegenProperty pr = fromProperty("aaa", inner); + p.baseType = pr.datatype; } else property = PropertyBuilder.build(qp.getType(), qp.getFormat(), null); diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index f560b660b153..7e2cc186cb47 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -34,6 +34,28 @@ public class DefaultGenerator implements Generator { } 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()); + // + // licenseUrl + } + } StringBuilder hostBuilder = new StringBuilder(); if(swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java new file mode 100644 index 000000000000..2abf95c656a3 --- /dev/null +++ b/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java @@ -0,0 +1,152 @@ +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 ScalatraServerCodegen() { + super(); + outputFolder = "generated-code/scalatra"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "src/main/resources/scalatra"; + apiPackage = "com.wordnik.client.api"; + modelPackage = "com.wordnik.client.model"; + + defaultIncludes = new HashSet( + Arrays.asList("double", + "int", + "long", + "short", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "List", + "Set", + "Map") + ); + + 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().replaceAll("\\.", "/"); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replaceAll("\\.", "/"); + } + + @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(); + } + Json.prettyPrint(objs); + 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 From 4d214dbcefdc4a5a22ff8d41e3ccd4c954607335 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 10 Oct 2014 21:39:45 -0700 Subject: [PATCH 069/325] updated client --- src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java | 2 +- .../swagger/codegen/languages/ScalatraServerCodegen.java | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index 4b2783e34688..7fa227240816 100644 --- a/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -644,7 +644,7 @@ public class DefaultCodegen { Property inner = qp.getItems(); property = new ArrayProperty(inner); collectionFormat = qp.getCollectionFormat(); - CodegenProperty pr = fromProperty("aaa", inner); + CodegenProperty pr = fromProperty("inner", inner); p.baseType = pr.datatype; } else diff --git a/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java b/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java index 2abf95c656a3..6e923f348ed1 100644 --- a/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/src/main/java/com/wordnik/swagger/codegen/languages/ScalatraServerCodegen.java @@ -115,7 +115,6 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf for(CodegenOperation op: operationList) { op.httpMethod = op.httpMethod.toLowerCase(); } - Json.prettyPrint(objs); return objs; } From 5a70550a3729a149708fa49264fee25b4b23e6c1 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 10 Oct 2014 21:41:21 -0700 Subject: [PATCH 070/325] added scalatra support --- .../resources/scalatra/Bootstrap.mustache | 20 + src/main/resources/scalatra/JettyMain.scala | 32 ++ src/main/resources/scalatra/JsonUtil.scala | 12 + src/main/resources/scalatra/README.mustache | 10 + .../resources/scalatra/ServletApp.mustache | 39 ++ src/main/resources/scalatra/api.mustache | 94 ++++ src/main/resources/scalatra/build.sbt | 59 ++ src/main/resources/scalatra/model.mustache | 15 + .../scalatra/project/build.properties | 1 + .../resources/scalatra/project/plugins.sbt | 7 + src/main/resources/scalatra/sbt | 518 ++++++++++++++++++ src/main/resources/scalatra/web.xml | 17 + .../swagger-static/operation.mustache | 22 + swagger.json | 279 +++++----- 14 files changed, 996 insertions(+), 129 deletions(-) create mode 100644 src/main/resources/scalatra/Bootstrap.mustache create mode 100644 src/main/resources/scalatra/JettyMain.scala create mode 100644 src/main/resources/scalatra/JsonUtil.scala create mode 100644 src/main/resources/scalatra/README.mustache create mode 100644 src/main/resources/scalatra/ServletApp.mustache create mode 100644 src/main/resources/scalatra/api.mustache create mode 100644 src/main/resources/scalatra/build.sbt create mode 100644 src/main/resources/scalatra/model.mustache create mode 100644 src/main/resources/scalatra/project/build.properties create mode 100644 src/main/resources/scalatra/project/plugins.sbt create mode 100755 src/main/resources/scalatra/sbt create mode 100644 src/main/resources/scalatra/web.xml diff --git a/src/main/resources/scalatra/Bootstrap.mustache b/src/main/resources/scalatra/Bootstrap.mustache new file mode 100644 index 000000000000..64c0b07eb283 --- /dev/null +++ b/src/main/resources/scalatra/Bootstrap.mustache @@ -0,0 +1,20 @@ +import {{apiPackage}}._ +import akka.actor.ActorSystem +import com.wordnik.swagger.app.{ResourcesApp, SwaggerApp} +import javax.servlet.ServletContext +import org.scalatra.LifeCycle + +class ScalatraBootstrap extends LifeCycle { + implicit val swagger = new SwaggerApp + + override def init(context: ServletContext) { + implicit val system = ActorSystem("appActorSystem") + try { + {{#apiInfo}}{{#apis}}context mount (new {{classname}}, "/{{baseName}}/*") + {{/apis}}{{/apiInfo}} + context mount (new ResourcesApp, "/api-docs/*") + } catch { + case e: Throwable => e.printStackTrace() + } + } +} \ No newline at end of file diff --git a/src/main/resources/scalatra/JettyMain.scala b/src/main/resources/scalatra/JettyMain.scala new file mode 100644 index 000000000000..ec73dd228164 --- /dev/null +++ b/src/main/resources/scalatra/JettyMain.scala @@ -0,0 +1,32 @@ +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/src/main/resources/scalatra/JsonUtil.scala b/src/main/resources/scalatra/JsonUtil.scala new file mode 100644 index 000000000000..691a82f563b7 --- /dev/null +++ b/src/main/resources/scalatra/JsonUtil.scala @@ -0,0 +1,12 @@ +package json + +import com.fasterxml.jackson.module.scala.DefaultScalaModule +import com.fasterxml.jackson.core.JsonGenerator.Feature +import com.fasterxml.jackson.databind._ + +object JsonUtil { + val mapper = new ObjectMapper() + mapper.registerModule(new DefaultScalaModule()) + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) +} \ No newline at end of file diff --git a/src/main/resources/scalatra/README.mustache b/src/main/resources/scalatra/README.mustache new file mode 100644 index 000000000000..f8a560b776f5 --- /dev/null +++ b/src/main/resources/scalatra/README.mustache @@ -0,0 +1,10 @@ +# 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 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) \ No newline at end of file diff --git a/src/main/resources/scalatra/ServletApp.mustache b/src/main/resources/scalatra/ServletApp.mustache new file mode 100644 index 000000000000..f6e53468ec9d --- /dev/null +++ b/src/main/resources/scalatra/ServletApp.mustache @@ -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( + """{{{appName}}}""", + """{{{appDescription}}}""", + """{{{infoUrl}}}""", + """{{{infoEmail}}}""", + """{{{licenseInfo}}}""", + """{{{licenseUrl}}}""") +} \ No newline at end of file diff --git a/src/main/resources/scalatra/api.mustache b/src/main/resources/scalatra/api.mustache new file mode 100644 index 000000000000..54710361fe9a --- /dev/null +++ b/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/src/main/resources/scalatra/build.sbt b/src/main/resources/scalatra/build.sbt new file mode 100644 index 000000000000..9f04adc46ba6 --- /dev/null +++ b/src/main/resources/scalatra/build.sbt @@ -0,0 +1,59 @@ +import AssemblyKeys._ // put this at the top of the file + +import NativePackagerKeys._ + +packageArchetype.java_server + +assemblySettings + +scalariformSettings + +organization := "com.wordnik" + +seq(webSettings :_*) + +mainClass in assembly := Some("JettyMain") + +name := "scalatra-sample" + +version := "0.1.0-SNAPSHOT" + +scalaVersion := "2.10.0" + +libraryDependencies ++= Seq( + "org.scalatest" %% "scalatest" % "2.0" % "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", + "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", + "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar")) +) + +resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository" + +resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/" + +resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/" + +ivyXML := + + + + + +mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) => + { + case "about.html" => MergeStrategy.discard + case x => old(x) + } +} diff --git a/src/main/resources/scalatra/model.mustache b/src/main/resources/scalatra/model.mustache new file mode 100644 index 000000000000..8c5d19546622 --- /dev/null +++ b/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/src/main/resources/scalatra/project/build.properties b/src/main/resources/scalatra/project/build.properties new file mode 100644 index 000000000000..8cbb5226c451 --- /dev/null +++ b/src/main/resources/scalatra/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.13.0 \ No newline at end of file diff --git a/src/main/resources/scalatra/project/plugins.sbt b/src/main/resources/scalatra/project/plugins.sbt new file mode 100644 index 000000000000..94de8e5414fa --- /dev/null +++ b/src/main/resources/scalatra/project/plugins.sbt @@ -0,0 +1,7 @@ +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/src/main/resources/scalatra/sbt b/src/main/resources/scalatra/sbt new file mode 100755 index 000000000000..491debf4fb3f --- /dev/null +++ b/src/main/resources/scalatra/sbt @@ -0,0 +1,518 @@ +#!/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 < + + + org.scalatra.servlet.ScalatraListener + + + + default + /*.html + /css/* + /js/*.js + /images/* + + diff --git a/src/main/resources/swagger-static/operation.mustache b/src/main/resources/swagger-static/operation.mustache index 88db8645de83..d0e35f1b2963 100644 --- a/src/main/resources/swagger-static/operation.mustache +++ b/src/main/resources/swagger-static/operation.mustache @@ -18,9 +18,31 @@