moved to client subdirectory

This commit is contained in:
Tony Tam
2012-09-23 16:12:56 -07:00
parent ad5d44769b
commit 1077e48e7e
19 changed files with 151 additions and 205 deletions

View File

@@ -0,0 +1,41 @@
/**
* 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.BasicScalaGenerator
import com.wordnik.swagger.core._
object ScalaPetstoreCodegen extends BasicScalaGenerator {
def main(args: Array[String]) = generateClient(args)
// package for api invoker, error files
override def invokerPackage = Some("com.wordnik.client")
// where to write generated code
override def destinationDir = "samples/client/petstore/scala/src/main/scala"
// package for models
override def modelPackage = Some("com.wordnik.petstore.model")
// package for api classes
override def apiPackage = Some("com.wordnik.petstore.api")
// supporting classes
override def supportingFiles = List(
("apiInvoker.mustache", "samples/client/petstore/scala/src/main/scala/com/wordnik/client", "ApiInvoker.scala"),
("pom.mustache", "samples/client/petstore/scala", "pom.xml")
)
}

View File

@@ -0,0 +1,225 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wordnik</groupId>
<artifactId>swagger-client</artifactId>
<packaging>jar</packaging>
<name>swagger-client</name>
<version>1.0</version>
<scm>
<connection>scm:git:git@github.com:wordnik/swagger-mustache.git</connection>
<developerConnection>scm:git:git@github.com:wordnik/swagger-mustache.git</developerConnection>
<url>https://github.com/wordnik/swagger-mustache</url>
</scm>
<prerequisites>
<maven>2.2.0</maven>
</prerequisites>
<pluginRepositories>
<pluginRepository>
<id>scala-tools.org</id>
<name>Scala-Tools Maven2 Repository</name>
<url>http://scala-tools.org/repo-releases</url>
</pluginRepository>
<pluginRepository>
<id>maven-mongodb-plugin-repo</id>
<name>maven mongodb plugin repository</name>
<url>http://maven-mongodb-plugin.googlecode.com/svn/maven/repo</url>
<layout>default</layout>
</pluginRepository>
</pluginRepositories>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.2</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/java</source>
</sources>
</configuration>
</execution>
<execution>
<id>add_test_sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<version>2.15.2</version>
<executions>
<execution>
<id>scala-compile-first</id>
<phase>process-resources</phase>
<goals>
<goal>add-source</goal>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>scala-test-compile</id>
<phase>process-test-resources</phase>
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
<configuration>
<jvmArgs>
<jvmArg>-Xms128m</jvmArg>
<jvmArg>-Xmx1500m</jvmArg>
</jvmArgs>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.scala-tools</groupId>
<artifactId>maven-scala-plugin</artifactId>
<configuration>
<scalaVersion>${scala-version}</scalaVersion>
</configuration>
</plugin>
</plugins>
</reporting>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>${jersey-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-core_2.9.1</artifactId>
<version>${swagger-core-version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.9.1</artifactId>
<version>${scala-test-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>scala-tools.org</id>
<name>Scala-Tools Maven2 Repository</name>
<url>http://scala-tools.org/repo-releases</url>
</repository>
<repository>
<id>wordnik-ci-aws</id>
<url>https://ci.aws.wordnik.com/artifactory/libs-snapshots/</url>
</repository>
<repository>
<id>wordnik-ci-aws-maven</id>
<url>https://ci.aws.wordnik.com/artifactory/m2-snapshots/</url>
</repository>
<repository>
<id>wordnik-ci-aws-remote</id>
<url>https://ci.aws.wordnik.com/artifactory/remote-repos/</url>
</repository>
</repositories>
<properties>
<jersey-version>1.7</jersey-version>
<swagger-core-version>1.1.0</swagger-core-version>
<scala-version>2.9.1-1</scala-version>
<junit-version>4.8.1</junit-version>
<maven-plugin.version>1.0.0</maven-plugin.version>
<scala-test-version>1.6.1</scala-test-version>
<junit-version>4.8.1</junit-version>
<scala-test-version>1.6.1</scala-test-version>
</properties>
</project>

View File

@@ -0,0 +1,137 @@
package com.wordnik.client
import com.sun.jersey.api.client.Client
import com.sun.jersey.api.client.ClientResponse
import com.sun.jersey.api.client.config.ClientConfig
import com.sun.jersey.api.client.config.DefaultClientConfig
import com.sun.jersey.api.client.filter.LoggingFilter
import java.net.URLEncoder
import javax.ws.rs.core.MediaType
import scala.collection.JavaConverters._
import scala.collection.mutable.HashMap
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.core.JsonGenerator.Feature
import com.fasterxml.jackson.databind._
import com.fasterxml.jackson.annotation._
import com.fasterxml.jackson.databind.annotation.JsonSerialize
object ScalaJsonUtil {
def getJsonMapper = {
val mapper = new ObjectMapper()
mapper.registerModule(new DefaultScalaModule())
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT)
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
mapper
}
}
object ApiInvoker {
val mapper = ScalaJsonUtil.getJsonMapper
val defaultHeaders: HashMap[String, String] = HashMap()
val hostMap: HashMap[String, Client] = HashMap()
def escapeString(value: String): String = {
URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20")
}
def deserialize(json: String, containerType: String, cls: Class[_]) = {
if (cls == classOf[String]) {
json match {
case s: String => {
if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 2)
else s
}
case _ => null
}
} else {
containerType match {
case "List" => {
val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls)
val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]]
response.asScala.toList
}
case _ => {
json match {
case e: String if ("\"\"" == e) => null
case _ => mapper.readValue(json, cls)
}
}
}
}
}
def serialize(obj: AnyRef): String = {
if (obj != null) {
obj match {
case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava)
case _ => mapper.writeValueAsString(obj)
}
} else null
}
def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], body: AnyRef, headerParams: Map[String, String]) = {
val client = getClient(host)
val querystring = queryParams.filter(k => k._2 != null).map(k => (escapeString(k._1) + "=" + escapeString(k._2))).mkString("?", "&", "")
val builder = client.resource(host + path + querystring).`type`("application/json")
headerParams.map(p => builder.header(p._1, p._2))
defaultHeaders.map(p => {
headerParams.contains(p._1) match {
case true => // override default with supplied header
case false => if (p._2 != null) builder.header(p._1, p._2)
}
})
val response: ClientResponse = method match {
case "GET" => {
builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse]
}
case "POST" => {
builder.post(classOf[ClientResponse], serialize(body))
}
case "PUT" => {
builder.put(classOf[ClientResponse], serialize(body))
}
case "DELETE" => {
builder.delete(classOf[ClientResponse])
}
case _ => null
}
response.getClientResponseStatus() match {
case ClientResponse.Status.OK => response.getEntity(classOf[String])
case _ => {
throw new ApiException(
response.getClientResponseStatus().getStatusCode(),
response.getEntity(classOf[String]))
}
}
}
def getClient(host: String): Client = {
hostMap.contains(host) match {
case true => hostMap(host)
case false => {
val client = Client.create()
// client.addFilter(new LoggingFilter())
hostMap += host -> client
client
}
}
}
}
class ApiException extends Exception {
var code = 0
def this(code: Int, msg: String) = {
this()
}
}

View File

@@ -0,0 +1,127 @@
package com.wordnik.petstore.api
import com.wordnik.petstore.model.Pet
import com.wordnik.client.ApiInvoker
import com.wordnik.client.ApiException
import scala.collection.mutable.HashMap
class PetApi {
var basePath: String = "http://petstore.swagger.wordnik.com/api"
var apiInvoker = ApiInvoker
def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value
def getPetById (petId: String) : Option[Pet]= {
// create path and map variables
val path = "/pet.{format}/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}",apiInvoker.escapeString(petId))
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(petId) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[Pet]).asInstanceOf[Pet])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def addPet (body: Pet) = {
// create path and map variables
val path = "/pet.{format}".replaceAll("\\{format\\}","json")// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(body) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def updatePet (body: Pet) = {
// create path and map variables
val path = "/pet.{format}".replaceAll("\\{format\\}","json")// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(body) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, body, headerParams.toMap) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def findPetsByStatus (status: String= "available") : Option[List[Pet]]= {
// create path and map variables
val path = "/pet.{format}/findByStatus".replaceAll("\\{format\\}","json")// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(status) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
if(String.valueOf(status) != "null") queryParams += "status" -> status.toString
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "List", classOf[Pet]).asInstanceOf[List[Pet]])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def findPetsByTags (tags: String) : Option[List[Pet]]= {
// create path and map variables
val path = "/pet.{format}/findByTags".replaceAll("\\{format\\}","json")// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(tags) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
if(String.valueOf(tags) != "null") queryParams += "tags" -> tags.toString
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "List", classOf[Pet]).asInstanceOf[List[Pet]])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
}

View File

@@ -0,0 +1,83 @@
package com.wordnik.petstore.api
import com.wordnik.petstore.model.Order
import com.wordnik.client.ApiInvoker
import com.wordnik.client.ApiException
import scala.collection.mutable.HashMap
class StoreApi {
var basePath: String = "http://petstore.swagger.wordnik.com/api"
var apiInvoker = ApiInvoker
def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value
def getOrderById (orderId: String) : Option[Order]= {
// create path and map variables
val path = "/store.{format}/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escapeString(orderId))
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(orderId) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[Order]).asInstanceOf[Order])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def deleteOrder (orderId: String) = {
// create path and map variables
val path = "/store.{format}/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}",apiInvoker.escapeString(orderId))
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(orderId) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def placeOrder (body: Order) = {
// create path and map variables
val path = "/store.{format}/order".replaceAll("\\{format\\}","json")// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(body) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
}

View File

@@ -0,0 +1,188 @@
package com.wordnik.petstore.api
import com.wordnik.petstore.model.User
import com.wordnik.client.ApiInvoker
import com.wordnik.client.ApiException
import scala.collection.mutable.HashMap
class UserApi {
var basePath: String = "http://petstore.swagger.wordnik.com/api"
var apiInvoker = ApiInvoker
def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value
def createUsersWithArrayInput (body: Array[User]) = {
// create path and map variables
val path = "/user.{format}/createWithArray".replaceAll("\\{format\\}","json")// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(body) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def createUser (body: User) = {
// create path and map variables
val path = "/user.{format}".replaceAll("\\{format\\}","json")// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(body) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def createUsersWithListInput (body: List[User]) = {
// create path and map variables
val path = "/user.{format}/createWithList".replaceAll("\\{format\\}","json")// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(body) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def updateUser (username: String, body: User) = {
// create path and map variables
val path = "/user.{format}/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escapeString(username))
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(username, body) - null).size match {
case 2 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, body, headerParams.toMap) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def deleteUser (username: String) = {
// create path and map variables
val path = "/user.{format}/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escapeString(username))
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(username) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def getUserByName (username: String) : Option[User]= {
// create path and map variables
val path = "/user.{format}/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escapeString(username))
// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(username) - null).size match {
case 1 => // all required values set
case _ => throw new Exception("missing required params")
}
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def loginUser (username: String, password: String) : Option[String]= {
// create path and map variables
val path = "/user.{format}/login".replaceAll("\\{format\\}","json")// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
// verify required params are set
(Set(username, password) - null).size match {
case 2 => // all required values set
case _ => throw new Exception("missing required params")
}
if(String.valueOf(username) != "null") queryParams += "username" -> username.toString
if(String.valueOf(password) != "null") queryParams += "password" -> password.toString
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match {
case s: String =>
Some(ApiInvoker.deserialize(s, "", classOf[String]).asInstanceOf[String])
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
def logoutUser () = {
// create path and map variables
val path = "/user.{format}/logout".replaceAll("\\{format\\}","json")// query params
val queryParams = new HashMap[String, String]
val headerParams = new HashMap[String, String]
try {
apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match {
case s: String =>
case _ => None
}
} catch {
case ex: ApiException if ex.code == 404 => None
case ex: ApiException => throw ex
}
}
}

View File

@@ -0,0 +1,6 @@
package com.wordnik.petstore.model
case class Category (
id: Long,
name: String)

View File

@@ -0,0 +1,11 @@
package com.wordnik.petstore.model
import java.util.Date
case class Order (
id: Long,
petId: Long,
/* Order Status */
status: String,
quantity: Int,
shipDate: Date)

