diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000000..7cb0b92be50 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,3 @@ +language: scala +scala: + - 2.10.2 diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000000..9f93e067e8e --- /dev/null +++ b/LICENSE @@ -0,0 +1,11 @@ +Copyright 2014 Reverb Technologies, Inc. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at [apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0) + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/README.md b/README.md index 3b42286f64c..f1dcbc5514c 100644 --- a/README.md +++ b/README.md @@ -1,9 +1,18 @@ # 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. You can find out more about both the spec and the framework at -http://swagger.wordnik.com. For more information about Wordnik's APIs, please visit http://developer.wordnik.com. +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: @@ -63,7 +72,7 @@ Other languages have petstore samples, too: 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/resources.json special-key +./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`. @@ -222,7 +231,7 @@ either repackage the library OR modify your codegen script to use a file path! License ------- -Copyright 2013 Wordnik, Inc. +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. diff --git a/bin/Version.scala b/bin/Version.scala index 8607187f845..d25fe6f9bb7 100644 --- a/bin/Version.scala +++ b/bin/Version.scala @@ -1,5 +1,7 @@ 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 e: String => e } -println(version) \ No newline at end of file +println(version) diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh new file mode 100755 index 00000000000..716db5bae15 --- /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-wordnik-api.sh b/bin/android-java-wordnik-api.sh new file mode 100755 index 00000000000..881f55c835e --- /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/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.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 index 44090ab0632..d53e746366a 100755 --- a/bin/runscala.sh +++ b/bin/runscala.sh @@ -1,7 +1,6 @@ #!/bin/sh SCRIPT="$0" -SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -19,6 +18,7 @@ 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. @@ -26,7 +26,7 @@ export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/ ags="$@" if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then - scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags + scala -cp $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.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 index 5884a3479b3..963d4734ca3 100755 --- a/bin/static-docs.sh +++ b/bin/static-docs.sh @@ -22,8 +22,8 @@ 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" -ags="$@ SwaggerDocGenerator http://developer.wordnik.com/v4/resources.json" +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files/resources.json" +ags="$@ SwaggerDocGenerator https://api.wordnik.com/v4/resources.json" if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags diff --git a/bin/yml2swagger.js b/bin/yml2swagger.js new file mode 100644 index 00000000000..2f4cce90a71 --- /dev/null +++ b/bin/yml2swagger.js @@ -0,0 +1,56 @@ +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 index 8ce46eac954..0c2599edde7 100644 --- a/build.sbt +++ b/build.sbt @@ -5,22 +5,24 @@ organization := "com.wordnik" name := "swagger-codegen" -version := "2.0.11" +version := "2.0.14" -scalaVersion := "2.9.1" +scalaVersion := "2.10.0" + +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.9.0", "2.9.0-1", "2.9.1", "2.9.1-1", "2.9.2", "2.9.3", "2.10.0") +crossScalaVersions := Seq("2.9.0", "2.9.0-1", "2.9.1", "2.9.1-1", "2.9.2", "2.9.3", "2.10.0", "2.10.1", "2.10.2") libraryDependencies ++= Seq( "org.json4s" %% "json4s-jackson" % "3.2.5", "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.4", + "org.rogach" %% "scallop" % "0.8.1", "junit" % "junit" % "4.11" % "test", "org.scalatest" %% "scalatest" % "1.9.1" % "test" ) @@ -28,8 +30,16 @@ libraryDependencies ++= Seq( 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") => + case v if v.startsWith("2.10") => { "org.fusesource.scalate" %% "scalate-core" % "1.6.1" + } +} + +libraryDependencies ++= { + scalaVersion.toString match { + case v if v.startsWith("2.10") => Seq("org.scala-lang" % "scala-reflect" % v) + case _ => Seq() + } } packageOptions <+= (name, version, organization) map { @@ -55,9 +65,13 @@ publishTo <<= (version) { version: String => 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"))) -//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 diff --git a/package.json b/package.json new file mode 100644 index 00000000000..ea21c211095 --- /dev/null +++ b/package.json @@ -0,0 +1,16 @@ +{ + "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/plugins.sbt b/project/plugins.sbt index 4409dd0a68c..653d01424af 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,2 +1,3 @@ +addSbtPlugin("com.typesafe.sbt" % "sbt-pgp" % "0.8") addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.9.1") diff --git a/samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala b/samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala index 2be7f229b84..bc441275a6f 100644 --- a/samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala +++ b/samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala @@ -14,13 +14,13 @@ * limitations under the License. */ -import com.wordnik.swagger.codegen.BasicJavaGenerator +import com.wordnik.swagger.codegen.BasicAndroidJavaGenerator -object AndroidJavaPetstoreCodegen extends BasicJavaGenerator { +object AndroidJavaPetstoreCodegen extends BasicAndroidJavaGenerator { def main(args: Array[String]) = generateClient(args) // location of templates - override def templateDir = "android-java" + override def templateDir = "src/main/resources/android-java" // where to write generated code override def destinationDir = "samples/client/petstore/android-java/src/main/java" 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 index c620cd42599..c9e33d53512 100644 --- 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 @@ -27,6 +27,10 @@ public class PetApi { } 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())); @@ -34,10 +38,6 @@ public class PetApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -58,6 +58,10 @@ public class PetApi { } } 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())); @@ -65,10 +69,6 @@ public class PetApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -89,6 +89,10 @@ public class PetApi { } } 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())); @@ -96,10 +100,6 @@ public class PetApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(petId == null || body == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -120,6 +120,10 @@ public class PetApi { } } 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())); @@ -127,10 +131,6 @@ public class PetApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -178,6 +178,10 @@ public class PetApi { } } 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"); @@ -185,10 +189,6 @@ public class PetApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -209,6 +209,10 @@ public class PetApi { } } 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"); @@ -216,10 +220,6 @@ public class PetApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -240,6 +240,10 @@ public class PetApi { } } 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"); @@ -247,10 +251,6 @@ public class PetApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(status == null ) { - throw new ApiException(400, "missing required params"); - } if(!"null".equals(String.valueOf(status))) queryParams.put("status", String.valueOf(status)); String contentType = "application/json"; @@ -273,6 +273,10 @@ public class PetApi { } } 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"); @@ -280,10 +284,6 @@ public class PetApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(tags == null ) { - throw new ApiException(400, "missing required params"); - } if(!"null".equals(String.valueOf(tags))) queryParams.put("tags", String.valueOf(tags)); String contentType = "application/json"; diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/StoreApi.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/StoreApi.java index ea2fd613818..12076bf43dd 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/petstore/api/StoreApi.java @@ -26,6 +26,10 @@ public class StoreApi { } 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())); @@ -33,10 +37,6 @@ public class StoreApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(orderId == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -57,6 +57,10 @@ public class StoreApi { } } public void deleteOrder (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())); @@ -64,10 +68,6 @@ public class StoreApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(orderId == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -88,6 +88,10 @@ public class StoreApi { } } public void placeOrder (Order 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 = "/store/order".replaceAll("\\{format\\}","json"); @@ -95,10 +99,6 @@ public class StoreApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { diff --git a/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/UserApi.java b/samples/client/petstore/android-java/src/main/java/com/wordnik/petstore/api/UserApi.java index 505f1245ce1..56ed2a8e038 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/petstore/api/UserApi.java @@ -26,6 +26,10 @@ public class UserApi { } 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"); @@ -33,10 +37,6 @@ public class UserApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -57,6 +57,10 @@ public class UserApi { } } 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"); @@ -64,10 +68,6 @@ public class UserApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -88,6 +88,10 @@ public class UserApi { } } 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"); @@ -95,10 +99,6 @@ public class UserApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -119,6 +119,10 @@ public class UserApi { } } 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"); + } // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); @@ -126,10 +130,6 @@ public class UserApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(username == null || body == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -150,6 +150,10 @@ public class UserApi { } } public void deleteUser (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())); @@ -157,10 +161,6 @@ public class UserApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(username == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -181,6 +181,10 @@ public class UserApi { } } 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())); @@ -188,10 +192,6 @@ public class UserApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(username == null ) { - throw new ApiException(400, "missing required params"); - } String contentType = "application/json"; try { @@ -212,6 +212,10 @@ public class UserApi { } } 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"); @@ -219,10 +223,6 @@ public class UserApi { Map queryParams = new HashMap(); Map headerParams = new HashMap(); - // verify required params are set - if(username == null || password == null ) { - throw new ApiException(400, "missing required params"); - } if(!"null".equals(String.valueOf(username))) queryParams.put("username", String.valueOf(username)); if(!"null".equals(String.valueOf(password))) diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/PetApi.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/PetApi.cs index 733e22f12db..f56b2b02070 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/PetApi.cs @@ -21,6 +21,38 @@ return basePath; } + /// + /// uploads an image + /// + /// Additional data to pass to server + /// file to upload + /// + public void uploadFile (string additionalMetadata, File body) { + // create path and map variables + var path = "/pet/uploadImage".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + + string paramStr = null; + try { + var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } /// /// Find pet by ID Returns a pet based on ID /// @@ -97,7 +129,7 @@ /// ID of pet that needs to be fetched /// Pet object that needs to be added to the store /// - public Array partialUpdate (string petId, Pet body) { + public List partialUpdate (string petId, Pet body) { // create path and map variables var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString())); @@ -113,7 +145,7 @@ try { var response = apiInvoker.invokeAPI(basePath, path, "PATCH", queryParams, body, headerParams); if(response != null){ - return (Array) ApiInvoker.deserialize(response, typeof(Array)); + return (List) ApiInvoker.deserialize(response, typeof(List)); } else { return null; @@ -165,38 +197,6 @@ } } /// - /// uploads an image - /// - /// Additional data to pass to server - /// file to upload - /// - public void uploadFile (string additionalMetadata, File body) { - // create path and map variables - var path = "/pet/uploadImage".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// /// Add a new pet to the store /// /// Pet object that needs to be added to the store @@ -271,7 +271,7 @@ /// /// Status values that need to be considered for filter /// - public Array findPetsByStatus (string status) { + public List findPetsByStatus (string status) { // create path and map variables var path = "/pet/findByStatus".Replace("{format}","json"); @@ -291,7 +291,7 @@ try { var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); if(response != null){ - return (Array) ApiInvoker.deserialize(response, typeof(Array)); + return (List) ApiInvoker.deserialize(response, typeof(List)); } else { return null; @@ -310,7 +310,7 @@ /// /// Tags to filter by /// - public Array findPetsByTags (string tags) { + public List findPetsByTags (string tags) { // create path and map variables var path = "/pet/findByTags".Replace("{format}","json"); @@ -330,7 +330,7 @@ try { var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); if(response != null){ - return (Array) ApiInvoker.deserialize(response, typeof(Array)); + return (List) ApiInvoker.deserialize(response, typeof(List)); } else { return null; diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/StoreApi.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/StoreApi.cs index 22c36a411ca..c085d9c07ac 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/StoreApi.cs @@ -21,41 +21,6 @@ return basePath; } - /// - /// Find purchase order by ID For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors - /// - /// ID of pet that needs to be fetched - /// - public Order getOrderById (string orderId) { - // create path and map variables - var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.escapeString(orderId.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (orderId == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); - if(response != null){ - return (Order) ApiInvoker.deserialize(response, typeof(Order)); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } - } - } /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// @@ -92,6 +57,41 @@ } } /// + /// Find purchase order by ID For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors + /// + /// ID of pet that needs to be fetched + /// + public Order getOrderById (string orderId) { + // create path and map variables + var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.escapeString(orderId.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + + // verify required params are set + if (orderId == null ) { + throw new ApiException(400, "missing required params"); + } + string paramStr = null; + try { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + if(response != null){ + return (Order) ApiInvoker.deserialize(response, typeof(Order)); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + /// /// Place an order for a pet /// /// order placed for purchasing the pet diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/UserApi.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/UserApi.cs index bde3ed4af4b..a9c94195151 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/UserApi.cs @@ -21,6 +21,186 @@ return basePath; } + /// + /// Delete user This can only be done by the logged in user. + /// + /// The name that needs to be deleted + /// + public void deleteUser (string username) { + // create path and map variables + var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(username.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + + // verify required params are set + if (username == null ) { + throw new ApiException(400, "missing required params"); + } + string paramStr = null; + try { + var response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + /// + /// Get user by user name + /// + /// The name that needs to be fetched. Use user1 for testing. + /// + public User getUserByName (string username) { + // create path and map variables + var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(username.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + + // verify required params are set + if (username == null ) { + throw new ApiException(400, "missing required params"); + } + string paramStr = null; + try { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + if(response != null){ + return (User) ApiInvoker.deserialize(response, typeof(User)); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + /// + /// Updated user This can only be done by the logged in user. + /// + /// name that need to be deleted + /// Updated user object + /// + public void updateUser (string username, User body) { + // create path and map variables + var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(username.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + + // verify required params are set + if (username == null || body == null ) { + throw new ApiException(400, "missing required params"); + } + string paramStr = null; + try { + var response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + /// + /// Logs user into the system + /// + /// The user name for login + /// The password for login in clear text + /// + public string loginUser (string username, string password) { + // create path and map variables + var path = "/user/login".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + + // verify required params are set + if (username == null || password == null ) { + throw new ApiException(400, "missing required params"); + } + string paramStr = null; + if (username != null){ + paramStr = (username != null && username is DateTime) ? ((DateTime)(object)username).ToString("u") : Convert.ToString(username); + queryParams.Add("username", paramStr); + } + if (password != null){ + paramStr = (password != null && password is DateTime) ? ((DateTime)(object)password).ToString("u") : Convert.ToString(password); + queryParams.Add("password", paramStr); + } + try { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + if(response != null){ + return (string) ApiInvoker.deserialize(response, typeof(string)); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + /// + /// Logs out current logged in user session + /// + /// + public void logoutUser () { + // create path and map variables + var path = "/user/logout".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + + string paramStr = null; + try { + var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } /// /// Create user This can only be done by the logged in user. /// @@ -126,185 +306,5 @@ } } } - /// - /// Updated user This can only be done by the logged in user. - /// - /// name that need to be deleted - /// Updated user object - /// - public void updateUser (string username, User body) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(username.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (username == null || body == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// Delete user This can only be done by the logged in user. - /// - /// The name that needs to be deleted - /// - public void deleteUser (string username) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(username.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (username == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } - /// - /// Get user by user name - /// - /// The name that needs to be fetched. Use user1 for testing. - /// - public User getUserByName (string username) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.escapeString(username.ToString())); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (username == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); - if(response != null){ - return (User) ApiInvoker.deserialize(response, typeof(User)); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } - } - } - /// - /// Logs user into the system - /// - /// The user name for login - /// The password for login in clear text - /// - public string loginUser (string username, string password) { - // create path and map variables - var path = "/user/login".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - // verify required params are set - if (username == null || password == null ) { - throw new ApiException(400, "missing required params"); - } - string paramStr = null; - if (username != null){ - paramStr = (username != null && username is DateTime) ? ((DateTime)(object)username).ToString("u") : Convert.ToString(username); - queryParams.Add("username", paramStr); - } - if (password != null){ - paramStr = (password != null && password is DateTime) ? ((DateTime)(object)password).ToString("u") : Convert.ToString(password); - queryParams.Add("password", paramStr); - } - try { - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); - if(response != null){ - return (string) ApiInvoker.deserialize(response, typeof(string)); - } - else { - return null; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return null; - } - else { - throw ex; - } - } - } - /// - /// Logs out current logged in user session - /// - /// - public void logoutUser () { - // create path and map variables - var path = "/user/logout".Replace("{format}","json"); - - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - - string paramStr = null; - try { - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { - return ; - } - else { - throw ex; - } - } - } } } diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Category.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Category.cs index e5aa324be6c..dfad92a046f 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Category.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Category.cs @@ -5,10 +5,8 @@ using System.Collections.Generic; namespace Com.Wordnik.Petstore.Model { public class Category { - /* Category unique identifier */ public long id { get; set; } - /* Name of the category */ public string name { get; set; } public override string ToString() { diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Order.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Order.cs index d4d5a0d77a1..ae5012193e7 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Order.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Order.cs @@ -5,19 +5,15 @@ using System.Collections.Generic; namespace Com.Wordnik.Petstore.Model { public class Order { - /* Unique identifier for the order */ public long id { get; set; } - /* ID of pet being ordered */ public long petId { get; set; } - /* Number of pets ordered */ public int quantity { get; set; } - /* Status of the order */ + /* Order Status */ public string status { get; set; } - /* Date shipped, only if it has been */ public DateTime shipDate { get; set; } public override string ToString() { diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Pet.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Pet.cs index 87bca18a1f4..8bd8f260601 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Pet.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Pet.cs @@ -5,19 +5,15 @@ using System.Collections.Generic; namespace Com.Wordnik.Petstore.Model { public class Pet { - /* Unique identifier for the Pet */ + /* unique identifier for the pet */ public long id { get; set; } - /* Category the pet is in */ public Category category { get; set; } - /* Friendly name of the pet */ public string name { get; set; } - /* Image URLs */ public List photoUrls { get; set; } - /* Tags assigned to this pet */ public List tags { get; set; } /* pet status in the store */ diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Tag.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Tag.cs index 8a4b38b656b..61187fbd772 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Tag.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Tag.cs @@ -5,10 +5,8 @@ using System.Collections.Generic; namespace Com.Wordnik.Petstore.Model { public class Tag { - /* Unique identifier for the tag */ public long id { get; set; } - /* Friendly name for the tag */ public string name { get; set; } public override string ToString() { diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/User.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/User.cs index adce974f71f..bbbd6eaccc3 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/User.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/User.cs @@ -5,25 +5,18 @@ using System.Collections.Generic; namespace Com.Wordnik.Petstore.Model { public class User { - /* Unique identifier for the user */ public long id { get; set; } - /* Unique username */ - public string username { get; set; } - - /* First name of the user */ public string firstName { get; set; } - /* Last name of the user */ + public string username { get; set; } + public string lastName { get; set; } - /* Email address of the user */ public string email { get; set; } - /* Password name of the user */ public string password { get; set; } - /* Phone number of the user */ public string phone { get; set; } /* User Status */ @@ -33,8 +26,8 @@ namespace Com.Wordnik.Petstore.Model { var sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" id: ").Append(id).Append("\n"); - sb.Append(" username: ").Append(username).Append("\n"); sb.Append(" firstName: ").Append(firstName).Append("\n"); + sb.Append(" username: ").Append(username).Append("\n"); sb.Append(" lastName: ").Append(lastName).Append("\n"); sb.Append(" email: ").Append(email).Append("\n"); sb.Append(" password: ").Append(password).Append("\n"); diff --git a/samples/client/petstore/java/JavaPetstoreCodegen.scala b/samples/client/petstore/java/JavaPetstoreCodegen.scala index bd9b068c12a..3afebc87f40 100644 --- a/samples/client/petstore/java/JavaPetstoreCodegen.scala +++ b/samples/client/petstore/java/JavaPetstoreCodegen.scala @@ -20,7 +20,7 @@ object JavaPetstoreCodegen extends BasicJavaGenerator { def main(args: Array[String]) = generateClient(args) // location of templates - override def templateDir = "Java" + override def templateDir = "src/main/resources/Java" // where to write generated code override def destinationDir = "samples/client/petstore/java/src/main/java" diff --git a/samples/client/petstore/java/pom.xml b/samples/client/petstore/java/pom.xml index 63bfe1612b5..51011d64065 100644 --- a/samples/client/petstore/java/pom.xml +++ b/samples/client/petstore/java/pom.xml @@ -178,6 +178,17 @@ ${jackson-version} compile + + com.fasterxml.jackson.datatype + jackson-datatype-joda + 2.1.5 + + + joda-time + joda-time + ${jodatime-version} + compile + @@ -203,6 +214,7 @@ 1.7 2.1.4 + 2.3 2.9.1-1 4.8.1 1.0.0 diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/client/ApiInvoker.java b/samples/client/petstore/java/src/main/java/com/wordnik/client/ApiInvoker.java index 955ffe39f6e..0a163d80d40 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/client/ApiInvoker.java +++ b/samples/client/petstore/java/src/main/java/com/wordnik/client/ApiInvoker.java @@ -12,12 +12,15 @@ import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; +import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; import java.util.Map; import java.util.HashMap; import java.util.List; import java.io.IOException; +import java.net.URLEncoder; +import java.io.UnsupportedEncodingException; public class ApiInvoker { private static ApiInvoker INSTANCE = new ApiInvoker(); @@ -27,13 +30,18 @@ public class ApiInvoker { public static ApiInvoker getInstance() { return INSTANCE; } - + public void addDefaultHeader(String key, String value) { defaultHeaderMap.put(key, value); } public String escapeString(String str) { - return str; + try{ + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } + catch(UnsupportedEncodingException e) { + return str; + } } public static Object deserialize(String json, String containerType, Class cls) throws ApiException { @@ -46,7 +54,7 @@ public class ApiInvoker { else if(String.class.equals(cls)) { if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) return json.substring(1, json.length() - 2); - else + else return json; } else { @@ -60,9 +68,9 @@ public class ApiInvoker { public static String serialize(Object obj) throws ApiException { try { - if (obj != null) + if (obj != null) return JsonUtil.getJsonMapper().writeValueAsString(obj); - else + else return null; } catch (Exception e) { @@ -70,11 +78,11 @@ public class ApiInvoker { } } - public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, String contentType) throws ApiException { + public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { Client client = getClient(host); StringBuilder b = new StringBuilder(); - + for(String key : queryParams.keySet()) { String value = queryParams.get(key); if (value != null){ @@ -91,7 +99,7 @@ public class ApiInvoker { for(String key : headerParams.keySet()) { builder.header(key, headerParams.get(key)); } - + for(String key : defaultHeaderMap.keySet()) { if(!headerParams.containsKey(key)) { builder.header(key, defaultHeaderMap.get(key)); @@ -106,30 +114,55 @@ public class ApiInvoker { if(body == null) response = builder.post(ClientResponse.class, serialize(body)); else - response = builder.type("application/json").post(ClientResponse.class, serialize(body)); + response = builder.type(contentType).post(ClientResponse.class, serialize(body)); } else if ("PUT".equals(method)) { if(body == null) response = builder.put(ClientResponse.class, serialize(body)); - else - response = builder.type("application/json").put(ClientResponse.class, serialize(body)); + else { + if("application/x-www-form-urlencoded".equals(contentType)) { + StringBuilder formParamBuilder = new StringBuilder(); + + // encode the form params + for(String key : headerParams.keySet()) { + String value = headerParams.get(key); + if(value != null && !"".equals(value.trim())) { + if(formParamBuilder.length() > 0) { + formParamBuilder.append("&"); + } + try { + formParamBuilder.append(URLEncoder.encode(key, "utf8")).append("=").append(URLEncoder.encode(value, "utf8")); + } + catch (Exception e) { + // move on to next + } + } + } + response = builder.type(contentType).put(ClientResponse.class, formParamBuilder.toString()); + } + else + response = builder.type(contentType).put(ClientResponse.class, serialize(body)); + } } else if ("DELETE".equals(method)) { if(body == null) response = builder.delete(ClientResponse.class, serialize(body)); else - response = builder.type("application/json").delete(ClientResponse.class, serialize(body)); + response = builder.type(contentType).delete(ClientResponse.class, serialize(body)); } else { throw new ApiException(500, "unknown method type " + method); } - if(response.getClientResponseStatus() == ClientResponse.Status.OK) { + if(response.getClientResponseStatus() == ClientResponse.Status.NO_CONTENT) { + return null; + } + else if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) { return (String) response.getEntity(String.class); } else { throw new ApiException( response.getClientResponseStatus().getStatusCode(), - response.getEntity(String.class)); + response.getEntity(String.class)); } } diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/client/JsonUtil.java b/samples/client/petstore/java/src/main/java/com/wordnik/client/JsonUtil.java index 4dc919306d5..da0fca7816e 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/client/JsonUtil.java +++ b/samples/client/petstore/java/src/main/java/com/wordnik/client/JsonUtil.java @@ -5,6 +5,8 @@ import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.core.JsonGenerator.Feature; +import com.fasterxml.jackson.datatype.joda.*; + public class JsonUtil { public static ObjectMapper mapper; @@ -12,6 +14,7 @@ public class JsonUtil { mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.registerModule(new JodaModule()); } public static ObjectMapper getJsonMapper() { diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/PetApi.java b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/PetApi.java index 8b460e98cfa..9fa2290e63f 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/PetApi.java +++ b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/PetApi.java @@ -23,21 +23,25 @@ public class PetApi { } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams, contentType); if(response != null){ return (Pet) ApiInvoker.deserialize(response, "", Pet.class); } @@ -54,21 +58,25 @@ public class PetApi { } } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams, contentType); if(response != null){ return ; } @@ -85,21 +93,25 @@ public class PetApi { } } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(petId == null || body == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json","application/xml"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "PATCH", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "PATCH", queryParams, body, headerParams, formParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "Array", Pet.class); } @@ -116,21 +128,27 @@ public class PetApi { } } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(petId == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + formParams.put("name", name); + formParams.put("status", status); + String[] contentTypes = { + "application/x-www-form-urlencoded"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams, formParams, contentType); if(response != null){ return ; } @@ -153,11 +171,16 @@ public class PetApi { // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); + Map formParams = new HashMap(); - String contentType = "application/json"; + formParams.put("additionalMetadata", additionalMetadata); + String[] contentTypes = { + "multipart/form-data"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, formParams, contentType); if(response != null){ return ; } @@ -174,21 +197,25 @@ public class PetApi { } } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json","application/xml"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, formParams, contentType); if(response != null){ return ; } @@ -205,21 +232,25 @@ public class PetApi { } } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams, formParams, contentType); if(response != null){ return ; } @@ -236,23 +267,27 @@ public class PetApi { } } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(status == null ) { - throw new ApiException(400, "missing required params"); - } if(!"null".equals(String.valueOf(status))) queryParams.put("status", String.valueOf(status)); - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "Array", Pet.class); } @@ -269,23 +304,27 @@ public class PetApi { } } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(tags == null ) { - throw new ApiException(400, "missing required params"); - } if(!"null".equals(String.valueOf(tags))) queryParams.put("tags", String.valueOf(tags)); - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "Array", Pet.class); } diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/StoreApi.java b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/StoreApi.java index dc57a7956dc..b855953090a 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/StoreApi.java +++ b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/StoreApi.java @@ -22,21 +22,25 @@ public class StoreApi { } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(orderId == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams, contentType); if(response != null){ return (Order) ApiInvoker.deserialize(response, "", Order.class); } @@ -53,21 +57,25 @@ public class StoreApi { } } public void deleteOrder (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(); + Map formParams = new HashMap(); - // verify required params are set - if(orderId == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams, contentType); if(response != null){ return ; } @@ -84,21 +92,25 @@ public class StoreApi { } } public void placeOrder (Order 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 = "/store/order".replaceAll("\\{format\\}","json"); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); + Map formParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, formParams, contentType); if(response != null){ return ; } diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/UserApi.java b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/UserApi.java index c5c7d3affae..158bfa5abc5 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/UserApi.java +++ b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/api/UserApi.java @@ -22,21 +22,25 @@ public class UserApi { } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, formParams, contentType); if(response != null){ return ; } @@ -53,21 +57,25 @@ public class UserApi { } } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, formParams, contentType); if(response != null){ return ; } @@ -84,21 +92,25 @@ public class UserApi { } } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(body == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, formParams, contentType); if(response != null){ return ; } @@ -115,21 +127,25 @@ public class UserApi { } } 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"); + } // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); + Map formParams = new HashMap(); - // verify required params are set - if(username == null || body == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams, formParams, contentType); if(response != null){ return ; } @@ -146,21 +162,25 @@ public class UserApi { } } public void deleteUser (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(); + Map formParams = new HashMap(); - // verify required params are set - if(username == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams, contentType); if(response != null){ return ; } @@ -177,21 +197,25 @@ public class UserApi { } } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(username == null ) { - throw new ApiException(400, "missing required params"); - } - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams, contentType); if(response != null){ return (User) ApiInvoker.deserialize(response, "", User.class); } @@ -208,25 +232,29 @@ public class UserApi { } } 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(); + Map formParams = new HashMap(); - // verify required params are set - if(username == null || password == null ) { - throw new ApiException(400, "missing required params"); - } 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"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams, contentType); if(response != null){ return (String) ApiInvoker.deserialize(response, "", String.class); } @@ -249,11 +277,15 @@ public class UserApi { // query params Map queryParams = new HashMap(); Map headerParams = new HashMap(); + Map formParams = new HashMap(); - String contentType = "application/json"; + String[] contentTypes = { + "application/json"}; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams, contentType); if(response != null){ return ; } diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Category.java b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Category.java index 080008e4864..aa9303084bb 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Category.java +++ b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Category.java @@ -1,9 +1,7 @@ package com.wordnik.petstore.model; public class Category { - /* Category unique identifier */ private Long id = null; - /* Name of the category */ private String name = null; public Long getId() { return id; diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Order.java b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Order.java index 6b6c23d79ae..c44ea0f38cc 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Order.java +++ b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Order.java @@ -2,15 +2,12 @@ package com.wordnik.petstore.model; import java.util.Date; public class Order { - /* Unique identifier for the order */ private Long id = null; - /* ID of pet being ordered */ private Long petId = null; - /* Number of pets ordered */ private Integer quantity = null; - /* Status of the order */ + /* Order Status */ private String status = null; - /* Date shipped, only if it has been */ + //public enum statusEnum { placed, approved, delivered, }; private Date shipDate = null; public Long getId() { return id; diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Pet.java b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Pet.java index 7220a93d98a..b5a577d1a86 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Pet.java +++ b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Pet.java @@ -4,18 +4,15 @@ import java.util.*; import com.wordnik.petstore.model.Category; import com.wordnik.petstore.model.Tag; public class Pet { - /* Unique identifier for the Pet */ + /* unique identifier for the pet */ private Long id = null; - /* Category the pet is in */ private Category category = null; - /* Friendly name of the pet */ private String name = null; - /* Image URLs */ private List photoUrls = new ArrayList(); - /* Tags assigned to this pet */ private List tags = new ArrayList(); /* pet status in the store */ private String status = null; + //public enum statusEnum { available, pending, sold, }; public Long getId() { return id; } diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Tag.java b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Tag.java index 4ce4a0eb5e2..886a5a6513b 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Tag.java +++ b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/Tag.java @@ -1,9 +1,7 @@ package com.wordnik.petstore.model; public class Tag { - /* Unique identifier for the tag */ private Long id = null; - /* Friendly name for the tag */ private String name = null; public Long getId() { return id; diff --git a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/User.java b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/User.java index d2e09da239b..4b28758adde 100644 --- a/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/User.java +++ b/samples/client/petstore/java/src/main/java/com/wordnik/petstore/model/User.java @@ -1,22 +1,16 @@ package com.wordnik.petstore.model; public class User { - /* Unique identifier for the user */ private Long id = null; - /* Unique username */ - private String username = null; - /* First name of the user */ private String firstName = null; - /* Last name of the user */ + private String username = null; private String lastName = null; - /* Email address of the user */ private String email = null; - /* Password name of the user */ private String password = null; - /* Phone number of the user */ private String phone = null; /* User Status */ private Integer userStatus = null; + //public enum userStatusEnum { 1-registered, 2-active, 3-closed, }; public Long getId() { return id; } @@ -24,13 +18,6 @@ public class User { this.id = id; } - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - public String getFirstName() { return firstName; } @@ -38,6 +25,13 @@ public class User { this.firstName = firstName; } + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + public String getLastName() { return lastName; } @@ -78,8 +72,8 @@ public class User { StringBuilder sb = new StringBuilder(); sb.append("class User {\n"); sb.append(" id: ").append(id).append("\n"); - sb.append(" username: ").append(username).append("\n"); sb.append(" firstName: ").append(firstName).append("\n"); + sb.append(" username: ").append(username).append("\n"); sb.append(" lastName: ").append(lastName).append("\n"); sb.append(" email: ").append(email).append("\n"); sb.append(" password: ").append(password).append("\n"); diff --git a/samples/client/petstore/scala/src/main/scala/com/wordnik/client/ApiInvoker.scala b/samples/client/petstore/scala/src/main/scala/com/wordnik/client/ApiInvoker.scala index b9252e8d0f0..7056e3bee8b 100644 --- a/samples/client/petstore/scala/src/main/scala/com/wordnik/client/ApiInvoker.scala +++ b/samples/client/petstore/scala/src/main/scala/com/wordnik/client/ApiInvoker.scala @@ -44,6 +44,8 @@ object ApiInvoker { URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") } + def addHeader(key: String, value: String) = defaultHeaders += key -> value + def escape(value: Long): String = value.toString def escape(value: Double): String = value.toString def escape(value: Float): String = value.toString diff --git a/samples/client/wordnik-api/android/AndroidWordnikApiCodegen.scala b/samples/client/wordnik-api/android/AndroidWordnikApiCodegen.scala new file mode 100644 index 00000000000..c1a1f7aee15 --- /dev/null +++ b/samples/client/wordnik-api/android/AndroidWordnikApiCodegen.scala @@ -0,0 +1,51 @@ +/** + * Copyright 2012 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 AndroidWordnikApiCodegen extends BasicAndroidJavaGenerator { + def main(args: Array[String]) = generateClient(args) + + // location of templates + override def templateDir = "src/main/resources/android-java" + + def destinationRoot = "samples/client/wordnik-api/android" + + // where to write generated code + override def destinationDir = destinationRoot + "/src/main/java" + + // package for api invoker, error files + override def invokerPackage = Some("com.wordnik.client.common") + + // package for models + override def modelPackage = Some("com.wordnik.client.model") + + // package for api classes + override def apiPackage = Some("com.wordnik.client.api") + + additionalParams ++= Map( + "artifactId" -> "wordnik-android-client", + "artifactVersion" -> "1.0.0", + "groupId" -> "com.wordnik") + + // supporting classes + override def supportingFiles = + List( + ("apiInvoker.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiInvoker.java"), + ("JsonUtil.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "JsonUtil.java"), + ("apiException.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiException.java"), + ("pom.mustache", destinationRoot, "pom.xml")) +} diff --git a/samples/client/wordnik-api/android/README.md b/samples/client/wordnik-api/android/README.md new file mode 100644 index 00000000000..6ad4cc8fe6d --- /dev/null +++ b/samples/client/wordnik-api/android/README.md @@ -0,0 +1,79 @@ +# Wordnik Android client library + +## Overview +This is a full client library for the Wordnik API. It requires that you have a valid Wordnik API Key--you +can get one for free at http://developer.wordnik.com. + +This library is built using the Wordnik [Swagger](http://swagger.wordnik.com) client library generator. You +can re-generate this library by running ./bin/android-java-wordnik-api.sh from the swagger-codegen project + +## Usage +You can use maven central to add this library to your current project: + +```xml + + com.wordnik + wordnik-android-client + 4.0 + +``` + +or with gradle: + +```gradle +repositories { + mavenCentral() +} + +dependencies { + compile 'com.wordnik:wordnik-android-client:4.0' +} +``` + +or you can pull the source and re-generate the client library with Maven: + +``` +mvn package +``` + +Add the library to your project and you're ready to go: + +```java +import com.wordnik.client.api.*; +import com.wordnik.client.model.*; + +import android.os.AsyncTask; +import android.util.Log; + +class WordOfTheDayAsyncTask extends AsyncTask { + @Override + protected WordOfTheDay doInBackground(Void... params) { + WordsApi api = new WordsApi(); + api.addHeader("api_key", "YOUR_API_KEY"); + try { + return api.getWordOfTheDay("2014-02-19"); + } + catch (Exception e) { + Log.d("WordOfTheDayAsyncTask", e.getMessage()); + return null; + } + } + + @Override + protected void onPostExecute(WordOfTheDay d) { + Log.d("WordOfTheDayAsyncTask", d.toString()); + } +} +``` + +You can now invoke the async task anywhere in your app. Of course you'll want to do +something more in your `onPostExecute` function. + +```java +new WordOfTheDayAsyncTask().execute(); +``` + +This project was built with the following minimum requirements: + +* Maven 3.0 +* Java JDK 6 diff --git a/pom.xml.disabled b/samples/client/wordnik-api/android/pom.xml similarity index 54% rename from pom.xml.disabled rename to samples/client/wordnik-api/android/pom.xml index ad11f255325..03fdf69754e 100644 --- a/pom.xml.disabled +++ b/samples/client/wordnik-api/android/pom.xml @@ -1,51 +1,20 @@ - - - org.sonatype.oss - oss-parent - 5 - + 4.0.0 com.wordnik - swagger-codegen_2.9.1 + wordnik-android-client jar - swagger-codegen - 2.0.2-SNAPSHOT + wordnik-android-client + 4.0 - scm:git:git@github.com:wordnik/swagger-codegen.git + scm:git:git@github.com:wordnik/swagger-mustache.git scm:git:git@github.com:wordnik/swagger-codegen.git https://github.com/wordnik/swagger-codegen 2.2.0 - - - rpidikiti - Ramesh Pidikiti - ramesh@wordnik.com - - - ayush - Ayush Gupts - ayush@glugbot.com - - - fehguy - Tony Tam - fehguy@gmail.com - - - - github - https://github.com/wordnik/swagger-codegen/issues - - - - Apache License 2.0 - http://www.apache.org/licenses/LICENSE-2.0.html - repo - - + @@ -78,6 +47,8 @@ + + org.apache.maven.plugins maven-jar-plugin @@ -93,6 +64,7 @@ + org.codehaus.mojo build-helper-maven-plugin @@ -135,72 +107,41 @@ net.alchim31.maven scala-maven-plugin - 3.1.0 + ${scala-maven-plugin-version} - scala-compile-first - process-resources - add-source compile - - - - scala-test-compile - process-test-resources - testCompile + + incremental + - -Xms128m - -Xmx1500m + -Xmx384m - incremental + + -target:jvm-1.5 + -deprecation + + + + run-scalatest + org.scalatest.tools.Runner + + -p + ${project.build.testOutputDirectory} + + + -Xmx512m + + + - - - net.alchim31.maven - scala-maven-plugin - 3.1.0 - - - attach-javadocs - - doc-jar - - - - - - - org.apache.maven.plugins - maven-site-plugin - 3.0 - - - - maven-project-info-reports-plugin - 2.2 - - - net.alchim31.maven - scala-maven-plugin - 3.1.0 - - - -Xms64m - -Xmx1024m - - - - - - - @@ -208,33 +149,42 @@ net.alchim31.maven scala-maven-plugin - - ${scala-version} - + ${scala-maven-plugin-version} - commons-io - commons-io - 2.3 + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + compile - org.fusesource.scalate - scalate-wikitext_2.9 - 1.6.1 + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + compile - org.fusesource.scalate - scalate-page_2.9 - 1.6.1 + com.fasterxml.jackson.core + jackson-databind + ${jackson-version} + compile + + org.apache.httpcomponents + httpclient + ${httpclient-version} + compile + + + org.scala-lang scala-library ${scala-version} - compile + test org.scalatest @@ -248,25 +198,17 @@ ${junit-version} test - - org.json4s - json4s-jackson_2.9.1 - ${json4s-version} - compile - - - org.json4s - json4s-native_2.9.1 - ${json4s-version} - compile - + - 1.1.1-SNAPSHOT + 2.1.4 2.9.1-1 4.8.1 - 1.0.0 + 1.0.0 + 4.8.1 1.6.1 - 3.0.0 + 4.0 + 3.1.5 + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/AccountApi.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/AccountApi.java new file mode 100644 index 00000000000..5b334fa1e4f --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/AccountApi.java @@ -0,0 +1,192 @@ +package com.wordnik.client.api; + +import com.wordnik.client.common.ApiException; +import com.wordnik.client.common.ApiInvoker; +import com.wordnik.client.model.User; +import com.wordnik.client.model.WordList; +import com.wordnik.client.model.ApiTokenStatus; +import com.wordnik.client.model.AuthenticationToken; +import java.util.*; + +public class AccountApi { + String basePath = "http://api.wordnik.com/v4"; + 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 AuthenticationToken authenticate (String username, String password) throws ApiException { + // verify required params are set + if(username == null || password == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/account.{format}/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + 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 (AuthenticationToken) ApiInvoker.deserialize(response, "", AuthenticationToken.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public AuthenticationToken authenticatePost (String username, String body) throws ApiException { + // verify required params are set + if(username == null || body == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/account.{format}/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + if(response != null){ + return (AuthenticationToken) ApiInvoker.deserialize(response, "", AuthenticationToken.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public List getWordListsForLoggedInUser (String auth_token, Integer skip, Integer limit) throws ApiException { + // verify required params are set + if(auth_token == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/account.{format}/wordLists".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(skip))) + queryParams.put("skip", String.valueOf(skip)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "List", WordList.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public ApiTokenStatus getApiTokenStatus (String api_key) throws ApiException { + // create path and map variables + String path = "/account.{format}/apiTokenStatus".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + headerParams.put("api_key", api_key); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (ApiTokenStatus) ApiInvoker.deserialize(response, "", ApiTokenStatus.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public User getLoggedInUser (String auth_token) throws ApiException { + // verify required params are set + if(auth_token == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/account.{format}/user".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + 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; + } + } + } + } + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordApi.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordApi.java new file mode 100644 index 00000000000..003a88caf0e --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordApi.java @@ -0,0 +1,475 @@ +package com.wordnik.client.api; + +import com.wordnik.client.common.ApiException; +import com.wordnik.client.common.ApiInvoker; +import com.wordnik.client.model.FrequencySummary; +import com.wordnik.client.model.Bigram; +import com.wordnik.client.model.WordObject; +import com.wordnik.client.model.ExampleSearchResults; +import com.wordnik.client.model.Example; +import com.wordnik.client.model.ScrabbleScoreResult; +import com.wordnik.client.model.TextPron; +import com.wordnik.client.model.Syllable; +import com.wordnik.client.model.Related; +import com.wordnik.client.model.Definition; +import com.wordnik.client.model.AudioFile; +import java.util.*; + +public class WordApi { + String basePath = "http://api.wordnik.com/v4"; + 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 ExampleSearchResults getExamples (String word, String includeDuplicates, String useCanonical, Integer skip, Integer limit) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}/examples".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(includeDuplicates))) + queryParams.put("includeDuplicates", String.valueOf(includeDuplicates)); + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + if(!"null".equals(String.valueOf(skip))) + queryParams.put("skip", String.valueOf(skip)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (ExampleSearchResults) ApiInvoker.deserialize(response, "", ExampleSearchResults.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public WordObject getWord (String word, String useCanonical, String includeSuggestions) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + if(!"null".equals(String.valueOf(includeSuggestions))) + queryParams.put("includeSuggestions", String.valueOf(includeSuggestions)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (WordObject) ApiInvoker.deserialize(response, "", WordObject.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public List getDefinitions (String word, String partOfSpeech, String sourceDictionaries, Integer limit, String includeRelated, String useCanonical, String includeTags) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}/definitions".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + if(!"null".equals(String.valueOf(partOfSpeech))) + queryParams.put("partOfSpeech", String.valueOf(partOfSpeech)); + if(!"null".equals(String.valueOf(includeRelated))) + queryParams.put("includeRelated", String.valueOf(includeRelated)); + if(!"null".equals(String.valueOf(sourceDictionaries))) + queryParams.put("sourceDictionaries", String.valueOf(sourceDictionaries)); + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + if(!"null".equals(String.valueOf(includeTags))) + queryParams.put("includeTags", String.valueOf(includeTags)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "List", Definition.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public Example getTopExample (String word, String useCanonical) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}/topExample".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (Example) ApiInvoker.deserialize(response, "", Example.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public List getRelatedWords (String word, String relationshipTypes, String useCanonical, Integer limitPerRelationshipType) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}/relatedWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + if(!"null".equals(String.valueOf(relationshipTypes))) + queryParams.put("relationshipTypes", String.valueOf(relationshipTypes)); + if(!"null".equals(String.valueOf(limitPerRelationshipType))) + queryParams.put("limitPerRelationshipType", String.valueOf(limitPerRelationshipType)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "List", Related.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public List getTextPronunciations (String word, String sourceDictionary, String typeFormat, String useCanonical, Integer limit) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}/pronunciations".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + if(!"null".equals(String.valueOf(sourceDictionary))) + queryParams.put("sourceDictionary", String.valueOf(sourceDictionary)); + if(!"null".equals(String.valueOf(typeFormat))) + queryParams.put("typeFormat", String.valueOf(typeFormat)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "List", TextPron.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public List getHyphenation (String word, String sourceDictionary, String useCanonical, Integer limit) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}/hyphenation".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + if(!"null".equals(String.valueOf(sourceDictionary))) + queryParams.put("sourceDictionary", String.valueOf(sourceDictionary)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "List", Syllable.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public FrequencySummary getWordFrequency (String word, String useCanonical, Integer startYear, Integer endYear) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}/frequency".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + if(!"null".equals(String.valueOf(startYear))) + queryParams.put("startYear", String.valueOf(startYear)); + if(!"null".equals(String.valueOf(endYear))) + queryParams.put("endYear", String.valueOf(endYear)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (FrequencySummary) ApiInvoker.deserialize(response, "", FrequencySummary.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public List getPhrases (String word, Integer limit, Integer wlmi, String useCanonical) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}/phrases".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + if(!"null".equals(String.valueOf(wlmi))) + queryParams.put("wlmi", String.valueOf(wlmi)); + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "List", Bigram.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public List getEtymologies (String word, String useCanonical) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}/etymologies".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "List", String.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public List getAudio (String word, String useCanonical, Integer limit) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}/audio".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(useCanonical))) + queryParams.put("useCanonical", String.valueOf(useCanonical)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "List", AudioFile.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public ScrabbleScoreResult getScrabbleScore (String word) throws ApiException { + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/word.{format}/{word}/scrabbleScore".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (ScrabbleScoreResult) ApiInvoker.deserialize(response, "", ScrabbleScoreResult.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + } + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListApi.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListApi.java new file mode 100644 index 00000000000..e017c466636 --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListApi.java @@ -0,0 +1,231 @@ +package com.wordnik.client.api; + +import com.wordnik.client.common.ApiException; +import com.wordnik.client.common.ApiInvoker; +import com.wordnik.client.model.WordListWord; +import com.wordnik.client.model.WordList; +import com.wordnik.client.model.StringValue; +import java.util.*; + +public class WordListApi { + String basePath = "http://api.wordnik.com/v4"; + 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 updateWordList (String permalink, WordList body, String auth_token) throws ApiException { + // verify required params are set + if(permalink == null || auth_token == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + public void deleteWordList (String permalink, String auth_token) throws ApiException { + // verify required params are set + if(permalink == null || auth_token == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + public WordList getWordListByPermalink (String permalink, String auth_token) throws ApiException { + // verify required params are set + if(permalink == null || auth_token == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (WordList) ApiInvoker.deserialize(response, "", WordList.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public void addWordsToWordList (String permalink, List body, String auth_token) throws ApiException { + // verify required params are set + if(permalink == null || auth_token == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/wordList.{format}/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return ; + } + else { + throw ex; + } + } + } + public List getWordListWords (String permalink, String auth_token, String sortBy, String sortOrder, Integer skip, Integer limit) throws ApiException { + // verify required params are set + if(permalink == null || auth_token == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/wordList.{format}/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(sortBy))) + queryParams.put("sortBy", String.valueOf(sortBy)); + if(!"null".equals(String.valueOf(sortOrder))) + queryParams.put("sortOrder", String.valueOf(sortOrder)); + if(!"null".equals(String.valueOf(skip))) + queryParams.put("skip", String.valueOf(skip)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "List", WordListWord.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public void deleteWordsFromWordList (String permalink, List body, String auth_token) throws ApiException { + // verify required params are set + if(permalink == null || auth_token == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/wordList.{format}/{permalink}/deleteWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}", apiInvoker.escapeString(permalink.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, 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/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListsApi.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListsApi.java new file mode 100644 index 00000000000..c97ab75e597 --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordListsApi.java @@ -0,0 +1,61 @@ +package com.wordnik.client.api; + +import com.wordnik.client.common.ApiException; +import com.wordnik.client.common.ApiInvoker; +import com.wordnik.client.model.WordList; +import java.util.*; + +public class WordListsApi { + String basePath = "http://api.wordnik.com/v4"; + 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 WordList createWordList (WordList body, String auth_token) throws ApiException { + // verify required params are set + if(auth_token == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/wordLists.{format}".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); + if(response != null){ + return (WordList) ApiInvoker.deserialize(response, "", WordList.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + } + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordsApi.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordsApi.java new file mode 100644 index 00000000000..c1c8a81efa0 --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/api/WordsApi.java @@ -0,0 +1,273 @@ +package com.wordnik.client.api; + +import com.wordnik.client.common.ApiException; +import com.wordnik.client.common.ApiInvoker; +import com.wordnik.client.model.DefinitionSearchResults; +import com.wordnik.client.model.WordObject; +import com.wordnik.client.model.WordOfTheDay; +import com.wordnik.client.model.WordSearchResults; +import java.util.*; + +public class WordsApi { + String basePath = "http://api.wordnik.com/v4"; + 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 WordSearchResults searchWords (String query, String includePartOfSpeech, String excludePartOfSpeech, String caseSensitive, Integer minCorpusCount, Integer maxCorpusCount, Integer minDictionaryCount, Integer maxDictionaryCount, Integer minLength, Integer maxLength, Integer skip, Integer limit) throws ApiException { + // verify required params are set + if(query == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/words.{format}/search/{query}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "query" + "\\}", apiInvoker.escapeString(query.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(caseSensitive))) + queryParams.put("caseSensitive", String.valueOf(caseSensitive)); + if(!"null".equals(String.valueOf(includePartOfSpeech))) + queryParams.put("includePartOfSpeech", String.valueOf(includePartOfSpeech)); + if(!"null".equals(String.valueOf(excludePartOfSpeech))) + queryParams.put("excludePartOfSpeech", String.valueOf(excludePartOfSpeech)); + if(!"null".equals(String.valueOf(minCorpusCount))) + queryParams.put("minCorpusCount", String.valueOf(minCorpusCount)); + if(!"null".equals(String.valueOf(maxCorpusCount))) + queryParams.put("maxCorpusCount", String.valueOf(maxCorpusCount)); + if(!"null".equals(String.valueOf(minDictionaryCount))) + queryParams.put("minDictionaryCount", String.valueOf(minDictionaryCount)); + if(!"null".equals(String.valueOf(maxDictionaryCount))) + queryParams.put("maxDictionaryCount", String.valueOf(maxDictionaryCount)); + if(!"null".equals(String.valueOf(minLength))) + queryParams.put("minLength", String.valueOf(minLength)); + if(!"null".equals(String.valueOf(maxLength))) + queryParams.put("maxLength", String.valueOf(maxLength)); + if(!"null".equals(String.valueOf(skip))) + queryParams.put("skip", String.valueOf(skip)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (WordSearchResults) ApiInvoker.deserialize(response, "", WordSearchResults.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public WordOfTheDay getWordOfTheDay (String date) throws ApiException { + // create path and map variables + String path = "/words.{format}/wordOfTheDay".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(date))) + queryParams.put("date", String.valueOf(date)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (WordOfTheDay) ApiInvoker.deserialize(response, "", WordOfTheDay.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public DefinitionSearchResults reverseDictionary (String query, String findSenseForWord, String includeSourceDictionaries, String excludeSourceDictionaries, String includePartOfSpeech, String excludePartOfSpeech, String expandTerms, String sortBy, String sortOrder, Integer minCorpusCount, Integer maxCorpusCount, Integer minLength, Integer maxLength, String includeTags, String skip, Integer limit) throws ApiException { + // verify required params are set + if(query == null ) { + throw new ApiException(400, "missing required params"); + } + // create path and map variables + String path = "/words.{format}/reverseDictionary".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(query))) + queryParams.put("query", String.valueOf(query)); + if(!"null".equals(String.valueOf(findSenseForWord))) + queryParams.put("findSenseForWord", String.valueOf(findSenseForWord)); + if(!"null".equals(String.valueOf(includeSourceDictionaries))) + queryParams.put("includeSourceDictionaries", String.valueOf(includeSourceDictionaries)); + if(!"null".equals(String.valueOf(excludeSourceDictionaries))) + queryParams.put("excludeSourceDictionaries", String.valueOf(excludeSourceDictionaries)); + if(!"null".equals(String.valueOf(includePartOfSpeech))) + queryParams.put("includePartOfSpeech", String.valueOf(includePartOfSpeech)); + if(!"null".equals(String.valueOf(excludePartOfSpeech))) + queryParams.put("excludePartOfSpeech", String.valueOf(excludePartOfSpeech)); + if(!"null".equals(String.valueOf(minCorpusCount))) + queryParams.put("minCorpusCount", String.valueOf(minCorpusCount)); + if(!"null".equals(String.valueOf(maxCorpusCount))) + queryParams.put("maxCorpusCount", String.valueOf(maxCorpusCount)); + if(!"null".equals(String.valueOf(minLength))) + queryParams.put("minLength", String.valueOf(minLength)); + if(!"null".equals(String.valueOf(maxLength))) + queryParams.put("maxLength", String.valueOf(maxLength)); + if(!"null".equals(String.valueOf(expandTerms))) + queryParams.put("expandTerms", String.valueOf(expandTerms)); + if(!"null".equals(String.valueOf(includeTags))) + queryParams.put("includeTags", String.valueOf(includeTags)); + if(!"null".equals(String.valueOf(sortBy))) + queryParams.put("sortBy", String.valueOf(sortBy)); + if(!"null".equals(String.valueOf(sortOrder))) + queryParams.put("sortOrder", String.valueOf(sortOrder)); + if(!"null".equals(String.valueOf(skip))) + queryParams.put("skip", String.valueOf(skip)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (DefinitionSearchResults) ApiInvoker.deserialize(response, "", DefinitionSearchResults.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public List getRandomWords (String includePartOfSpeech, String excludePartOfSpeech, String sortBy, String sortOrder, String hasDictionaryDef, Integer minCorpusCount, Integer maxCorpusCount, Integer minDictionaryCount, Integer maxDictionaryCount, Integer minLength, Integer maxLength, Integer limit) throws ApiException { + // create path and map variables + String path = "/words.{format}/randomWords".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(hasDictionaryDef))) + queryParams.put("hasDictionaryDef", String.valueOf(hasDictionaryDef)); + if(!"null".equals(String.valueOf(includePartOfSpeech))) + queryParams.put("includePartOfSpeech", String.valueOf(includePartOfSpeech)); + if(!"null".equals(String.valueOf(excludePartOfSpeech))) + queryParams.put("excludePartOfSpeech", String.valueOf(excludePartOfSpeech)); + if(!"null".equals(String.valueOf(minCorpusCount))) + queryParams.put("minCorpusCount", String.valueOf(minCorpusCount)); + if(!"null".equals(String.valueOf(maxCorpusCount))) + queryParams.put("maxCorpusCount", String.valueOf(maxCorpusCount)); + if(!"null".equals(String.valueOf(minDictionaryCount))) + queryParams.put("minDictionaryCount", String.valueOf(minDictionaryCount)); + if(!"null".equals(String.valueOf(maxDictionaryCount))) + queryParams.put("maxDictionaryCount", String.valueOf(maxDictionaryCount)); + if(!"null".equals(String.valueOf(minLength))) + queryParams.put("minLength", String.valueOf(minLength)); + if(!"null".equals(String.valueOf(maxLength))) + queryParams.put("maxLength", String.valueOf(maxLength)); + if(!"null".equals(String.valueOf(sortBy))) + queryParams.put("sortBy", String.valueOf(sortBy)); + if(!"null".equals(String.valueOf(sortOrder))) + queryParams.put("sortOrder", String.valueOf(sortOrder)); + if(!"null".equals(String.valueOf(limit))) + queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (List) ApiInvoker.deserialize(response, "List", WordObject.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + public WordObject getRandomWord (String includePartOfSpeech, String excludePartOfSpeech, String hasDictionaryDef, Integer minCorpusCount, Integer maxCorpusCount, Integer minDictionaryCount, Integer maxDictionaryCount, Integer minLength, Integer maxLength) throws ApiException { + // create path and map variables + String path = "/words.{format}/randomWord".replaceAll("\\{format\\}","json"); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + if(!"null".equals(String.valueOf(hasDictionaryDef))) + queryParams.put("hasDictionaryDef", String.valueOf(hasDictionaryDef)); + if(!"null".equals(String.valueOf(includePartOfSpeech))) + queryParams.put("includePartOfSpeech", String.valueOf(includePartOfSpeech)); + if(!"null".equals(String.valueOf(excludePartOfSpeech))) + queryParams.put("excludePartOfSpeech", String.valueOf(excludePartOfSpeech)); + if(!"null".equals(String.valueOf(minCorpusCount))) + queryParams.put("minCorpusCount", String.valueOf(minCorpusCount)); + if(!"null".equals(String.valueOf(maxCorpusCount))) + queryParams.put("maxCorpusCount", String.valueOf(maxCorpusCount)); + if(!"null".equals(String.valueOf(minDictionaryCount))) + queryParams.put("minDictionaryCount", String.valueOf(minDictionaryCount)); + if(!"null".equals(String.valueOf(maxDictionaryCount))) + queryParams.put("maxDictionaryCount", String.valueOf(maxDictionaryCount)); + if(!"null".equals(String.valueOf(minLength))) + queryParams.put("minLength", String.valueOf(minLength)); + if(!"null".equals(String.valueOf(maxLength))) + queryParams.put("maxLength", String.valueOf(maxLength)); + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (WordObject) ApiInvoker.deserialize(response, "", WordObject.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } + } + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/ApiException.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/ApiException.java new file mode 100644 index 00000000000..8c96d599bb4 --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/ApiException.java @@ -0,0 +1,29 @@ +package com.wordnik.client.common; + +public class ApiException extends Exception { + int code = 0; + String message = null; + + public ApiException() {} + + public ApiException(int code, String message) { + this.code = code; + this.message = message; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMessage() { + return message; + } + + public void setMessage(String message) { + this.message = message; + } +} diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/ApiInvoker.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/ApiInvoker.java new file mode 100644 index 00000000000..fb2ba7f8ce5 --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/ApiInvoker.java @@ -0,0 +1,272 @@ +package com.wordnik.client.common; + + +import com.fasterxml.jackson.core.JsonGenerator.Feature; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import org.apache.http.*; +import org.apache.http.client.*; +import org.apache.http.client.methods.*; +import org.apache.http.conn.*; +import org.apache.http.conn.scheme.*; +import org.apache.http.conn.ssl.*; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.*; +import org.apache.http.impl.conn.*; +import org.apache.http.params.*; +import org.apache.http.util.EntityUtils; + +import java.io.File; +import java.net.Socket; +import java.net.UnknownHostException; +import java.net.URLEncoder; + +import java.util.Map; +import java.util.HashMap; +import java.util.List; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import java.security.GeneralSecurityException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.cert.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import java.util.Date; +import java.util.Random; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +public class ApiInvoker { + private static ApiInvoker INSTANCE = new ApiInvoker(); + private Map defaultHeaderMap = new HashMap(); + + private HttpClient client = null; + + private boolean ignoreSSLCertificates = false; + + private ClientConnectionManager ignoreSSLConnectionManager; + + public ApiInvoker() { + initConnectionManager(); + } + + public static ApiInvoker getInstance() { + return INSTANCE; + } + + public void ignoreSSLCertificates(boolean ignoreSSLCertificates) { + this.ignoreSSLCertificates = ignoreSSLCertificates; + } + + public void addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + } + + public String escapeString(String str) { + return str; + } + + public static Object deserialize(String json, String containerType, Class cls) throws ApiException { + try{ + if("List".equals(containerType)) { + JavaType typeInfo = JsonUtil.getJsonMapper().getTypeFactory().constructCollectionType(List.class, cls); + List response = (List) JsonUtil.getJsonMapper().readValue(json, typeInfo); + return response; + } + else if(String.class.equals(cls)) { + if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) + return json.substring(1, json.length() - 2); + else + return json; + } + else { + return JsonUtil.getJsonMapper().readValue(json, cls); + } + } + catch (IOException e) { + throw new ApiException(500, e.getMessage()); + } + } + + public static String serialize(Object obj) throws ApiException { + try { + if (obj != null) + return JsonUtil.getJsonMapper().writeValueAsString(obj); + else + return null; + } + catch (Exception e) { + throw new ApiException(500, e.getMessage()); + } + } + + public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, String contentType) throws ApiException { + HttpClient client = getClient(host); + + StringBuilder b = new StringBuilder(); + for(String key : queryParams.keySet()) { + String value = queryParams.get(key); + if (value != null){ + if(b.toString().length() == 0) + b.append("?"); + else + b.append("&"); + b.append(escapeString(key)).append("=").append(escapeString(value)); + } + } + String url = host + path + b.toString(); + + HashMap headers = new HashMap(); + + for(String key : headerParams.keySet()) { + headers.put(key, headerParams.get(key)); + } + + for(String key : defaultHeaderMap.keySet()) { + if(!headerParams.containsKey(key)) { + headers.put(key, defaultHeaderMap.get(key)); + } + } + headers.put("Accept", "application/json"); + + HttpResponse response = null; + try{ + if("GET".equals(method)) { + HttpGet get = new HttpGet(url); + get.addHeader("Accept", "application/json"); + for(String key : headers.keySet()) { + get.setHeader(key, headers.get(key)); + } + response = client.execute(get); + } + else if ("POST".equals(method)) { + HttpPost post = new HttpPost(url); + + if (body != null) { + post.setHeader("Content-Type", contentType); + post.setEntity(new StringEntity(serialize(body), "UTF-8")); + } + for(String key : headers.keySet()) { + post.setHeader(key, headers.get(key)); + } + response = client.execute(post); + } + else if ("PUT".equals(method)) { + HttpPut put = new HttpPut(url); + if(body != null) { + put.setHeader("Content-Type", contentType); + put.setEntity(new StringEntity(serialize(body), "UTF-8")); + } + for(String key : headers.keySet()) { + put.setHeader(key, headers.get(key)); + } + response = client.execute(put); + } + else if ("DELETE".equals(method)) { + HttpDelete delete = new HttpDelete(url); + for(String key : headers.keySet()) { + delete.setHeader(key, headers.get(key)); + } + response = client.execute(delete); + } + + int code = response.getStatusLine().getStatusCode(); + String responseString = null; + if(code == 204) + responseString = ""; + else if(code >= 200 && code < 300) { + if(response.getEntity() != null) { + HttpEntity resEntity = response.getEntity(); + responseString = EntityUtils.toString(resEntity); + } + } + else { + if(response.getEntity() != null) { + HttpEntity resEntity = response.getEntity(); + responseString = EntityUtils.toString(resEntity); + } + else + responseString = "no data"; + throw new ApiException(code, responseString); + } + return responseString; + } + catch(IOException e) { + throw new ApiException(500, e.getMessage()); + } + } + + private HttpClient getClient(String host) { + if (client == null) { + if (ignoreSSLCertificates && ignoreSSLConnectionManager != null) { + // Trust self signed certificates + client = new DefaultHttpClient(ignoreSSLConnectionManager, new BasicHttpParams()); + } else { + client = new DefaultHttpClient(); + } + } + return client; + } + + private void initConnectionManager() { + try { + final SSLContext sslContext = SSLContext.getInstance("SSL"); + + // set up a TrustManager that trusts everything + TrustManager[] trustManagers = new TrustManager[] { + new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return null; + } + public void checkClientTrusted(X509Certificate[] certs, String authType) {} + public void checkServerTrusted(X509Certificate[] certs, String authType) {} + }}; + + sslContext.init(null, trustManagers, new SecureRandom()); + + SSLSocketFactory sf = new SSLSocketFactory((KeyStore)null) { + private javax.net.ssl.SSLSocketFactory sslFactory = sslContext.getSocketFactory(); + + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException, UnknownHostException { + return sslFactory.createSocket(socket, host, port, autoClose); + } + + public Socket createSocket() throws IOException { + return sslFactory.createSocket(); + } + }; + + sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + Scheme httpsScheme = new Scheme("https", sf, 443); + SchemeRegistry schemeRegistry = new SchemeRegistry(); + schemeRegistry.register(httpsScheme); + schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + + ignoreSSLConnectionManager = new SingleClientConnManager(new BasicHttpParams(), schemeRegistry); + } catch (NoSuchAlgorithmException e) { + // This will only be thrown if SSL isn't available for some reason. + } catch (KeyManagementException e) { + // This might be thrown when passing a key into init(), but no key is being passed. + } catch (GeneralSecurityException e) { + // This catches anything else that might go wrong. + // If anything goes wrong we default to the standard connection manager. + } + } +} + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/JsonUtil.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/JsonUtil.java new file mode 100644 index 00000000000..3a3ceb7b326 --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/common/JsonUtil.java @@ -0,0 +1,21 @@ +package com.wordnik.client.common; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.core.JsonGenerator.Feature; + +public class JsonUtil { + public static ObjectMapper mapper; + + static { + mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + } + + public static ObjectMapper getJsonMapper() { + return mapper; + } +} + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ApiTokenStatus.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ApiTokenStatus.java new file mode 100644 index 00000000000..4f65a350537 --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ApiTokenStatus.java @@ -0,0 +1,74 @@ +package com.wordnik.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ApiTokenStatus { + @JsonProperty("valid") + private Boolean valid = null; + @JsonProperty("token") + private String token = null; + @JsonProperty("resetsInMillis") + private Long resetsInMillis = null; + @JsonProperty("remainingCalls") + private Long remainingCalls = null; + @JsonProperty("expiresInMillis") + private Long expiresInMillis = null; + @JsonProperty("totalRequests") + private Long totalRequests = null; + public Boolean getValid() { + return valid; + } + public void setValid(Boolean valid) { + this.valid = valid; + } + + public String getToken() { + return token; + } + public void setToken(String token) { + this.token = token; + } + + public Long getResetsInMillis() { + return resetsInMillis; + } + public void setResetsInMillis(Long resetsInMillis) { + this.resetsInMillis = resetsInMillis; + } + + public Long getRemainingCalls() { + return remainingCalls; + } + public void setRemainingCalls(Long remainingCalls) { + this.remainingCalls = remainingCalls; + } + + public Long getExpiresInMillis() { + return expiresInMillis; + } + public void setExpiresInMillis(Long expiresInMillis) { + this.expiresInMillis = expiresInMillis; + } + + public Long getTotalRequests() { + return totalRequests; + } + public void setTotalRequests(Long totalRequests) { + this.totalRequests = totalRequests; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ApiTokenStatus {\n"); + sb.append(" valid: ").append(valid).append("\n"); + sb.append(" token: ").append(token).append("\n"); + sb.append(" resetsInMillis: ").append(resetsInMillis).append("\n"); + sb.append(" remainingCalls: ").append(remainingCalls).append("\n"); + sb.append(" expiresInMillis: ").append(expiresInMillis).append("\n"); + sb.append(" totalRequests: ").append(totalRequests).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AudioFile.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AudioFile.java new file mode 100644 index 00000000000..d6d46ad2f8e --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AudioFile.java @@ -0,0 +1,155 @@ +package com.wordnik.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Date; +public class AudioFile { + @JsonProperty("attributionUrl") + private String attributionUrl = null; + @JsonProperty("commentCount") + private Integer commentCount = null; + @JsonProperty("voteCount") + private Integer voteCount = null; + @JsonProperty("fileUrl") + private String fileUrl = null; + @JsonProperty("audioType") + private String audioType = null; + @JsonProperty("id") + private Long id = null; + @JsonProperty("duration") + private Double duration = null; + @JsonProperty("attributionText") + private String attributionText = null; + @JsonProperty("createdBy") + private String createdBy = null; + @JsonProperty("description") + private String description = null; + @JsonProperty("createdAt") + private Date createdAt = null; + @JsonProperty("voteWeightedAverage") + private Float voteWeightedAverage = null; + @JsonProperty("voteAverage") + private Float voteAverage = null; + @JsonProperty("word") + private String word = null; + public String getAttributionUrl() { + return attributionUrl; + } + public void setAttributionUrl(String attributionUrl) { + this.attributionUrl = attributionUrl; + } + + public Integer getCommentCount() { + return commentCount; + } + public void setCommentCount(Integer commentCount) { + this.commentCount = commentCount; + } + + public Integer getVoteCount() { + return voteCount; + } + public void setVoteCount(Integer voteCount) { + this.voteCount = voteCount; + } + + public String getFileUrl() { + return fileUrl; + } + public void setFileUrl(String fileUrl) { + this.fileUrl = fileUrl; + } + + public String getAudioType() { + return audioType; + } + public void setAudioType(String audioType) { + this.audioType = audioType; + } + + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + public Double getDuration() { + return duration; + } + public void setDuration(Double duration) { + this.duration = duration; + } + + public String getAttributionText() { + return attributionText; + } + public void setAttributionText(String attributionText) { + this.attributionText = attributionText; + } + + public String getCreatedBy() { + return createdBy; + } + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + + public Date getCreatedAt() { + return createdAt; + } + public void setCreatedAt(Date createdAt) { + this.createdAt = createdAt; + } + + public Float getVoteWeightedAverage() { + return voteWeightedAverage; + } + public void setVoteWeightedAverage(Float voteWeightedAverage) { + this.voteWeightedAverage = voteWeightedAverage; + } + + public Float getVoteAverage() { + return voteAverage; + } + public void setVoteAverage(Float voteAverage) { + this.voteAverage = voteAverage; + } + + public String getWord() { + return word; + } + public void setWord(String word) { + this.word = word; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AudioFile {\n"); + sb.append(" attributionUrl: ").append(attributionUrl).append("\n"); + sb.append(" commentCount: ").append(commentCount).append("\n"); + sb.append(" voteCount: ").append(voteCount).append("\n"); + sb.append(" fileUrl: ").append(fileUrl).append("\n"); + sb.append(" audioType: ").append(audioType).append("\n"); + sb.append(" id: ").append(id).append("\n"); + sb.append(" duration: ").append(duration).append("\n"); + sb.append(" attributionText: ").append(attributionText).append("\n"); + sb.append(" createdBy: ").append(createdBy).append("\n"); + sb.append(" description: ").append(description).append("\n"); + sb.append(" createdAt: ").append(createdAt).append("\n"); + sb.append(" voteWeightedAverage: ").append(voteWeightedAverage).append("\n"); + sb.append(" voteAverage: ").append(voteAverage).append("\n"); + sb.append(" word: ").append(word).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AuthenticationToken.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AuthenticationToken.java new file mode 100644 index 00000000000..03c6cc00dba --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/AuthenticationToken.java @@ -0,0 +1,44 @@ +package com.wordnik.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class AuthenticationToken { + @JsonProperty("token") + private String token = null; + @JsonProperty("userId") + private Long userId = null; + @JsonProperty("userSignature") + private String userSignature = null; + public String getToken() { + return token; + } + public void setToken(String token) { + this.token = token; + } + + public Long getUserId() { + return userId; + } + public void setUserId(Long userId) { + this.userId = userId; + } + + public String getUserSignature() { + return userSignature; + } + public void setUserSignature(String userSignature) { + this.userSignature = userSignature; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AuthenticationToken {\n"); + sb.append(" token: ").append(token).append("\n"); + sb.append(" userId: ").append(userId).append("\n"); + sb.append(" userSignature: ").append(userSignature).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Bigram.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Bigram.java new file mode 100644 index 00000000000..4be9f36cf56 --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Bigram.java @@ -0,0 +1,64 @@ +package com.wordnik.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Bigram { + @JsonProperty("count") + private Long count = null; + @JsonProperty("gram2") + private String gram2 = null; + @JsonProperty("gram1") + private String gram1 = null; + @JsonProperty("wlmi") + private Double wlmi = null; + @JsonProperty("mi") + private Double mi = null; + public Long getCount() { + return count; + } + public void setCount(Long count) { + this.count = count; + } + + public String getGram2() { + return gram2; + } + public void setGram2(String gram2) { + this.gram2 = gram2; + } + + public String getGram1() { + return gram1; + } + public void setGram1(String gram1) { + this.gram1 = gram1; + } + + public Double getWlmi() { + return wlmi; + } + public void setWlmi(Double wlmi) { + this.wlmi = wlmi; + } + + public Double getMi() { + return mi; + } + public void setMi(Double mi) { + this.mi = mi; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Bigram {\n"); + sb.append(" count: ").append(count).append("\n"); + sb.append(" gram2: ").append(gram2).append("\n"); + sb.append(" gram1: ").append(gram1).append("\n"); + sb.append(" wlmi: ").append(wlmi).append("\n"); + sb.append(" mi: ").append(mi).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Citation.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Citation.java new file mode 100644 index 00000000000..5b2f45bc650 --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Citation.java @@ -0,0 +1,34 @@ +package com.wordnik.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class Citation { + @JsonProperty("cite") + private String cite = null; + @JsonProperty("source") + private String source = null; + public String getCite() { + return cite; + } + public void setCite(String cite) { + this.cite = cite; + } + + public String getSource() { + return source; + } + public void setSource(String source) { + this.source = source; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Citation {\n"); + sb.append(" cite: ").append(cite).append("\n"); + sb.append(" source: ").append(source).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ContentProvider.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ContentProvider.java new file mode 100644 index 00000000000..b0d994d3b0b --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/ContentProvider.java @@ -0,0 +1,34 @@ +package com.wordnik.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ContentProvider { + @JsonProperty("id") + private Integer id = null; + @JsonProperty("name") + private String name = null; + public Integer getId() { + return id; + } + public void setId(Integer id) { + this.id = id; + } + + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ContentProvider {\n"); + sb.append(" id: ").append(id).append("\n"); + sb.append(" name: ").append(name).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} + diff --git a/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Definition.java b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Definition.java new file mode 100644 index 00000000000..f16273a415a --- /dev/null +++ b/samples/client/wordnik-api/android/src/main/java/com/wordnik/client/model/Definition.java @@ -0,0 +1,181 @@ +package com.wordnik.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.*; +import com.wordnik.client.model.Label; +import com.wordnik.client.model.ExampleUsage; +import com.wordnik.client.model.TextPron; +import com.wordnik.client.model.Citation; +import com.wordnik.client.model.Related; +import com.wordnik.client.model.Note; +public class Definition { + @JsonProperty("extendedText") + private String extendedText = null; + @JsonProperty("text") + private String text = null; + @JsonProperty("sourceDictionary") + private String sourceDictionary = null; + @JsonProperty("citations") + private List citations = new ArrayList(); + @JsonProperty("labels") + private List + + com.fasterxml.jackson.datatype + jackson-datatype-joda + 2.1.5 + + + joda-time + joda-time + ${jodatime-version} + compile + @@ -203,6 +214,7 @@ 1.7 2.1.4 + 2.3 2.9.1-1 4.8.1 1.0.0 diff --git a/src/main/resources/android-java/api.mustache b/src/main/resources/android-java/api.mustache index 925e9b9d711..fb510052ac8 100644 --- a/src/main/resources/android-java/api.mustache +++ b/src/main/resources/android-java/api.mustache @@ -19,24 +19,17 @@ public class {{classname}} { public ApiInvoker getInvoker() { return apiInvoker; } - + public void setBasePath(String basePath) { this.basePath = basePath; } - + public String getBasePath() { return basePath; } {{#operation}} public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { - // create path and map variables - String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - {{#requiredParamCount}} // verify required params are set if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { @@ -44,11 +37,18 @@ public class {{classname}} { } {{/requiredParamCount}} + // create path and map variables + String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + {{#queryParams}}if(!"null".equals(String.valueOf({{paramName}}))) - queryParams.put("{{paramName}}", String.valueOf({{paramName}})); + queryParams.put("{{baseName}}", String.valueOf({{paramName}})); {{/queryParams}} - {{#headerParams}}headerParams.put("{{paramName}}", {{paramName}}); + {{#headerParams}}headerParams.put("{{baseName}}", {{paramName}}); {{/headerParams}} String contentType = "application/json"; @@ -72,4 +72,4 @@ public class {{classname}} { } {{/operation}} } -{{/operations}} \ No newline at end of file +{{/operations}} diff --git a/src/main/resources/android-java/apiInvoker.mustache b/src/main/resources/android-java/apiInvoker.mustache index 453adb690d0..425c2e7e004 100644 --- a/src/main/resources/android-java/apiInvoker.mustache +++ b/src/main/resources/android-java/apiInvoker.mustache @@ -9,11 +9,18 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize; import org.apache.http.*; import org.apache.http.client.*; import org.apache.http.client.methods.*; +import org.apache.http.conn.*; +import org.apache.http.conn.scheme.*; +import org.apache.http.conn.ssl.*; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.*; +import org.apache.http.impl.conn.*; +import org.apache.http.params.*; import org.apache.http.util.EntityUtils; import java.io.File; +import java.net.Socket; +import java.net.UnknownHostException; import java.net.URLEncoder; import java.util.Map; @@ -22,15 +29,50 @@ import java.util.List; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.security.GeneralSecurityException; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.cert.*; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; + +import java.util.Date; +import java.util.Random; +import java.util.logging.Level; +import java.util.logging.Logger; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + public class ApiInvoker { private static ApiInvoker INSTANCE = new ApiInvoker(); private Map defaultHeaderMap = new HashMap(); private HttpClient client = null; + + private boolean ignoreSSLCertificates = false; + + private ClientConnectionManager ignoreSSLConnectionManager; + + public ApiInvoker() { + initConnectionManager(); + } + public static ApiInvoker getInstance() { return INSTANCE; } + public void ignoreSSLCertificates(boolean ignoreSSLCertificates) { + this.ignoreSSLCertificates = ignoreSSLCertificates; + } + public void addDefaultHeader(String key, String value) { defaultHeaderMap.put(key, value); } @@ -114,8 +156,11 @@ public class ApiInvoker { } else if ("POST".equals(method)) { HttpPost post = new HttpPost(url); - post.setHeader("Content-Type", contentType); - post.setEntity(new StringEntity(serialize(body), "UTF-8")); + + if (body != null) { + post.setHeader("Content-Type", contentType); + post.setEntity(new StringEntity(serialize(body), "UTF-8")); + } for(String key : headers.keySet()) { post.setHeader(key, headers.get(key)); } @@ -139,6 +184,18 @@ public class ApiInvoker { } response = client.execute(delete); } + else if ("PATCH".equals(method)) { + HttpPatch patch = new HttpPatch(url); + + if (body != null) { + patch.setHeader("Content-Type", contentType); + patch.setEntity(new StringEntity(serialize(body), "UTF-8")); + } + for(String key : headers.keySet()) { + patch.setHeader(key, headers.get(key)); + } + response = client.execute(patch); + } int code = response.getStatusLine().getStatusCode(); String responseString = null; @@ -167,8 +224,60 @@ public class ApiInvoker { } private HttpClient getClient(String host) { - if(client == null) - client = new DefaultHttpClient(); + if (client == null) { + if (ignoreSSLCertificates && ignoreSSLConnectionManager != null) { + // Trust self signed certificates + client = new DefaultHttpClient(ignoreSSLConnectionManager, new BasicHttpParams()); + } else { + client = new DefaultHttpClient(); + } + } return client; } -} \ No newline at end of file + + private void initConnectionManager() { + try { + final SSLContext sslContext = SSLContext.getInstance("SSL"); + + // set up a TrustManager that trusts everything + TrustManager[] trustManagers = new TrustManager[] { + new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return null; + } + public void checkClientTrusted(X509Certificate[] certs, String authType) {} + public void checkServerTrusted(X509Certificate[] certs, String authType) {} + }}; + + sslContext.init(null, trustManagers, new SecureRandom()); + + SSLSocketFactory sf = new SSLSocketFactory((KeyStore)null) { + private javax.net.ssl.SSLSocketFactory sslFactory = sslContext.getSocketFactory(); + + public Socket createSocket(Socket socket, String host, int port, boolean autoClose) + throws IOException, UnknownHostException { + return sslFactory.createSocket(socket, host, port, autoClose); + } + + public Socket createSocket() throws IOException { + return sslFactory.createSocket(); + } + }; + + sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); + Scheme httpsScheme = new Scheme("https", sf, 443); + SchemeRegistry schemeRegistry = new SchemeRegistry(); + schemeRegistry.register(httpsScheme); + schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); + + ignoreSSLConnectionManager = new SingleClientConnManager(new BasicHttpParams(), schemeRegistry); + } catch (NoSuchAlgorithmException e) { + // This will only be thrown if SSL isn't available for some reason. + } catch (KeyManagementException e) { + // This might be thrown when passing a key into init(), but no key is being passed. + } catch (GeneralSecurityException e) { + // This catches anything else that might go wrong. + // If anything goes wrong we default to the standard connection manager. + } + } +} diff --git a/src/main/resources/android-java/httpPatch.mustache b/src/main/resources/android-java/httpPatch.mustache new file mode 100644 index 00000000000..55cec2f1279 --- /dev/null +++ b/src/main/resources/android-java/httpPatch.mustache @@ -0,0 +1,16 @@ +package {{invokerPackage}}; + +import org.apache.http.client.methods.*; + +public class HttpPatch extends HttpPost { + public static final String METHOD_PATCH = "PATCH"; + + public HttpPatch(final String url) { + super(url); + } + + @Override + public String getMethod() { + return METHOD_PATCH; + } +} \ No newline at end of file diff --git a/src/main/resources/android-java/pom.mustache b/src/main/resources/android-java/pom.mustache index 5ec4fd76a82..c595e16d83a 100644 --- a/src/main/resources/android-java/pom.mustache +++ b/src/main/resources/android-java/pom.mustache @@ -1,11 +1,11 @@ 4.0.0 - com.wordnik + {{groupId}} {{artifactId}} jar {{artifactId}} - 1.0.0 + {{artifactVersion}} scm:git:git@github.com:wordnik/swagger-mustache.git scm:git:git@github.com:wordnik/swagger-codegen.git @@ -207,7 +207,7 @@ 1.0.0 4.8.1 1.6.1 - 4.2.3 + 4.0 3.1.5 diff --git a/src/main/resources/csharp/apiInvoker.mustache b/src/main/resources/csharp/apiInvoker.mustache index c522d1545f6..8f1f0f43081 100644 --- a/src/main/resources/csharp/apiInvoker.mustache +++ b/src/main/resources/csharp/apiInvoker.mustache @@ -61,6 +61,7 @@ var client = WebRequest.Create(host + path + querystring); client.ContentType = "application/json"; + client.Method = method; foreach (var headerParamsItem in headerParams) { diff --git a/src/main/resources/objc/SWGApiClient.m b/src/main/resources/objc/SWGApiClient.m index 669fd4d570b..1c48412bc5a 100644 --- a/src/main/resources/objc/SWGApiClient.m +++ b/src/main/resources/objc/SWGApiClient.m @@ -280,7 +280,7 @@ static bool loggingEnabled = false; } if(body != nil) { - if([body isKindOfClass:[NSDictionary class]]){ + if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){ [request setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; } else if ([body isKindOfClass:[SWGFile class]]) {} diff --git a/src/main/resources/php/Swagger.mustache b/src/main/resources/php/Swagger.mustache index e7b7c11fbeb..0c3836a75eb 100644 --- a/src/main/resources/php/Swagger.mustache +++ b/src/main/resources/php/Swagger.mustache @@ -44,13 +44,12 @@ class APIClient { * @param array $queryParams parameters to be place in query URL * @param array $postData parameters to be placed in POST body * @param array $headerParams parameters to be place in request header - * @return unknown + * @return mixed */ public function callAPI($resourcePath, $method, $queryParams, $postData, $headerParams) { $headers = array(); - $headers[] = "Content-type: application/json"; # Allow API key from $headerParams to override default $added_api_key = False; @@ -67,7 +66,7 @@ class APIClient { } if (is_object($postData) or is_array($postData)) { - $postData = json_encode(self::sanitizeForSerialization($postData)); + $postData = json_encode($this->sanitizeForSerialization($postData)); } $url = $this->apiServer . $resourcePath; @@ -118,21 +117,35 @@ class APIClient { $response_info['http_code']); } - return $data; } /** * Build a JSON POST object */ - public static function sanitizeForSerialization($postData) { - foreach ($postData as $key => $value) { - if (is_a($value, "DateTime")) { - $postData->{$key} = $value->format(DateTime::ISO8601); - } - } - return $postData; - } + protected function sanitizeForSerialization($data) + { + if (is_scalar($data) || null === $data) { + $sanitized = $data; + } else if ($data instanceof \DateTime) { + $sanitized = $data->format(\DateTime::ISO8601); + } else if (is_array($data)) { + foreach ($data as $property => $value) { + $data[$property] = $this->sanitizeForSerialization($value); + } + $sanitized = $data; + } else if (is_object($data)) { + $values = array(); + foreach (array_keys($data::$swaggerTypes) as $property) { + $values[$property] = $this->sanitizeForSerialization($data->$property); + } + $sanitized = $values; + } else { + $sanitized = (string)$data; + } + + return $sanitized; + } /** * Take value and turn it into a string suitable for inclusion in @@ -170,72 +183,42 @@ class APIClient { return $value; } - /** - * Deserialize a JSON string into an object - * - * @param object $object object or primitive to be deserialized - * @param string $class class name is passed as a string - * @return object an instance of $class - */ - public static function deserialize($object, $class) { + /** + * Deserialize a JSON string into an object + * + * @param object $object object or primitive to be deserialized + * @param string $class class name is passed as a string + * @return object an instance of $class + */ - if (gettype($object) == "NULL") { - return $object; - } - - if (substr($class, 0, 6) == 'array[') { - $sub_class = substr($class, 6, -1); - $sub_objects = array(); - foreach ($object as $sub_object) { - $sub_objects[] = self::deserialize($sub_object, - $sub_class); + public static function deserialize($data, $class) + { + if (null === $data) { + $deserialized = null; + } else if (substr($class, 0, 6) == 'array[') { + $subClass = substr($class, 6, -1); + $values = array(); + foreach ($data as $value) { + $values[] = self::deserialize($value, $subClass); } - return $sub_objects; + $deserialized = $values; } elseif ($class == 'DateTime') { - return new DateTime($object); - } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { - settype($object, $class); - return $object; - } else { - $instance = new $class(); // this instantiates class named $class - $classVars = get_class_vars($class); - } + $deserialized = new \DateTime($data); + } elseif (in_array($class, array('string', 'int', 'float', 'bool'))) { + settype($data, $class); + $deserialized = $data; + } else { + $instance = new $class(); + foreach ($instance::$swaggerTypes as $property => $type) { + if (isset($data->$property)) { + $instance->$property = self::deserialize($data->$property, $type); + } + } + $deserialized = $instance; + } - foreach ($object as $property => $value) { + return $deserialized; + } - // Need to handle possible pluralization differences - $true_property = $property; - - if (! property_exists($class, $true_property)) { - if (substr($property, -1) == 's') { - $true_property = substr($property, 0, -1); - } - } - - if (array_key_exists($true_property, $classVars['swaggerTypes'])) { - $type = $classVars['swaggerTypes'][$true_property]; - } else { - $type = 'string'; - } - if (in_array($type, array('string', 'int', 'float', 'bool'))) { - settype($value, $type); - $instance->{$true_property} = $value; - } elseif (preg_match("/array<(.*)>/", $type, $matches)) { - $sub_class = $matches[1]; - $instance->{$true_property} = array(); - foreach ($value as $sub_property => $sub_value) { - $instance->{$true_property}[] = self::deserialize($sub_value, - $sub_class); - } - } else { - $instance->{$true_property} = self::deserialize($value, $type); - } - } - return $instance; - } } - -?> - - diff --git a/src/main/resources/php/api.mustache b/src/main/resources/php/api.mustache index fa081768fa8..87a2a0a197d 100644 --- a/src/main/resources/php/api.mustache +++ b/src/main/resources/php/api.mustache @@ -45,6 +45,8 @@ class {{classname}} { $method = "{{httpMethod}}"; $queryParams = array(); $headerParams = array(); + $headerParams['Accept'] = '{{produces}}'; + $headerParams['Content-Type'] = '{{consume}}'; {{#queryParams}} if(${{paramName}} != null) { diff --git a/src/main/resources/ruby/swagger/configuration.mustache b/src/main/resources/ruby/swagger/configuration.mustache index b86775d8135..c0b3c46268c 100644 --- a/src/main/resources/ruby/swagger/configuration.mustache +++ b/src/main/resources/ruby/swagger/configuration.mustache @@ -3,8 +3,7 @@ module Swagger class Configuration require 'swagger/version' - attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, - :user_agent, :logger, :inject_format + attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params # Defaults go in here.. def initialize @@ -14,8 +13,10 @@ module Swagger @base_path = '/v4' @user_agent = "ruby-#{Swagger::VERSION}" @inject_format = true + @force_ending_format = false + @camelize_params = true end end -end +end \ No newline at end of file diff --git a/src/main/resources/ruby/swagger/request.mustache b/src/main/resources/ruby/swagger/request.mustache index 685ee8b455f..7836cb0bf03 100644 --- a/src/main/resources/ruby/swagger/request.mustache +++ b/src/main/resources/ruby/swagger/request.mustache @@ -87,6 +87,15 @@ module Swagger end end + # Stick a .{format} placeholder on the end of the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words/blah.{format} + if Swagger.configuration.force_ending_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = "#{p}.#{format}" + end + end + p = p.sub("{format}", self.format.to_s) URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') @@ -121,7 +130,9 @@ module Swagger self.params.each_pair do |key, value| next if self.path.include? "{#{key}}" # skip path params next if value.blank? && value.class != FalseClass # skip empties - key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + if Swagger.configuration.camelize_params + key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + end query_values[key] = value.to_s end @@ -185,4 +196,4 @@ module Swagger end end -end +end \ No newline at end of file diff --git a/src/main/resources/scala/pom.mustache b/src/main/resources/scala/pom.mustache index 5070b8c06e1..4cb2c261fad 100644 --- a/src/main/resources/scala/pom.mustache +++ b/src/main/resources/scala/pom.mustache @@ -1,11 +1,11 @@ 4.0.0 - com.wordnik - swagger-client + {{groupId}} + {{artifactId}} jar - swagger-client - 1.0 + {{artifactId}} + {{apiVersion}} 2.2.0 @@ -170,13 +170,13 @@ com.wordnik - swagger-core_2.9.1 + swagger-core_${scala-short-version} ${swagger-core-version} compile org.scalatest - scalatest_2.9.1 + scalatest_${scala-short-version} ${scala-test-version} test @@ -187,15 +187,34 @@ test + + + scala_2.10 + + 2.10.3 + 2.10 + 1.3.2 + 2.1.2 + + + + scala_2.9.1 + + true + + + 2.9.1-1 + 2.9.1 + 1.1.0 + 1.6.1 + + + 1.7 - 1.1.0 - 2.9.1-1 4.8.1 1.0.0 - 1.6.1 4.8.1 - 1.6.1 3.1.5 diff --git a/src/main/resources/swagger-static/assets/js/main.js b/src/main/resources/swagger-static/assets/js/main.js index d80666acad2..660d628567c 100644 --- a/src/main/resources/swagger-static/assets/js/main.js +++ b/src/main/resources/swagger-static/assets/js/main.js @@ -60,4 +60,16 @@ function goToAnchor() { window.scrollTo(0,$('a[name='+anchor+']').offset().top - 80); } } +function resize() +{ + $(".sidebar").css('height', $(window).height() -60); + $("#content-window").css('height', $(window).height() -60); +} +$(function(){ + window.onresize = resize; + resize(); + $(window).bind('hashchange', function() { + choose(window.location.href.toString()); + }); +}); \ 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 fd65f66ccdc..1821b19d506 100644 --- a/src/main/resources/swagger-static/index.mustache +++ b/src/main/resources/swagger-static/index.mustache @@ -32,12 +32,12 @@ {{#apis}}
diff --git a/src/main/resources/swagger-static/model.mustache b/src/main/resources/swagger-static/model.mustache index 9020c422e6e..fd107aa1fef 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/main/scala/com/wordnik/swagger/codegen/BasicAndroidJavaClient.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicAndroidJavaClient.scala index e34f3ae5356..111e0b7d896 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicAndroidJavaClient.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/BasicAndroidJavaClient.scala @@ -14,15 +14,17 @@ * limitations under the License. */ +package com.wordnik.swagger.codegen + import com.wordnik.swagger.codegen.BasicJavaGenerator import com.wordnik.swagger.model._ -object BasicAndroidJavaClient extends BasicJavaGenerator { +object BasicAndroidJavaClient extends BasicAndroidJavaGenerator { def main(args: Array[String]) = generateClient(args) +} - override def templateDir = "src/main/resources/android-java" - +class BasicAndroidJavaGenerator extends BasicJavaGenerator { override def typeMapping = super.typeMapping ++ Map( "file" -> "File") @@ -42,15 +44,11 @@ object BasicAndroidJavaClient extends BasicJavaGenerator { "AnyRef", "Any") - additionalParams ++= Map( - "artifactId" -> "swagger-android-client", - "artifactVersion" -> "1.0.0", - "groupId" -> "com.wordnik" - ) - // package for api invoker, error files override def invokerPackage = Some("com.wordnik.client") + override def templateDir = "android-java" + // where to write generated code override def destinationDir = "generated-code/android-java/src/main/java" @@ -60,12 +58,21 @@ object BasicAndroidJavaClient extends BasicJavaGenerator { // package for api classes override def apiPackage = 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", "android-java", "pom.xml") + ("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") ) -} \ No newline at end of file +} diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicCSharpGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicCSharpGenerator.scala index 580955769c5..9454ab84c13 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicCSharpGenerator.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/BasicCSharpGenerator.scala @@ -102,7 +102,7 @@ class BasicCSharpGenerator extends BasicGenerator { val ComplexTypeMatcher = "(.*)\\[(.*)\\].*".r val t = e match { case ComplexTypeMatcher(container, inner) => { - e.replaceAll(container, typeMapping.getOrElse(container, container)) + e.replaceAll(container, typeMapping.getOrElse(container.toLowerCase, container)) } case _ => e } @@ -126,8 +126,8 @@ class BasicCSharpGenerator extends BasicGenerator { override def toDeclaration(obj: ModelProperty) = { var declaredType = toDeclaredType(obj.`type`) - declaredType match { - case "Array" => declaredType = "List" + declaredType.toLowerCase match { + case "array" => declaredType = "List" case e: String => e } diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicGenerator.scala index e426d90d687..87f19065390 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicGenerator.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/BasicGenerator.scala @@ -43,26 +43,18 @@ abstract class BasicGenerator extends CodegenConfig with PathUtil { var codegen = new Codegen(this) - def generateClient(args: Array[String]) = { + def generateClient(args: Array[String]): Unit = { + generateClientWithoutExit(args) + System.exit(0) + } + + 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 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 apiKey = if(args.length > 1) Some(args(1)) else None + val authorization = authenticate(apiKey) val doc = { try { ResourceExtractor.fetchListing(getResourcePath(host), authorization) @@ -71,13 +63,7 @@ abstract class BasicGenerator extends CodegenConfig with PathUtil { } } - implicit val basePath = getBasePath(host, doc.basePath) - println("base path is " + basePath) - - val apiReferences = doc.apis - if (apiReferences == null) - throw new Exception("No APIs specified by resource") - val apis = ApiExtractor.fetchApiListings(doc.swaggerVersion, basePath, apiReferences, authorization) + val apis: List[ApiListing] = getApis(host, doc, authorization) SwaggerSerializers.validationMessages.filter(_.level == ValidationMessage.ERROR).size match { case i: Int if i > 0 => { @@ -92,7 +78,8 @@ abstract class BasicGenerator extends CodegenConfig with PathUtil { } case 0 => } - + implicit val basePath = getBasePath(host, doc.basePath) + new SwaggerSpecValidator(doc, apis).validate() val allModels = new HashMap[String, Model] @@ -128,8 +115,33 @@ abstract class BasicGenerator extends CodegenConfig with PathUtil { println("wrote api " + filename) }) - codegen.writeSupportingClasses(operationMap, allModels.toMap) - System.exit(0) + codegen.writeSupportingClasses(operationMap, allModels.toMap, doc.apiVersion) + } + + + def getApis(host: String, doc: ResourceListing, authorization: Option[ApiKeyValue]): List[ApiListing] = { + implicit val basePath = getBasePath(host, doc.basePath) + 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) = { diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala index f624d6781a8..9f707df2a83 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala @@ -27,6 +27,8 @@ class BasicJavaGenerator extends BasicGenerator { "double", "int", "long", + "short", + "char", "float", "String", "boolean", @@ -52,6 +54,8 @@ class BasicJavaGenerator extends BasicGenerator { "int" -> "Integer", "float" -> "Float", "long" -> "Long", + "short" -> "Short", + "char" -> "String", "double" -> "Double", "object" -> "Object", "integer" -> "Integer") @@ -82,7 +86,12 @@ class BasicJavaGenerator extends BasicGenerator { "Date" -> "java.util.Date", "Array" -> "java.util.*", "ArrayList" -> "java.util.*", - "List" -> "java.util.*") + "List" -> "java.util.*", + "DateTime" -> "org.joda.time.*", + "LocalDateTime" -> "org.joda.time.*", + "LocalDate" -> "org.joda.time.*", + "LocalTime" -> "org.joda.time.*" + ) // package for models override def modelPackage = Some("com.wordnik.client.model") @@ -174,6 +183,15 @@ class BasicJavaGenerator extends BasicGenerator { (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). @@ -183,6 +201,7 @@ class BasicJavaGenerator extends BasicGenerator { case "Boolean" => "null" case "Integer" => "null" case "Long" => "null" + case "Short" => "null" case "Float" => "null" case "Double" => "null" case "List" => { diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala index 02806438963..4dec4c0ec16 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala @@ -82,10 +82,11 @@ class BasicObjcGenerator extends BasicGenerator { // objective c doesn't like variables starting with "new" override def toVarName(name: String): String = { - if(name.startsWith("new") || reservedWords.contains(name)) { - escapeReservedWord(name) + val paramName = name.replaceAll("[^a-zA-Z0-9_]","") + if(paramName.startsWith("new") || reservedWords.contains(paramName)) { + escapeReservedWord(paramName) } - else name + else paramName } // naming for the apis @@ -103,13 +104,13 @@ class BasicObjcGenerator extends BasicGenerator { apiTemplateFiles += "api-body.mustache" -> ".m" // package for models - override def invokerPackage = None + override def invokerPackage: Option[String] = None // package for models - override def modelPackage = None + override def modelPackage: Option[String] = None // package for api classes - override def apiPackage = None + override def apiPackage: Option[String] = None // response classes override def processResponseClass(responseClass: String): Option[String] = { diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicPHPGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicPHPGenerator.scala index 58528d083b3..34af8caf977 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicPHPGenerator.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/BasicPHPGenerator.scala @@ -152,9 +152,6 @@ class BasicPHPGenerator extends BasicGenerator { (declaredType, defaultValue) } - // escape keywords - override def escapeReservedWord(word: String) = "`" + word + "`" - // supporting classes override def supportingFiles = List( ("Swagger.mustache", destinationDir + File.separator + apiPackage.get, diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicRubyGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicRubyGenerator.scala index ed949efc7fa..0c7441f3216 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicRubyGenerator.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/BasicRubyGenerator.scala @@ -26,10 +26,6 @@ object BasicRubyGenerator extends BasicRubyGenerator { class BasicRubyGenerator extends BasicGenerator { - override def toApiName(name: String) = { - name(0).toUpper + name.substring(1) + "_api" - } - override def apiPackage = Some("lib") // location of templates @@ -58,9 +54,13 @@ class BasicRubyGenerator extends BasicGenerator { } } - override def toModelFilename(name: String) = name.toLowerCase - override def toApiFilename(name: String) = name.toLowerCase + "_api" + 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) diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicScalaGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicScalaGenerator.scala index 3df3a3b2934..e60ff2f0dfd 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicScalaGenerator.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/BasicScalaGenerator.scala @@ -205,6 +205,15 @@ class BasicScalaGenerator extends BasicGenerator { // 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"), diff --git a/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala b/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala index d78bae95110..3aa72cbe975 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala @@ -81,12 +81,12 @@ class Codegen(config: CodegenConfig) { lb }) opList += apiToMap(apiPath, operation) - + CoreUtils.extractModelNames(operation).foreach(i => allImports += i) } }) } - + case None => } @@ -188,6 +188,19 @@ class Codegen(config: CodegenConfig) { (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 => { @@ -210,14 +223,14 @@ class Codegen(config: CodegenConfig) { 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 => { + operation.responseMessages.foreach(param => { val params = new HashMap[String, AnyRef] params += "code" -> param.code.toString() params += "reason" -> param.message params += "hasMore" -> "true" - errorList += params + errorList += params }) } @@ -242,6 +255,8 @@ class Codegen(config: CodegenConfig) { } 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) @@ -295,17 +310,18 @@ class Codegen(config: CodegenConfig) { val requiredParams = new ListBuffer[HashMap[String, AnyRef]] paramList.filter(p => p.contains("required") && p("required") == "true").foreach(param => { - requiredParams += HashMap( - "paramName" -> param("paramName"), - "defaultValue" -> param("defaultValue"), - "baseName" -> param("baseName"), - "hasMore" -> "true") + 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" @@ -368,6 +384,32 @@ class Codegen(config: CodegenConfig) { "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 => { @@ -406,6 +448,7 @@ class Codegen(config: CodegenConfig) { "classname" -> config.toModelName(className), "classVarName" -> config.toVarName(className), // suggested name of object created from this class "modelPackage" -> config.modelPackage, + "description" -> model.description, "newline" -> "\n") val l = new ListBuffer[AnyRef] @@ -466,6 +509,7 @@ class Codegen(config: CodegenConfig) { "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), @@ -478,12 +522,11 @@ class Codegen(config: CodegenConfig) { case true => properties += "isPrimitiveType" -> "true" case _ => properties += "complexType" -> config.toModelName(baseType) } - l += properties }) - l.size match { - case 0 => - case _ => l.last.asInstanceOf[HashMap[String, String]] -= "hasMore" + if(l.size > 0) { + val last = l.last.asInstanceOf[HashMap[String, String]] + last.remove("hasMore") } data += "vars" -> l data += "imports" -> imports.toSet @@ -512,87 +555,110 @@ class Codegen(config: CodegenConfig) { write(m) } - def writeSupportingClasses(apis: Map[(String, String), List[(String, Operation)]], models: Map[String, Model]) = { - val rootDir = new java.io.File(".") - val engine = new TemplateEngine(Some(rootDir)) + final def writeSupportingClasses( + apis: Map[(String, String), List[(String, Operation)]], + models: Map[String, Model], + apiVersion: String, + rootDir: Option[File], + dataF: (Map[(String, String), List[(String, Operation)]], Map[String, Model]) => Map[String, AnyRef]): Seq[File] = { - val apiList = new ListBuffer[Map[String, AnyRef]] - apis.foreach(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 - }) - }) + val engine = new TemplateEngine(rootDir orElse Some(new File("."))) + val data = dataF(apis, models) - val modelList = new ListBuffer[HashMap[String, AnyRef]] - - models.foreach(m => { - val json = writeJson(m._2) - - modelList += HashMap( - "modelName" -> m._1, - "model" -> modelToMap(m._1, m._2), - "filename" -> config.toModelFilename(m._1), - "modelJson" -> json, - "hasMore" -> "true") - }) - modelList.size match { - case 0 => - case _ => modelList.last.asInstanceOf[HashMap[String, String]] -= "hasMore" - } - - val data: HashMap[String, AnyRef] = - HashMap( - "invokerPackage" -> config.invokerPackage, - "package" -> config.packageName, - "modelPackage" -> config.modelPackage, - "apiPackage" -> config.apiPackage, - "apis" -> apiList, - "models" -> modelList) ++ config.additionalParams - - config.supportingFiles.map(file => { + val outputFiles = config.supportingFiles map { file => val supportingFile = file._1 val outputDir = file._2 val destFile = file._3 - val outputFilename = outputDir + File.separator + destFile - val outputFolder = new File(outputFilename).getParent + val outputFile = new File(outputDir.replaceAll("\\.", File.separator) + File.separator + destFile) + val outputFolder = outputFile.getParent new File(outputFolder).mkdirs if (supportingFile.endsWith(".mustache")) { val output = { - val (resourceName, (_, template)) = compileTemplate(supportingFile, Some(rootDir), Some(engine)) + val (resourceName, (_, template)) = compileTemplate(supportingFile, rootDir, Some(engine)) engine.layout(resourceName, template, data.toMap) } - val fw = new FileWriter(outputFilename, false) + val fw = new FileWriter(outputFile, false) fw.write(output + "\n") fw.close() - println("wrote " + outputFilename) + println("wrote " + outputFile.getPath()) } else { val file = new File(config.templateDir + File.separator + supportingFile) - if(file.isDirectory()) { + 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 outputFile = new File(outputFilename) - val parentDir = new File(outputFile.getParent) + val parentDir = outputFile.getParentFile() if (parentDir != null && !parentDir.exists) { println("making directory: " + parentDir.toString + ": " + parentDir.mkdirs) } - FileUtils.copyInputStreamToFile(is, new File(outputFilename)) - println("copied " + outputFilename) + 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 + } + + def writeSupportingClasses(apis: Map[(String, String), List[(String, Operation)]], + models: Map[String, Model], apiVersion: String): Seq[File] = { + + val rootDir: Option[File] = Some(new File(".")) + + def apiListF(apis: Map[(String, String), List[(String, Operation)]]): List[Map[String, AnyRef]] = { + val apiList = new ListBuffer[Map[String, AnyRef]] + apis.foreach(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" -> apiToMap(t._1, 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 = writeJson(m._2) + modelList += HashMap( + "modelName" -> m._1, + "model" -> modelToMap(m._1, m._2), + "filename" -> config.toModelFilename(m._1), + "modelJson" -> json, + "hasMoreModels" -> "true") + }) + modelList.size match { + case 0 => + case _ => modelList.last.asInstanceOf[HashMap[String, String]] -= "hasMoreModels" + } + + modelList.map(_.toMap).toList + } + + def dataF(apis: Map[(String, String), List[(String, Operation)]], + models: Map[String, Model]): Map[String, AnyRef] = + Map( + "invokerPackage" -> config.invokerPackage, + "package" -> config.packageName, + "modelPackage" -> config.modelPackage, + "apiPackage" -> config.apiPackage, + "apis" -> apiListF(apis), + "models" -> modelListF(models), + "apiVersion" -> apiVersion) ++ config.additionalParams + + writeSupportingClasses(apis, models, apiVersion, rootDir, dataF) } protected def isListType(dt: String) = isCollectionType(dt, "List") || isCollectionType(dt, "Array") || isCollectionType(dt, "Set") diff --git a/src/main/scala/com/wordnik/swagger/codegen/ScalaAsyncClientGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/ScalaAsyncClientGenerator.scala index 7dd2b47e3e9..5ae7574ad76 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/ScalaAsyncClientGenerator.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/ScalaAsyncClientGenerator.scala @@ -114,91 +114,55 @@ object ScalaAsyncClientGenerator extends App { } 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]) = { - val engine = new TemplateEngine(rootDir orElse Some(new File("."))) - val apiList = new ListBuffer[Map[String, AnyRef]] + override def writeSupportingClasses(apis: Map[(String, String), List[(String, Operation)]], + models: Map[String, Model], apiVersion: String): Seq[File] = { - 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 - }) - }) - - - - val modelList = new ListBuffer[HashMap[String, AnyRef]] - - models.foreach(m => { - val json = write(m._2) + 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.size match { + case 0 => + case _ => modelList.last.asInstanceOf[HashMap[String, String]] -= "hasMore" + } + modelList.map(_.toMap).toList } - val data = + 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" -> apiList, - "models" -> modelList) + "apis" -> apiListF(apis), + "models" -> modelListF(models)) - config.supportingFiles.map(file => { - val supportingFile = file._1 - val outputDir = file._2 - val destFile = file._3 - - val outputFilename = outputDir.replaceAll("\\.", File.separator) + File.separator + destFile - val outputFolder = new File(outputFilename).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(outputFilename, false) - fw.write(output + "\n") - fw.close() - println("wrote " + outputFilename) - } 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 outputFile = new File(outputFilename) - val parentDir = new File(outputFile.getParent) - if (parentDir != null && !parentDir.exists) { - println("making directory: " + parentDir.toString + ": " + parentDir.mkdirs) - } - FileUtils.copyInputStreamToFile(is, new File(outputFilename)) - println("copied " + outputFilename) - is.close - } - } - }) - //a shutdown method will be added to scalate in an upcoming release - - engine.compiler.shutdown() + writeSupportingClasses(apis, models, apiVersion, rootDir, dataF) } override protected def compileTemplate(templateFile: String, rootDir: Option[File] = None, engine: Option[TemplateEngine] = None): (String, (TemplateEngine, Template)) = { @@ -377,7 +341,7 @@ class ScalaAsyncClientGenerator(cfg: SwaggerGenConfig) extends BasicGenerator { println("wrote api " + filename) }) - codegen.writeSupportingClasses(operationMap, allModels.toMap) + codegen.writeSupportingClasses(operationMap, allModels.toMap, doc.apiVersion) } diff --git a/src/main/scala/com/wordnik/swagger/codegen/language/CodegenConfig.scala b/src/main/scala/com/wordnik/swagger/codegen/language/CodegenConfig.scala index 5514a7af4e7..8176b7a69b3 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/language/CodegenConfig.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/language/CodegenConfig.scala @@ -96,14 +96,20 @@ abstract class CodegenConfig { case "boolean" => "is" case _ => "get" } - base + name(0).toUpper + name.substring(1) + 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 + name(0).toUpper + name.substring(1) + base + { + if (name.length > 0) name(0).toUpper + name.substring(1) + else "" + } } def toVarName(name: String): String = { diff --git a/src/main/scala/com/wordnik/swagger/codegen/util/RemoteUrl.scala b/src/main/scala/com/wordnik/swagger/codegen/util/RemoteUrl.scala index b673230c661..826a3ec9f34 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/util/RemoteUrl.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/util/RemoteUrl.scala @@ -30,6 +30,15 @@ trait RemoteUrl { 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() } diff --git a/src/main/scala/com/wordnik/swagger/model/LegacySerializers.scala b/src/main/scala/com/wordnik/swagger/model/LegacySerializers.scala index 5d6109b71c3..a217db0513f 100644 --- a/src/main/scala/com/wordnik/swagger/model/LegacySerializers.scala +++ b/src/main/scala/com/wordnik/swagger/model/LegacySerializers.scala @@ -183,6 +183,10 @@ object LegacySerializers { 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({ @@ -204,7 +208,7 @@ object LegacySerializers { (json \ "produces").extract[List[String]], (json \ "consumes").extract[List[String]], (json \ "protocols").extract[List[String]], - (json \ "authorizations").extract[List[String]], + authorizations, (json \ "parameters").extract[List[Parameter]], (json \ "errorResponses").extract[List[ResponseMessage]], (json \ "deprecated").extractOpt[String] diff --git a/src/main/scala/com/wordnik/swagger/model/SwaggerModelSerializer.scala b/src/main/scala/com/wordnik/swagger/model/SwaggerModelSerializer.scala index 8b63333f07d..3cf837e9d42 100644 --- a/src/main/scala/com/wordnik/swagger/model/SwaggerModelSerializer.scala +++ b/src/main/scala/com/wordnik/swagger/model/SwaggerModelSerializer.scala @@ -100,6 +100,10 @@ object SwaggerSerializers { 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 + } ApiListing( (json \ "apiVersion").extractOrElse({ !!(json, RESOURCE, "apiVersion", "missing required field", ERROR) @@ -120,7 +124,7 @@ object SwaggerSerializers { (json \ "produces").extract[List[String]], (json \ "consumes").extract[List[String]], (json \ "protocols").extract[List[String]], - (json \ "authorizations").extract[List[String]], + authorizations, (json \ "apis").extract[List[ApiDescription]], (json \ "models").extractOpt[Map[String, Model]], (json \ "description").extractOpt[String], @@ -238,6 +242,10 @@ object SwaggerSerializers { 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("")) @@ -291,7 +299,7 @@ object SwaggerSerializers { (json \ "produces").extract[List[String]], (json \ "consumes").extract[List[String]], (json \ "protocols").extract[List[String]], - (json \ "authorizations").extract[List[String]], + authorizations, (json \ "parameters").extract[List[Parameter]], (json \ "responseMessages").extract[List[ResponseMessage]], (json \ "deprecated").extractOpt[String] @@ -347,10 +355,16 @@ object SwaggerSerializers { 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 != "") diff --git a/src/main/scala/com/wordnik/swagger/model/SwaggerModels.scala b/src/main/scala/com/wordnik/swagger/model/SwaggerModels.scala index 2257f8259e0..89aefb884a4 100644 --- a/src/main/scala/com/wordnik/swagger/model/SwaggerModels.scala +++ b/src/main/scala/com/wordnik/swagger/model/SwaggerModels.scala @@ -76,7 +76,7 @@ case class ApiListing ( var produces: List[String] = List.empty, var consumes: List[String] = List.empty, var protocols: List[String] = List.empty, - var authorizations: List[String] = List.empty, + var authorizations: List[AuthorizationType] = List.empty, apis: List[ApiDescription] = List(), models: Option[Map[String, Model]] = None, description: Option[String] = None, @@ -97,7 +97,7 @@ case class Operation ( var produces: List[String] = List.empty, var consumes: List[String] = List.empty, var protocols: List[String] = List.empty, - var authorizations: List[String] = List.empty, + var authorizations: List[AuthorizationType] = List.empty, parameters: List[Parameter] = List.empty, responseMessages: List[ResponseMessage] = List.empty, `deprecated`: Option[String] = None) diff --git a/src/test/resources/petstore-1.2/api-docs b/src/test/resources/petstore-1.2/api-docs index 252fc4d5e39..370eca562a7 100644 --- a/src/test/resources/petstore-1.2/api-docs +++ b/src/test/resources/petstore-1.2/api-docs @@ -6,49 +6,52 @@ "path": "/pet", "description": "Operations about pets" }, - { - "path": "/store", - "description": "Operations about store" - }, { "path": "/user", "description": "Operations about user" + }, + { + "path": "/store", + "description": "Operations about store" } ], "authorizations": { "oauth2": { "type": "oauth2", "scopes": [ - "PUBLIC" + { + "scope": "email", + "description": "Access to your email address" + }, + { + "scope": "pets", + "description": "Access to your pets" + } ], "grantTypes": { "implicit": { "loginEndpoint": { - "url": "http://localhost:8002/oauth/dialog" + "url": "http://petstore.swagger.wordnik.com/oauth/dialog" }, - "tokenName": "access_code" + "tokenName": "access_token" }, "authorization_code": { "tokenRequestEndpoint": { - "url": "http://localhost:8002/oauth/requestToken", + "url": "http://petstore.swagger.wordnik.com/oauth/requestToken", "clientIdName": "client_id", "clientSecretName": "client_secret" }, "tokenEndpoint": { - "url": "http://localhost:8002/oauth/token", + "url": "http://petstore.swagger.wordnik.com/oauth/token", "tokenName": "access_code" } } } - }, - "apiKey": { - "type": "apiKey", - "passAs": "header" } }, "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.", + "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", diff --git a/src/test/resources/petstore-1.2/pet b/src/test/resources/petstore-1.2/pet index 7f1c17ecd72..4a8439a4424 100644 --- a/src/test/resources/petstore-1.2/pet +++ b/src/test/resources/petstore-1.2/pet @@ -1,7 +1,7 @@ { "apiVersion": "1.0.0", "swaggerVersion": "1.2", - "basePath": "http://localhost:8002/api", + "basePath": "http://petstore.swagger.wordnik.com/api", "resourcePath": "/pet", "produces": [ "application/json", @@ -19,21 +19,17 @@ "notes": "Returns a pet based on ID", "type": "Pet", "nickname": "getPetById", - "produces": [ - "application/json", - "application/xml" - ], - "authorizations": [ - "oauth2" - ], + "authorizations": {}, "parameters": [ { "name": "petId", "description": "ID of pet that needs to be fetched", "required": true, - "allowMultiple": false, - "type": "string", - "paramType": "path" + "type": "integer", + "format": "int64", + "paramType": "path", + "minimum": "1.0", + "maximum": "100000.0" } ], "responseMessages": [ @@ -47,18 +43,120 @@ } ] }, + { + "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, - "allowMultiple": false, "type": "string", "paramType": "path" } @@ -75,41 +173,18 @@ { "path": "/pet", "operations": [ - { - "method": "POST", - "summary": "Add a new pet to the store", - "notes": "", - "type": "void", - "nickname": "addPet", - "parameters": [ - { - "name": "body", - "description": "Pet object that needs to be added to the store", - "required": true, - "allowMultiple": false, - "type": "Pet", - "paramType": "body" - } - ], - "responseMessages": [ - { - "code": 405, - "message": "Invalid input" - } - ] - }, { "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, - "allowMultiple": false, "type": "Pet", "paramType": "body" } @@ -128,6 +203,40 @@ "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" + } + ] } ] }, @@ -143,17 +252,13 @@ "$ref": "Pet" }, "nickname": "findPetsByStatus", - "produces": [ - "application/json", - "application/xml" - ], + "authorizations": {}, "parameters": [ { "name": "status", "description": "Status values that need to be considered for filter", "defaultValue": "available", "required": true, - "allowMultiple": true, "type": "string", "paramType": "query", "enum": [ @@ -184,16 +289,12 @@ "$ref": "Pet" }, "nickname": "findPetsByTags", - "produces": [ - "application/json", - "application/xml" - ], + "authorizations": {}, "parameters": [ { "name": "tags", "description": "Tags to filter by", "required": true, - "allowMultiple": true, "type": "string", "paramType": "query" } @@ -207,24 +308,66 @@ "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": { - "name": { - "type": "string" - }, "id": { "type": "integer", "format": "int64" + }, + "name": { + "type": "string" } } }, "Pet": { "id": "Pet", - "description": "A pet is a person's best friend", "required": [ "id", "name" @@ -232,7 +375,22 @@ "properties": { "id": { "type": "integer", - "format": "int64" + "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", @@ -240,9 +398,6 @@ "$ref": "Tag" } }, - "name": { - "type": "string" - }, "status": { "type": "string", "description": "pet status in the store", @@ -251,27 +406,18 @@ "pending", "sold" ] - }, - "category": { - "$ref": "Category" - }, - "photoUrls": { - "type": "array", - "items": { - "type": "string" - } } } }, "Category": { "id": "Category", "properties": { - "name": { - "type": "string" - }, "id": { "type": "integer", "format": "int64" + }, + "name": { + "type": "string" } } } diff --git a/src/test/resources/petstore-1.2/store b/src/test/resources/petstore-1.2/store index 040ceeca274..f7670669dfe 100644 --- a/src/test/resources/petstore-1.2/store +++ b/src/test/resources/petstore-1.2/store @@ -1,11 +1,10 @@ { "apiVersion": "1.0.0", "swaggerVersion": "1.2", - "basePath": "http://localhost:8002/api", + "basePath": "http://petstore.swagger.wordnik.com/api", "resourcePath": "/store", "produces": [ - "application/json", - "application/xml" + "application/json" ], "apis": [ { @@ -17,16 +16,12 @@ "notes": "For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors", "type": "Order", "nickname": "getOrderById", - "produces": [ - "application/json", - "application/xml" - ], + "authorizations": {}, "parameters": [ { "name": "orderId", "description": "ID of pet that needs to be fetched", "required": true, - "allowMultiple": false, "type": "string", "paramType": "path" } @@ -48,12 +43,19 @@ "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, - "allowMultiple": false, "type": "string", "paramType": "path" } @@ -80,12 +82,19 @@ "notes": "", "type": "void", "nickname": "placeOrder", + "authorizations": { + "oauth2": [ + { + "scope": "test:anything", + "description": "anything" + } + ] + }, "parameters": [ { "name": "body", "description": "order placed for purchasing the pet", "required": true, - "allowMultiple": false, "type": "Order", "paramType": "body" } @@ -108,15 +117,6 @@ "type": "integer", "format": "int64" }, - "status": { - "type": "string", - "description": "Order Status", - "enum": [ - "placed", - "approved", - "delivered" - ] - }, "petId": { "type": "integer", "format": "int64" @@ -125,6 +125,15 @@ "type": "integer", "format": "int32" }, + "status": { + "type": "string", + "description": "Order Status", + "enum": [ + "placed", + " approved", + " delivered" + ] + }, "shipDate": { "type": "string", "format": "date-time" diff --git a/src/test/resources/petstore-1.2/user b/src/test/resources/petstore-1.2/user index 7f0e6764a5f..c9eb3f6ff78 100644 --- a/src/test/resources/petstore-1.2/user +++ b/src/test/resources/petstore-1.2/user @@ -1,11 +1,10 @@ { "apiVersion": "1.0.0", "swaggerVersion": "1.2", - "basePath": "http://localhost:8002/api", + "basePath": "http://petstore.swagger.wordnik.com/api", "resourcePath": "/user", "produces": [ - "application/json", - "application/xml" + "application/json" ], "apis": [ { @@ -17,12 +16,19 @@ "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, - "allowMultiple": false, "type": "User", "paramType": "body" } @@ -30,6 +36,20 @@ } ] }, + { + "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": [ @@ -39,12 +59,19 @@ "notes": "", "type": "void", "nickname": "createUsersWithArrayInput", + "authorizations": { + "oauth2": [ + { + "scope": "test:anything", + "description": "anything" + } + ] + }, "parameters": [ { "name": "body", "description": "List of user object", "required": true, - "allowMultiple": false, "type": "array", "items": { "$ref": "User" @@ -64,12 +91,19 @@ "notes": "", "type": "void", "nickname": "createUsersWithListInput", + "authorizations": { + "oauth2": [ + { + "scope": "test:anything", + "description": "anything" + } + ] + }, "parameters": [ { "name": "body", "description": "List of user object", "required": true, - "allowMultiple": false, "type": "array", "items": { "$ref": "User" @@ -89,12 +123,19 @@ "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, - "allowMultiple": false, "type": "string", "paramType": "path" }, @@ -102,7 +143,6 @@ "name": "body", "description": "Updated user object", "required": true, - "allowMultiple": false, "type": "User", "paramType": "body" } @@ -124,12 +164,19 @@ "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, - "allowMultiple": false, "type": "string", "paramType": "path" } @@ -151,16 +198,12 @@ "notes": "", "type": "User", "nickname": "getUserByName", - "produces": [ - "application/json", - "application/xml" - ], + "authorizations": {}, "parameters": [ { "name": "username", "description": "The name that needs to be fetched. Use user1 for testing.", "required": true, - "allowMultiple": false, "type": "string", "paramType": "path" } @@ -187,15 +230,12 @@ "notes": "", "type": "string", "nickname": "loginUser", - "produces": [ - "text/plain" - ], + "authorizations": {}, "parameters": [ { "name": "username", "description": "The user name for login", "required": true, - "allowMultiple": false, "type": "string", "paramType": "query" }, @@ -203,7 +243,6 @@ "name": "password", "description": "The password for login in clear text", "required": true, - "allowMultiple": false, "type": "string", "paramType": "query" } @@ -216,22 +255,6 @@ ] } ] - }, - { - "path": "/user/logout", - "operations": [ - { - "method": "GET", - "summary": "Logs out current logged in user session", - "notes": "", - "type": "void", - "nickname": "logoutUser", - "produces": [ - "text/plain" - ], - "parameters": [] - } - ] } ], "models": { @@ -242,19 +265,19 @@ "type": "integer", "format": "int64" }, + "firstName": { + "type": "string" + }, "username": { "type": "string" }, - "password": { + "lastName": { "type": "string" }, "email": { "type": "string" }, - "firstName": { - "type": "string" - }, - "lastName": { + "password": { "type": "string" }, "phone": { diff --git a/src/test/scala/BasicJavaGeneratorTest.scala b/src/test/scala/BasicJavaGeneratorTest.scala index a0a0c48e90d..6f000d5efa4 100644 --- a/src/test/scala/BasicJavaGeneratorTest.scala +++ b/src/test/scala/BasicJavaGeneratorTest.scala @@ -122,6 +122,7 @@ class BasicJavaGeneratorTest extends FlatSpec with ShouldMatchers { */ it should "honor the import mapping" in { config.importMapping("Date") should be ("java.util.Date") + config.importMapping("DateTime") should be ("org.joda.time.*") } /* diff --git a/src/test/scala/swaggerSpec1_2/ModelSerializersTest.scala b/src/test/scala/swaggerSpec1_2/ModelSerializersTest.scala index a97cc7000c3..6a6200a512f 100644 --- a/src/test/scala/swaggerSpec1_2/ModelSerializersTest.scala +++ b/src/test/scala/swaggerSpec1_2/ModelSerializersTest.scala @@ -31,16 +31,12 @@ class ResourceListingSerializersTest extends FlatSpec with ShouldMatchers { 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 "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 = """ { @@ -54,7 +50,8 @@ class ResourceListingSerializersTest extends FlatSpec with ShouldMatchers { "path":"/c", "description":"path c apis" } - ] + ], + "authorizations": {} } """ val json = parse(jsonString) @@ -63,15 +60,12 @@ class ResourceListingSerializersTest extends FlatSpec with ShouldMatchers { 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") } } - 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]) @@ -102,9 +96,52 @@ class ApiListingReferenceSerializersTest extends FlatSpec with ShouldMatchers { } @RunWith(classOf[JUnitRunner]) -class ApiDescriptionSerializersTest extends FlatSpec with ShouldMatchers { +class ApiListingSerializersTest extends FlatSpec with ShouldMatchers { 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 ShouldMatchers { + implicit val formats = SwaggerSerializers.formats("1.2") it should "deserialize an ApiDescription with no ops" in { val jsonString = """ { @@ -151,7 +188,8 @@ class ApiDescriptionSerializersTest extends FlatSpec with ShouldMatchers { "enum":["a","b","c"], "paramType":"query" } - ] + ], + "authorizations":{} } ] } @@ -179,6 +217,7 @@ class ApiDescriptionSerializersTest extends FlatSpec with ShouldMatchers { m.dataType should be ("string") m.paramType should be ("query") }) + op.authorizations.size should be (0) }) } case _ => fail("wrong type returned, should be ApiDescription") @@ -230,7 +269,8 @@ class OperationSerializersTest extends FlatSpec with ShouldMatchers { "enum":["a","b","c"], "paramType":"query" } - ] + ], + "authorizations":{} } """ val json = parse(jsonString) @@ -252,6 +292,7 @@ class OperationSerializersTest extends FlatSpec with ShouldMatchers { m.dataType should be ("string") m.paramType should be ("query") }) + op.authorizations.size should be (0) } case _ => fail("wrong type returned, should be Operation") } @@ -833,4 +874,4 @@ class AllowableValuesSerializersTest extends FlatSpec with ShouldMatchers { val l = AllowableRangeValues("-1", "3") write(l) should be ("""{"valueType":"RANGE","min":"-1","max":"3"}""") } -} \ No newline at end of file +}