View File

@@ -0,0 +1,13 @@
package com.wordnik.petstore.model
import com.wordnik.petstore.model.Category
import com.wordnik.petstore.model.Tag
case class Pet (
id: Long,
tags: List[Tag],
category: Category,
/* pet status in the store */
status: String,
name: String,
photoUrls: List[String])

View File

@@ -0,0 +1,6 @@
package com.wordnik.petstore.model
case class Tag (
id: Long,
name: String)

View File

@@ -0,0 +1,13 @@
package com.wordnik.petstore.model
case class User (
id: Long,
lastName: String,
username: String,
phone: String,
email: String,
/* User Status */
userStatus: Int,
firstName: String,
password: String)

View File

@@ -0,0 +1,103 @@
import com.wordnik.petstore.api._
import com.wordnik.petstore.model._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
import scala.collection.mutable.{ ListBuffer, HashMap }
import scala.collection.JavaConverters._
import scala.reflect.BeanProperty
@RunWith(classOf[JUnitRunner])
class PetApiTest extends FlatSpec with ShouldMatchers {
behavior of "PetApi"
val api = new PetApi
it should "fetch a pet" in {
api.getPetById("1") match {
case Some(pet) => {
pet should not be (null)
pet.id should be(1)
}
case None => fail("didn't find pet 1")
}
}
it should "add a new pet" in {
val pet = Pet(
1000,
(for (i <- (1 to 5)) yield Tag(i, "tag-" + i)).toList,
Category(1, "sold"),
"lost",
"dragon",
(for (i <- (1 to 10)) yield "http://foo.com/photo/" + i).toList)
api.addPet(pet)
api.getPetById("1000") match {
case Some(pet) => {
pet.id should be(1000)
pet.tags.size should be(5)
pet.status should be("lost")
pet.category should not be (null)
pet.category.name should be("sold")
pet.name should be("dragon")
pet.photoUrls.size should be(10)
}
case None => fail("didn't find pet created")
}
}
it should "update a pet" in {
val pet = Pet(
1000,
(for (i <- (1 to 5)) yield Tag(i, "tag-" + i)).toList,
Category(1, "sold"),
"confused",
"programmer",
(for (i <- (1 to 10)) yield "http://foo.com/photo/" + i).toList)
api.addPet(pet)
api.getPetById("1000") match {
case Some(pet) => {
pet.name should be("programmer")
pet.status should be("confused")
}
case None => fail("didn't find pet created")
}
val updatedPet = pet.copy(status="fulfilled")
api.updatePet(updatedPet)
api.getPetById("1000") match {
case Some(pet) => {
pet.name should be("programmer")
pet.status should be("fulfilled")
}
case None => fail("didn't find pet updated")
}
}
it should "find pets by status" in {
api.findPetsByStatus("available") match {
case Some(pets) => {
pets.foreach(pet => pet.status should be("available"))
}
case None => fail("didn't find pets by status")
}
}
it should "find pets by tag" in {
println("finding by tags")
api.findPetsByTags("tag1,tag2") match {
case Some(pets) => {
pets.foreach(pet => {
val tags = (for (tag <- pet.tags) yield tag.name).toSet
if ((tags & Set("tag1", "tag2")).size == 0)
fail("unexpected tags in " + tags)
})
}
case None => fail("didn't find pets by tag")
}
}
}

View File

@@ -0,0 +1,81 @@
import com.wordnik.client._
import com.wordnik.petstore.api._
import com.wordnik.petstore.model._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
import scala.collection.mutable.{ ListBuffer, HashMap }
import scala.collection.JavaConversions._
import scala.reflect.BeanProperty
@RunWith(classOf[JUnitRunner])
class StoreApiTest extends FlatSpec with ShouldMatchers {
behavior of "StoreApi"
val api = new StoreApi
api.apiInvoker.defaultHeaders += "api_key" -> "special-key"
it should "fetch an order" in {
api.getOrderById("1") match {
case Some(order) => {
order.id should be(1)
order.petId should be(1)
order.quantity should be(2)
order.shipDate should not be (null)
}
case None => fail("didn't find order")
}
}
it should "place an order" in {
val now = new java.util.Date
val order = Order (
1000,
10,
"pending",
101,
now)
api.placeOrder(order)
api.getOrderById("1000") match {
case Some(order) => {
order.id should be(1000)
order.petId should be(10)
order.quantity should be(101)
order.shipDate should be (now)
}
case None =>
}
}
it should "delete an order" in {
val now = new java.util.Date
val order = Order(
1001,
10,
"pending",
101,
now)
api.placeOrder(order)
api.getOrderById("1001") match {
case Some(order) => {
order.id should be(1001)
order.petId should be(10)
order.quantity should be(101)
order.shipDate should be (now)
}
case None =>
}
api.deleteOrder("1001")
intercept[ApiException] {
api.getOrderById("1001") should be (None)
}
}
}

View File

@@ -0,0 +1,152 @@
import com.wordnik.petstore.api._
import com.wordnik.petstore.model._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
import scala.collection.mutable.{ ListBuffer, HashMap }
import scala.collection.JavaConversions._
import scala.reflect.BeanProperty
@RunWith(classOf[JUnitRunner])
class UserApiTest extends FlatSpec with ShouldMatchers {
behavior of "UserApi"
val api = new UserApi
api.apiInvoker.defaultHeaders += "api_key" -> "special-key"
it should "fetch a user" in {
api.getUserByName("user1") match {
case Some(user) => {
user.id should be(1)
user.username should be("user1")
user.password should be("XXXXXXXXXXX")
user.email should be("email1@test.com")
user.firstName should be("first name 1")
user.lastName should be("last name 1")
user.phone should be("123-456-7890")
user.userStatus should be(1)
}
case None =>
}
}
it should "authenticate a user" in {
api.loginUser("user1", "XXXXXXXXXXX") match {
case Some(status) => status.startsWith("logged in user session") match {
case true => // success!
case _ => fail("didn't get expected message " + status)
}
case None => fail("not able to login")
}
}
it should "log out a user" in {
api.logoutUser
}
it should "create a user" in {
val user = User(
1002,
"Rocket",
"johnny",
"408-867-5309",
"johnny@fail.com",
1,
"Johnny",
"XXXXXXXXXXX")
api.createUser(user)
api.getUserByName("johnny") match {
case Some(user) => {
user.id should be (1002)
user.username should be ("johnny")
}
case None =>
}
}
it should "create 2 users" in {
val userArray = (for (i <- (1 to 2)) yield {
User(
2000 + i,
"Rocket-" + i,
"johnny-" + i,
"408-867-5309",
"johnny-" + i + "@fail.com",
1,
"Johnny",
"XXXXXXXXXXX")
}).toArray
api.createUsersWithArrayInput(userArray)
for (i <- (1 to 2)) {
api.getUserByName("johnny-" + i) match {
case Some(user) => {
user.id should be (2000 + i)
user.email should be ("johnny-" + i + "@fail.com")
}
case None => fail("didn't find user " + i)
}
}
}
it should "create 3 users" in {
val userList = (for (i <- (1 to 3)) yield {
User(
3000 + i,
"Rocket-" + i,
"fred-" + i,
"408-867-5309",
"fred-" + i + "@fail.com",
1,
"Johnny",
"XXXXXXXXXXX")
}).toList
api.createUsersWithListInput(userList)
for (i <- (1 to 3)) {
api.getUserByName("fred-" + i) match {
case Some(user) => {
user.id should be (3000 + i)
user.email should be ("fred-" + i + "@fail.com")
}
case None => fail("didn't find user " + i)
}
}
}
it should "update a user" in {
val user = User(
4000,
"Tiger",
"tony",
"408-867-5309",
"tony@fail.com",
1,
"Tony",
"XXXXXXXXXXX")
api.createUser(user)
api.getUserByName("tony") match {
case Some(user) => {
user.id should be (4000)
user.username should be ("tony")
}
case None =>
}
val updatedUser = user.copy(email="tony@succeed.com")
api.updateUser("tony", updatedUser)
api.getUserByName("tony") match {
case Some(user) => {
user.email should be ("tony@succeed.com")
}
case None =>
}
}
}