Add wordnik and petstore examples

This commit is contained in:
Camille Chafer 2015-04-02 16:26:16 +02:00
parent 0811e0bce3
commit 2ce55115a6
63 changed files with 3435 additions and 0 deletions

View File

@ -0,0 +1,227 @@
<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.0</version>
<prerequisites>
<maven>2.2.0</maven>
</prerequisites>
<pluginRepositories>
<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>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>${scala-maven-plugin-version}</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>
<args>
<arg>-feature</arg>
</args>
<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>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala-version}</version>
</dependency>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.10</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>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time-version}</version>
</dependency>
<dependency>
<groupId>org.joda</groupId>
<artifactId>joda-convert</artifactId>
<version>${joda-version}</version>
</dependency>
<dependency>
<groupId>com.typesafe</groupId>
<artifactId>config</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_2.10</artifactId>
<version>${akka-version}</version>
</dependency>
<dependency>
<groupId>io.spray</groupId>
<artifactId>spray-client</artifactId>
<version>${spray-version}</version>
</dependency>
<dependency>
<groupId>org.json4s</groupId>
<artifactId>json4s-jackson_2.10</artifactId>
<version>${json4s-jackson-version}</version>
</dependency>
</dependencies>
<properties>
<scala-version>2.10.4</scala-version>
<json4s-jackson-version>3.2.11</json4s-jackson-version>
<json4s-ext-version>3.2.11</json4s-ext-version>
<spray-version>1.3.1</spray-version>
<akka-version>2.3.9</akka-version>
<joda-version>1.2</joda-version>
<joda-time-version>2.2</joda-time-version>
<swagger-core-version>1.5.0-M1</swagger-core-version>
<maven-plugin.version>1.0.0</maven-plugin.version>
<junit-version>4.8.1</junit-version>
<scala-maven-plugin-version>3.1.5</scala-maven-plugin-version>
<scala-test-version>2.1.3</scala-test-version>
</properties>
</project>

View File

@ -0,0 +1,24 @@
io.swagger.client {
apiRequest {
compression {
enabled: false
size-threshold: 0
}
trust-certificates: true
connection-timeout: 5000ms
default-headers {
"userAgent": "swagger-client_1.0.0"
}
// let you define custom http status code, as in :
// { code: 601, reason: "some custom http status code", success: false }
custom-codes : []
}
}
spray.can.host-connector.max-redirects = 10

View File

@ -0,0 +1,43 @@
package io.swagger.client.api
import io.swagger.client.model._
import org.json4s._
import scala.reflect.ClassTag
object EnumsSerializers {
def all = Seq[Serializer[_]]() :+
new EnumNameSerializer(PetEnums.Status) :+
new EnumNameSerializer(OrderEnums.Status)
private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E)
extends Serializer[E#Value] {
import JsonDSL._
val EnumerationClass = classOf[E#Value]
def deserialize(implicit format: Formats):
PartialFunction[(TypeInfo, JValue), E#Value] = {
case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => {
json match {
case JString(value) =>
enum.withName(value)
case value =>
throw new MappingException(s"Can't convert $value to $EnumerationClass")
}
}
}
private[this] def isValid(json: JValue) = json match {
case JString(value) if enum.values.exists(_.toString == value) => true
case _ => false
}
def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case i: E#Value => i.toString
}
}
}

View File

@ -0,0 +1,139 @@
package io.swagger.client.api
import io.swagger.client.model.Pet
import java.io.File
import io.swagger.client.core._
import io.swagger.client.core.CollectionFormats._
import io.swagger.client.core.ApiKeyLocations._
object PetApi {
/**
*
* Expected answers:
* code 405 : (Validation exception)
* code 404 : (Pet not found)
* code 400 : (Invalid ID supplied)
*
* @param Body Pet object that needs to be added to the store
*/
def updatePet(Body: Option[Pet] = None): ApiRequest[Unit] =
ApiRequest[Unit](ApiMethods.PUT, "http://petstore.swagger.io/v2", "/pet", "application/json")
.withBody(Body)
.withErrorResponse[Unit](405)
.withErrorResponse[Unit](404)
.withErrorResponse[Unit](400)
/**
*
* Expected answers:
* code 405 : (Invalid input)
*
* @param Body Pet object that needs to be added to the store
*/
def addPet(Body: Option[Pet] = None): ApiRequest[Unit] =
ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet", "application/json")
.withBody(Body)
.withErrorResponse[Unit](405)
/**
* Multiple status values can be provided with comma seperated strings
*
* Expected answers:
* code 200 : Seq[Pet] (successful operation)
* code 400 : (Invalid status value)
*
* @param Status Status values that need to be considered for filter
*/
def findPetsByStatus(Status: Seq[String]): ApiRequest[Seq[Pet]] =
ApiRequest[Seq[Pet]](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/findByStatus", "application/json")
.withQueryParam("status", ArrayValues(Status, MULTI))
.withSuccessResponse[Seq[Pet]](200)
.withErrorResponse[Unit](400)
/**
* Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.
*
* Expected answers:
* code 200 : Seq[Pet] (successful operation)
* code 400 : (Invalid tag value)
*
* @param Tags Tags to filter by
*/
def findPetsByTags(Tags: Seq[String]): ApiRequest[Seq[Pet]] =
ApiRequest[Seq[Pet]](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/findByTags", "application/json")
.withQueryParam("tags", ArrayValues(Tags, MULTI))
.withSuccessResponse[Seq[Pet]](200)
.withErrorResponse[Unit](400)
/**
* Returns a pet when ID &lt; 10. ID &gt; 10 or nonintegers will simulate API error conditions
*
* Expected answers:
* code 404 : (Pet not found)
* code 200 : Pet (successful operation)
* code 400 : (Invalid ID supplied)
*
* Available security schemes:
* api_key (apiKey)
*
* @param PetId ID of pet that needs to be fetched
*/
def getPetById(PetId: Long)(implicit apiKey: ApiKeyValue): ApiRequest[Pet] =
ApiRequest[Pet](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/json")
.withApiKey(apiKey, "api_key", HEADER)
.withPathParam("petId", PetId)
.withErrorResponse[Unit](404)
.withSuccessResponse[Pet](200)
.withErrorResponse[Unit](400)
/**
*
* Expected answers:
* code 405 : (Invalid input)
*
* @param PetId ID of pet that needs to be updated
* @param Name Updated name of the pet
* @param Status Updated status of the pet
*/
def updatePetWithForm(PetId: String, Name: Option[String] = None, Status: Option[String] = None): ApiRequest[Unit] =
ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/x-www-form-urlencoded")
.withFormParam("name", Name)
.withFormParam("status", Status)
.withPathParam("petId", PetId)
.withErrorResponse[Unit](405)
/**
*
* Expected answers:
* code 400 : (Invalid pet value)
*
* @param ApiKey
* @param PetId Pet id to delete
*/
def deletePet(ApiKey: Option[String] = None, PetId: Long): ApiRequest[Unit] =
ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/json")
.withPathParam("petId", PetId)
.withHeaderParam("api_key", ApiKey)
.withErrorResponse[Unit](400)
/**
*
* Expected answers:
* code 0 : (successful operation)
*
* @param PetId ID of pet to update
* @param AdditionalMetadata Additional data to pass to server
* @param File file to upload
*/
def uploadFile(PetId: Long, AdditionalMetadata: Option[String] = None, File: Option[File] = None): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet/{petId}/uploadImage", "multipart/form-data")
.withFormParam("additionalMetadata", AdditionalMetadata)
.withFormParam("file", File)
.withPathParam("petId", PetId)
.withSuccessResponse[Unit](0)
}

View File

@ -0,0 +1,73 @@
package io.swagger.client.api
import io.swagger.client.model.Order
import io.swagger.client.core._
import io.swagger.client.core.CollectionFormats._
import io.swagger.client.core.ApiKeyLocations._
object StoreApi {
/**
* Returns a map of status codes to quantities
*
* Expected answers:
* code 200 : Map[String, Int] (successful operation)
*
* Available security schemes:
* api_key (apiKey)
*/
def getInventory()(implicit apiKey: ApiKeyValue): ApiRequest[Map[String, Int]] =
ApiRequest[Map[String, Int]](ApiMethods.GET, "http://petstore.swagger.io/v2", "/store/inventory", "application/json")
.withApiKey(apiKey, "api_key", HEADER)
.withSuccessResponse[Map[String, Int]](200)
/**
*
* Expected answers:
* code 200 : Order (successful operation)
* code 400 : (Invalid Order)
*
* @param Body order placed for purchasing the pet
*/
def placeOrder(Body: Option[Order] = None): ApiRequest[Order] =
ApiRequest[Order](ApiMethods.POST, "http://petstore.swagger.io/v2", "/store/order", "application/json")
.withBody(Body)
.withSuccessResponse[Order](200)
.withErrorResponse[Unit](400)
/**
* For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other values will generated exceptions
*
* Expected answers:
* code 404 : (Order not found)
* code 200 : Order (successful operation)
* code 400 : (Invalid ID supplied)
*
* @param OrderId ID of pet that needs to be fetched
*/
def getOrderById(OrderId: String): ApiRequest[Order] =
ApiRequest[Order](ApiMethods.GET, "http://petstore.swagger.io/v2", "/store/order/{orderId}", "application/json")
.withPathParam("orderId", OrderId)
.withErrorResponse[Unit](404)
.withSuccessResponse[Order](200)
.withErrorResponse[Unit](400)
/**
* For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors
*
* Expected answers:
* code 404 : (Order not found)
* code 400 : (Invalid ID supplied)
*
* @param OrderId ID of the order that needs to be deleted
*/
def deleteOrder(OrderId: String): ApiRequest[Unit] =
ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/store/order/{orderId}", "application/json")
.withPathParam("orderId", OrderId)
.withErrorResponse[Unit](404)
.withErrorResponse[Unit](400)
}

View File

@ -0,0 +1,123 @@
package io.swagger.client.api
import io.swagger.client.model.User
import io.swagger.client.core._
import io.swagger.client.core.CollectionFormats._
import io.swagger.client.core.ApiKeyLocations._
object UserApi {
/**
* This can only be done by the logged in user.
*
* Expected answers:
* code 0 : (successful operation)
*
* @param Body Created user object
*/
def createUser(Body: Option[User] = None): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user", "application/json")
.withBody(Body)
.withSuccessResponse[Unit](0)
/**
*
* Expected answers:
* code 0 : (successful operation)
*
* @param Body List of user object
*/
def createUsersWithArrayInput(Body: Seq[User]): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithArray", "application/json")
.withBody(Body)
.withSuccessResponse[Unit](0)
/**
*
* Expected answers:
* code 0 : (successful operation)
*
* @param Body List of user object
*/
def createUsersWithListInput(Body: Seq[User]): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithList", "application/json")
.withBody(Body)
.withSuccessResponse[Unit](0)
/**
*
* Expected answers:
* code 200 : String (successful operation)
* code 400 : (Invalid username/password supplied)
*
* @param Username The user name for login
* @param Password The password for login in clear text
*/
def loginUser(Username: Option[String] = None, Password: Option[String] = None): ApiRequest[String] =
ApiRequest[String](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/login", "application/json")
.withQueryParam("username", Username)
.withQueryParam("password", Password)
.withSuccessResponse[String](200)
.withErrorResponse[Unit](400)
/**
*
* Expected answers:
* code 0 : (successful operation)
*/
def logoutUser(): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/logout", "application/json")
.withSuccessResponse[Unit](0)
/**
*
* Expected answers:
* code 404 : (User not found)
* code 200 : User (successful operation)
* code 400 : (Invalid username supplied)
*
* @param Username The name that needs to be fetched. Use user1 for testing.
*/
def getUserByName(Username: String): ApiRequest[User] =
ApiRequest[User](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/{username}", "application/json")
.withPathParam("username", Username)
.withErrorResponse[Unit](404)
.withSuccessResponse[User](200)
.withErrorResponse[Unit](400)
/**
* This can only be done by the logged in user.
*
* Expected answers:
* code 404 : (User not found)
* code 400 : (Invalid user supplied)
*
* @param Username name that need to be deleted
* @param Body Updated user object
*/
def updateUser(Username: String, Body: Option[User] = None): ApiRequest[Unit] =
ApiRequest[Unit](ApiMethods.PUT, "http://petstore.swagger.io/v2", "/user/{username}", "application/json")
.withBody(Body)
.withPathParam("username", Username)
.withErrorResponse[Unit](404)
.withErrorResponse[Unit](400)
/**
* This can only be done by the logged in user.
*
* Expected answers:
* code 404 : (User not found)
* code 400 : (Invalid username supplied)
*
* @param Username The name that needs to be deleted
*/
def deleteUser(Username: String): ApiRequest[Unit] =
ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/user/{username}", "application/json")
.withPathParam("username", Username)
.withErrorResponse[Unit](404)
.withErrorResponse[Unit](400)
}

View File

@ -0,0 +1,323 @@
package io.swagger.client.core
import java.io.File
import java.security.cert.X509Certificate
import javax.net.ssl._
import akka.actor.ActorSystem
import akka.io.IO
import akka.pattern.ask
import akka.util.Timeout
import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import org.json4s.JsonAST.JString
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization
import spray.can.Http
import spray.can.Http.HostConnectorSetup
import spray.client.pipelining
import spray.client.pipelining._
import spray.http.HttpEncodings._
import spray.http.HttpHeaders.{RawHeader, `Accept-Encoding`}
import spray.http.Uri.Query
import spray.http._
import spray.http.parser.HttpParser
import spray.httpx.encoding.{Deflate, Encoder, Gzip}
import spray.httpx.unmarshalling._
import spray.io.ClientSSLEngineProvider
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.ClassTag
import scala.util.control.NonFatal
object ApiInvoker {
def apply()(implicit system: ActorSystem): ApiInvoker =
apply(DefaultFormats + DateTimeSerializer)
def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker =
apply(DefaultFormats + DateTimeSerializer ++ serializers)
def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats)
case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true)
def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess)
def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = {
StatusCodes.getForKey(code) foreach { c =>
StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true)
}
}
/**
* Allows request execution without calling apiInvoker.execute(request)
* request.response can be used to get a future of the ApiResponse generated.
* request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a
* Future will failed with a ClassCastException
* @param request the apiRequest to be executed
*/
implicit class ApiRequestImprovements[T](request: ApiRequest[T]) {
def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] =
response(ec, system, invoker)
def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] =
invoker.execute(request)
def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] =
invoker.execute(request).map(_.content).mapTo[U]
}
/**
* Allows transformation from ApiMethod to spray HttpMethods
* @param method the ApiMethod to be converted
*/
implicit class ApiMethodExtensions(val method: ApiMethod) {
def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET)
}
case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( {
case JString(s) =>
ISODateTimeFormat.dateTimeParser().parseDateTime(s)
}, {
case d: DateTime =>
JString(ISODateTimeFormat.dateTimeParser().print(d))
}))
}
class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes {
import io.swagger.client.core.ApiInvoker._
import io.swagger.client.core.ParametersMap._
implicit val ec = system.dispatcher
implicit val jsonFormats = formats
def settings = ApiSettings(system)
import spray.http.MessagePredicate._
val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) &&
Encoder.DefaultFilter &&
minEntitySize(settings.compressionSizeThreshold)
settings.customCodes.foreach(addCustomStatusCode)
private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer =
request =>
credentialsSeq.foldLeft(request) {
case (req, BasicCredentials(login, password)) =>
req ~> addCredentials(BasicHttpCredentials(login, password))
case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) =>
req ~> addHeader(RawHeader(keyName, keyValue.value))
case (req, _) => req
}
private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request =>
val rawHeaders = for {
(name, value) <- headers.asFormattedParams
header = RawHeader(name, String.valueOf(value))
} yield header
request.withHeaders(rawHeaders.toList)
}
private def bodyPart(name: String, value: Any): BodyPart = {
value match {
case f: File =>
BodyPart(f, name)
case v: String =>
BodyPart(HttpEntity(String.valueOf(v)))
case NumericValue(v) =>
BodyPart(HttpEntity(String.valueOf(v)))
case m: ApiModel =>
BodyPart(HttpEntity(Serialization.write(m)))
}
}
private def formDataContent(request: ApiRequest[_]) = {
val params = request.formParams.asFormattedParams
if (params.isEmpty)
None
else
Some(
normalizedContentType(request.contentType).mediaType match {
case MediaTypes.`multipart/form-data` =>
MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))})
case MediaTypes.`application/x-www-form-urlencoded` =>
FormData(params.mapValues(String.valueOf))
case m: MediaType => // Default : application/x-www-form-urlencoded.
FormData(params.mapValues(String.valueOf))
}
)
}
private def bodyContent(request: ApiRequest[_]): Option[Any] = {
request.bodyParam.map(Extraction.decompose).map(compact)
}
private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = {
val builder = new RequestBuilder(request.method.toSprayMethod)
val httpRequest = request.method.toSprayMethod match {
case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri)
case HttpMethods.POST | HttpMethods.PUT =>
formDataContent(request) orElse bodyContent(request) match {
case Some(c: FormData) =>
builder.apply(uri, c)
case Some(c: MultipartFormData) =>
builder.apply(uri, c)
case Some(c: String) =>
builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c))
case _ =>
builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " "))
}
case _ => builder.apply(uri)
}
httpRequest ~>
addHeaders(request.headerParams) ~>
addAuthentication(request.credentials) ~>
encode(Gzip(CompressionFilter))
}
def makeQuery(r: ApiRequest[_]): Query = {
r.credentials.foldLeft(r.queryParams) {
case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) =>
params + (keyName -> key.value)
case (params, _) => params
}.asFormattedParams
.mapValues(String.valueOf)
.foldRight[Query](Uri.Query.Empty) {
case ((name, value), acc) => acc.+:(name, value)
}
}
def makeUri(r: ApiRequest[_]): Uri = {
val opPath = r.operationPath.replaceAll("\\{format\\}", "json")
val opPathWithParams = r.pathParams.asFormattedParams
.mapValues(String.valueOf)
.foldLeft(opPath) {
case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value)
}
val query = makeQuery(r)
Uri(r.basePath + opPathWithParams).withQuery(query)
}
def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = {
try {
implicit val timeout: Timeout = settings.connectionTimeout
val uri = makeUri(r)
val connector = HostConnectorSetup(
uri.authority.host.toString,
uri.effectivePort,
sslEncryption = "https".equals(uri.scheme),
defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate)))
val request = createRequest(uri, r)
for {
Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector
response <- hostConnector.ask(request).mapTo[HttpResponse]
} yield {
response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r)
}
}
catch {
case NonFatal(x) => Future.failed(x)
}
}
def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = {
request.responseForCode(response.status.intValue) match {
case Some( (manifest: Manifest[T], state: ResponseState) ) =>
entityUnmarshaller(manifest)(response.entity) match {
case Right(value)
state match {
case ResponseState.Success =>
ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap)
case ResponseState.Error =>
throw new ApiError(response.status.intValue, "Error response received",
Some(value),
headers = response.headers.map(header => (header.name, header.value)).toMap)
}
case Left(MalformedContent(error, Some(cause)))
throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause)
case Left(MalformedContent(error, None))
throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString))
case Left(ContentExpected)
throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString))
}
case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString))
}
}
def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] =
Unmarshaller[T](MediaTypes.`application/json`) {
case x: HttpEntity.NonEmpty
parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`))
.noNulls
.camelizeKeys
.extract[T]
}
}
sealed trait CustomContentTypes {
def normalizedContentType(original: String): ContentType =
MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original)
def parseContentType(contentType: String): ContentType = {
val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType)
val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader)
(parsedContentTypeHeader: @unchecked) match {
case Right(ct: HttpHeaders.`Content-Type`) =>
ct.contentType
case Left(error: ErrorInfo) =>
throw new IllegalArgumentException(
s"Error converting '$contentType' to a ContentType header: '${error.summary}'")
}
}
}
sealed trait UntrustedSslContext {
this: ApiInvoker =>
implicit lazy val trustfulSslContext: SSLContext = {
settings.alwaysTrustCertificates match {
case false =>
SSLContext.getDefault
case true =>
class IgnoreX509TrustManager extends X509TrustManager {
def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
def getAcceptedIssuers = null
}
val context = SSLContext.getInstance("TLS")
context.init(null, Array(new IgnoreX509TrustManager), null)
context
}
}
implicit val clientSSLEngineProvider =
ClientSSLEngineProvider {
_ =>
val engine = trustfulSslContext.createSSLEngine()
engine.setUseClientMode(true)
engine
}
}

View File

@ -0,0 +1,50 @@
package io.swagger.client.core
sealed trait ResponseState
object ResponseState {
case object Success extends ResponseState
case object Error extends ResponseState
}
case class ApiRequest[U](
// required fields
method: ApiMethod,
basePath: String,
operationPath: String,
contentType: String,
// optional fields
responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty,
bodyParam: Option[Any] = None,
formParams: Map[String, Any] = Map.empty,
pathParams: Map[String, Any] = Map.empty,
queryParams: Map[String, Any] = Map.empty,
headerParams: Map[String, Any] = Map.empty,
credentials: Seq[Credentials] = List.empty) {
def withCredentials(cred: Credentials) = copy[U](credentials = credentials :+ cred)
def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) = withCredentials(ApiKeyCredentials(key, keyName, location))
def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Success)))
def withErrorResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Error)))
def withDefaultSuccessResponse[T](implicit m: Manifest[T]) = withSuccessResponse[T](0)
def withDefaultErrorResponse[T](implicit m: Manifest[T]) = withErrorResponse[T](0)
def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0)
def withoutBody() = copy[U](bodyParam = None)
def withBody(body: Any) = copy[U](bodyParam = Some(body))
def withFormParam(name: String, value: Any) = copy[U](formParams = formParams + (name -> value))
def withPathParam(name: String, value: Any) = copy[U](pathParams = pathParams + (name -> value))
def withQueryParam(name: String, value: Any) = copy[U](queryParams = queryParams + (name -> value))
def withHeaderParam(name: String, value: Any) = copy[U](headerParams = headerParams + (name -> value))
}

View File

@ -0,0 +1,32 @@
package io.swagger.client.core
import java.util.concurrent.TimeUnit
import akka.actor.{ExtendedActorSystem, Extension, ExtensionKey}
import com.typesafe.config.Config
import io.swagger.client.core.ApiInvoker.CustomStatusCode
import spray.http.HttpHeaders.RawHeader
import scala.collection.JavaConversions._
import scala.concurrent.duration.FiniteDuration
class ApiSettings(config: Config) extends Extension {
def this(system: ExtendedActorSystem) = this(system.settings.config)
private def cfg = config.getConfig("io.swagger.client.apiRequest")
val alwaysTrustCertificates = cfg.getBoolean("trust-certificates")
val defaultHeaders = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render))
val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS)
val compressionEnabled = cfg.getBoolean("compression.enabled")
val compressionSizeThreshold = cfg.getBytes("compression.size-threshold").toInt
val customCodes = cfg.getConfigList("custom-codes").toList.map { c => CustomStatusCode(
c.getInt("code"),
c.getString("reason"),
c.getBoolean("success"))
}
}
object ApiSettings extends ExtensionKey[ApiSettings]

View File

@ -0,0 +1,166 @@
package io.swagger.client.core
import java.io.File
import java.net.URLEncoder
import scala.util.Try
sealed trait ApiReturnWithHeaders {
def headers: Map[String, String]
def header(name: String): Option[String] = headers.get(name)
def getStringHeader(name: String) = header(name)
def getIntHeader(name: String) = castedHeader(name, java.lang.Integer.parseInt)
def getLongHeader(name: String) = castedHeader(name, java.lang.Long.parseLong)
def getFloatHeader(name: String) = castedHeader(name, java.lang.Float.parseFloat)
def getDoubleHeader(name: String) = castedHeader(name, java.lang.Double.parseDouble)
def getBooleanHeader(name: String) = castedHeader(name, java.lang.Boolean.parseBoolean)
private def castedHeader[U](name: String, conversion: String => U): Option[U] = { Try { header(name).map( conversion ) }.get }
}
sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty)
extends ApiReturnWithHeaders
sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty)
extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause)
with ApiReturnWithHeaders
sealed case class ApiMethod(value: String)
object ApiMethods {
val CONNECT = ApiMethod("CONNECT")
val DELETE = ApiMethod("DELETE")
val GET = ApiMethod("GET")
val HEAD = ApiMethod("HEAD")
val OPTIONS = ApiMethod("OPTIONS")
val PATCH = ApiMethod("PATCH")
val POST = ApiMethod("POST")
val PUT = ApiMethod("PUT")
val TRACE = ApiMethod("TRACE")
}
/**
* This trait needs to be added to any model defined by the api.
*/
trait ApiModel
/**
* Single trait defining a credential that can be transformed to a paramName / paramValue tupple
*/
sealed trait Credentials {
def asQueryParam: Option[(String, String)] = None
}
sealed case class BasicCredentials(user: String, password: String) extends Credentials
sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials {
override def asQueryParam: Option[(String, String)] = location match {
case ApiKeyLocations.QUERY => Some((keyName, key.value))
case _ => None
}
}
sealed case class ApiKeyValue(value: String)
sealed trait ApiKeyLocation
object ApiKeyLocations {
case object QUERY extends ApiKeyLocation
case object HEADER extends ApiKeyLocation
}
/**
* Case class used to unapply numeric values only in pattern matching
* @param value the string representation of the numeric value
*/
sealed case class NumericValue(value: String) {
override def toString = value
}
object NumericValue {
def unapply(n: Any): Option[NumericValue] = n match {
case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n)))
case _ => None
}
}
/**
* Used for params being arrays
*/
sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV)
object ArrayValues {
def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues =
ArrayValues(values.getOrElse(Seq.empty), format)
def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV)
}
/**
* Defines how arrays should be rendered in query strings.
*/
sealed trait CollectionFormat
trait MergedArrayFormat extends CollectionFormat {
def separator: String
}
object CollectionFormats {
case object CSV extends MergedArrayFormat {
override val separator = ","
}
case object TSV extends MergedArrayFormat {
override val separator = "\t"
}
case object SSV extends MergedArrayFormat {
override val separator = " "
}
case object PIPES extends MergedArrayFormat {
override val separator = "|"
}
case object MULTI extends CollectionFormat
}
object ParametersMap {
/**
* Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tupples,
* with valid url-encoding, arrays handling, files preservation, ...
*/
implicit class ParametersMapImprovements(val m: Map[String, Any]) {
def asFormattedParamsList = m.toList.flatMap(formattedParams)
def asFormattedParams = m.flatMap(formattedParams)
private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20")
private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2)
private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match {
case arr: ArrayValues =>
arr.format match {
case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _))
case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator)))
}
case None => Seq.empty
case Some(opt) =>
formattedParams(name, opt)
case s: Seq[Any] =>
formattedParams(name, ArrayValues(s))
case v: String => Seq((name, urlEncode(v)))
case NumericValue(v) => Seq((name, urlEncode(v)))
case f: File => Seq((name, f))
case m: ApiModel => Seq((name, m))
}
}
}

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Category (
Id: Option[Long],
Name: Option[String])
extends ApiModel

View File

@ -0,0 +1,29 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Order (
Id: Option[Long],
PetId: Option[Long],
Quantity: Option[Int],
ShipDate: Option[DateTime],
/* Order Status */
Status: Option[OrderEnums.Status],
Complete: Option[Boolean])
extends ApiModel
object OrderEnums {
type Status = Status.Value
object Status extends Enumeration {
val Placed = Value("placed")
val Approved = Value("approved")
val Delivered = Value("delivered")
}
}

View File

@ -0,0 +1,29 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Pet (
Id: Option[Long],
Category: Option[Category],
Name: String,
PhotoUrls: Seq[String],
Tags: Option[Seq[Tag]],
/* pet status in the store */
Status: Option[PetEnums.Status])
extends ApiModel
object PetEnums {
type Status = Status.Value
object Status extends Enumeration {
val Available = Value("available")
val Pending = Value("pending")
val Sold = Value("sold")
}
}

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Tag (
Id: Option[Long],
Name: Option[String])
extends ApiModel

View File

@ -0,0 +1,19 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class User (
Id: Option[Long],
Username: Option[String],
FirstName: Option[String],
LastName: Option[String],
Email: Option[String],
Password: Option[String],
Phone: Option[String],
/* User Status */
UserStatus: Option[Int])
extends ApiModel

View File

@ -0,0 +1,227 @@
<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.0</version>
<prerequisites>
<maven>2.2.0</maven>
</prerequisites>
<pluginRepositories>
<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>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>${scala-maven-plugin-version}</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>
<args>
<arg>-feature</arg>
</args>
<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>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala-version}</version>
</dependency>
<dependency>
<groupId>com.wordnik</groupId>
<artifactId>swagger-core</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<dependency>
<groupId>org.scalatest</groupId>
<artifactId>scalatest_2.10</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>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time-version}</version>
</dependency>
<dependency>
<groupId>org.joda</groupId>
<artifactId>joda-convert</artifactId>
<version>${joda-version}</version>
</dependency>
<dependency>
<groupId>com.typesafe</groupId>
<artifactId>config</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_2.10</artifactId>
<version>${akka-version}</version>
</dependency>
<dependency>
<groupId>io.spray</groupId>
<artifactId>spray-client</artifactId>
<version>${spray-version}</version>
</dependency>
<dependency>
<groupId>org.json4s</groupId>
<artifactId>json4s-jackson_2.10</artifactId>
<version>${json4s-jackson-version}</version>
</dependency>
</dependencies>
<properties>
<scala-version>2.10.4</scala-version>
<json4s-jackson-version>3.2.11</json4s-jackson-version>
<json4s-ext-version>3.2.11</json4s-ext-version>
<spray-version>1.3.1</spray-version>
<akka-version>2.3.9</akka-version>
<joda-version>1.2</joda-version>
<joda-time-version>2.2</joda-time-version>
<swagger-core-version>1.5.0-M1</swagger-core-version>
<maven-plugin.version>1.0.0</maven-plugin.version>
<junit-version>4.8.1</junit-version>
<scala-maven-plugin-version>3.1.5</scala-maven-plugin-version>
<scala-test-version>2.1.3</scala-test-version>
</properties>
</project>

View File

@ -0,0 +1,24 @@
io.swagger.client {
apiRequest {
compression {
enabled: false
size-threshold: 0
}
trust-certificates: true
connection-timeout: 5000ms
default-headers {
"userAgent": "swagger-client_1.0.0"
}
// let you define custom http status code, as in :
// { code: 601, reason: "some custom http status code", success: false }
custom-codes : []
}
}
spray.can.host-connector.max-redirects = 10

View File

@ -0,0 +1,109 @@
package io.swagger.client.api
import io.swagger.client.model.ApiTokenStatus
import io.swagger.client.model.AuthenticationToken
import io.swagger.client.model.User
import io.swagger.client.model.WordList
import io.swagger.client.core._
import io.swagger.client.core.CollectionFormats._
import io.swagger.client.core.ApiKeyLocations._
object AccountApi {
/**
*
*
* Expected answers:
* code 200 : ApiTokenStatus (Usage statistics for the supplied API key)
* code 400 : (No token supplied.)
* code 404 : (No API account with supplied token.)
*
* @param ApiKey Wordnik authentication token
*/
def getApiTokenStatus(ApiKey: Option[String] = None): ApiRequest[ApiTokenStatus] =
ApiRequest[ApiTokenStatus](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/apiTokenStatus", "application/json")
.withHeaderParam("api_key", ApiKey)
.withSuccessResponse[ApiTokenStatus](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : AuthenticationToken (A valid authentication token)
* code 403 : (Account not available.)
* code 404 : (User not found.)
*
* @param Username A confirmed Wordnik username
* @param Password The user&#39;s password
*/
def authenticate(Username: String, Password: String): ApiRequest[AuthenticationToken] =
ApiRequest[AuthenticationToken](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/authenticate/{username}", "application/json")
.withQueryParam("password", Password)
.withPathParam("username", Username)
.withSuccessResponse[AuthenticationToken](200)
.withErrorResponse[Unit](403)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : AuthenticationToken (A valid authentication token)
* code 403 : (Account not available.)
* code 404 : (User not found.)
*
* @param Username A confirmed Wordnik username
* @param Body The user&#39;s password
*/
def authenticatePost(Username: String, Body: String): ApiRequest[AuthenticationToken] =
ApiRequest[AuthenticationToken](ApiMethods.POST, "https://api.wordnik.com/v4", "/account.json/authenticate/{username}", "application/json")
.withBody(Body)
.withPathParam("username", Username)
.withSuccessResponse[AuthenticationToken](200)
.withErrorResponse[Unit](403)
.withErrorResponse[Unit](404)
/**
* Requires a valid auth_token to be set.
*
* Expected answers:
* code 200 : User (The logged-in user)
* code 403 : (Not logged in.)
* code 404 : (User not found.)
*
* @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)
*/
def getLoggedInUser(AuthToken: String): ApiRequest[User] =
ApiRequest[User](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/user", "application/json")
.withHeaderParam("auth_token", AuthToken)
.withSuccessResponse[User](200)
.withErrorResponse[Unit](403)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : Seq[WordList] (success)
* code 403 : (Not authenticated.)
* code 404 : (User account not found.)
*
* @param AuthToken auth_token of logged-in user
* @param Skip Results to skip
* @param Limit Maximum number of results to return
*/
def getWordListsForLoggedInUser(AuthToken: String, Skip: Option[Int] = None, Limit: Option[Int] = None): ApiRequest[Seq[WordList]] =
ApiRequest[Seq[WordList]](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/wordLists", "application/json")
.withQueryParam("skip", Skip)
.withQueryParam("limit", Limit)
.withHeaderParam("auth_token", AuthToken)
.withSuccessResponse[Seq[WordList]](200)
.withErrorResponse[Unit](403)
.withErrorResponse[Unit](404)
}

View File

@ -0,0 +1,41 @@
package io.swagger.client.api
import io.swagger.client.model._
import org.json4s._
import scala.reflect.ClassTag
object EnumsSerializers {
def all = Seq[Serializer[_]]()
private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E)
extends Serializer[E#Value] {
import JsonDSL._
val EnumerationClass = classOf[E#Value]
def deserialize(implicit format: Formats):
PartialFunction[(TypeInfo, JValue), E#Value] = {
case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => {
json match {
case JString(value) =>
enum.withName(value)
case value =>
throw new MappingException(s"Can't convert $value to $EnumerationClass")
}
}
}
private[this] def isValid(json: JValue) = json match {
case JString(value) if enum.values.exists(_.toString == value) => true
case _ => false
}
def serialize(implicit format: Formats): PartialFunction[Any, JValue] = {
case i: E#Value => i.toString
}
}
}

View File

@ -0,0 +1,253 @@
package io.swagger.client.api
import io.swagger.client.model.WordObject
import io.swagger.client.model.AudioFile
import io.swagger.client.model.Definition
import io.swagger.client.model.FrequencySummary
import io.swagger.client.model.Bigram
import io.swagger.client.model.Example
import io.swagger.client.core._
import io.swagger.client.core.CollectionFormats._
import io.swagger.client.core.ApiKeyLocations._
object WordApi {
/**
*
*
* Expected answers:
* code 200 : WordObject (success)
* code 400 : (Invalid word supplied.)
*
* @param Word String value of WordObject to return
* @param UseCanonical If true will try to return the correct word root (&#39;cats&#39; -&gt; &#39;cat&#39;). If false returns exactly what was requested.
* @param IncludeSuggestions Return suggestions (for correct spelling, case variants, etc.)
*/
def getWord(Word: String, UseCanonical: Option[String] = None, IncludeSuggestions: Option[String] = None): ApiRequest[WordObject] =
ApiRequest[WordObject](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}", "application/json")
.withQueryParam("useCanonical", UseCanonical)
.withQueryParam("includeSuggestions", IncludeSuggestions)
.withPathParam("word", Word)
.withSuccessResponse[WordObject](200)
.withErrorResponse[Unit](400)
/**
* The metadata includes a time-expiring fileUrl which allows reading the audio file directly from the API. Currently only audio pronunciations from the American Heritage Dictionary in mp3 format are supported.
*
* Expected answers:
* code 200 : Seq[AudioFile] (success)
* code 400 : (Invalid word supplied.)
*
* @param Word Word to get audio for.
* @param UseCanonical Use the canonical form of the word
* @param Limit Maximum number of results to return
*/
def getAudio(Word: String, UseCanonical: Option[String] = None, Limit: Option[Int] = None): ApiRequest[Seq[AudioFile]] =
ApiRequest[Seq[AudioFile]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/audio", "application/json")
.withQueryParam("useCanonical", UseCanonical)
.withQueryParam("limit", Limit)
.withPathParam("word", Word)
.withSuccessResponse[Seq[AudioFile]](200)
.withErrorResponse[Unit](400)
/**
*
*
* Expected answers:
* code 200 : Seq[Definition] (success)
* code 400 : (Invalid word supplied.)
* code 404 : (No definitions found.)
*
* @param Word Word to return definitions for
* @param Limit Maximum number of results to return
* @param PartOfSpeech CSV list of part-of-speech types
* @param IncludeRelated Return related words with definitions
* @param SourceDictionaries Source dictionary to return definitions from. If &#39;all&#39; is received, results are returned from all sources. If multiple values are received (e.g. &#39;century,wiktionary&#39;), results are returned from the first specified dictionary that has definitions. If left blank, results are returned from the first dictionary that has definitions. By default, dictionaries are searched in this order: ahd, wiktionary, webster, century, wordnet
* @param UseCanonical If true will try to return the correct word root (&#39;cats&#39; -&gt; &#39;cat&#39;). If false returns exactly what was requested.
* @param IncludeTags Return a closed set of XML tags in response
*/
def getDefinitions(Word: String, Limit: Option[Int] = None, PartOfSpeech: Option[String] = None, IncludeRelated: Option[String] = None, SourceDictionaries: Seq[String], UseCanonical: Option[String] = None, IncludeTags: Option[String] = None): ApiRequest[Seq[Definition]] =
ApiRequest[Seq[Definition]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/definitions", "application/json")
.withQueryParam("limit", Limit)
.withQueryParam("partOfSpeech", PartOfSpeech)
.withQueryParam("includeRelated", IncludeRelated)
.withQueryParam("sourceDictionaries", ArrayValues(SourceDictionaries, CSV))
.withQueryParam("useCanonical", UseCanonical)
.withQueryParam("includeTags", IncludeTags)
.withPathParam("word", Word)
.withSuccessResponse[Seq[Definition]](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : Seq[String] (success)
* code 400 : (Invalid word supplied.)
* code 404 : (No definitions found.)
*
* @param Word Word to return
* @param UseCanonical If true will try to return the correct word root (&#39;cats&#39; -&gt; &#39;cat&#39;). If false returns exactly what was requested.
*/
def getEtymologies(Word: String, UseCanonical: Option[String] = None): ApiRequest[Seq[String]] =
ApiRequest[Seq[String]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/etymologies", "application/json")
.withQueryParam("useCanonical", UseCanonical)
.withPathParam("word", Word)
.withSuccessResponse[Seq[String]](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : (success)
* code 400 : (Invalid word supplied.)
*
* @param Word Word to return examples for
* @param IncludeDuplicates Show duplicate examples from different sources
* @param UseCanonical If true will try to return the correct word root (&#39;cats&#39; -&gt; &#39;cat&#39;). If false returns exactly what was requested.
* @param Skip Results to skip
* @param Limit Maximum number of results to return
*/
def getExamples(Word: String, IncludeDuplicates: Option[String] = None, UseCanonical: Option[String] = None, Skip: Option[Int] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/examples", "application/json")
.withQueryParam("includeDuplicates", IncludeDuplicates)
.withQueryParam("useCanonical", UseCanonical)
.withQueryParam("skip", Skip)
.withQueryParam("limit", Limit)
.withPathParam("word", Word)
.withSuccessResponse[Unit](200)
.withErrorResponse[Unit](400)
/**
*
*
* Expected answers:
* code 200 : FrequencySummary (success)
* code 400 : (Invalid word supplied.)
* code 404 : (No results.)
*
* @param Word Word to return
* @param UseCanonical If true will try to return the correct word root (&#39;cats&#39; -&gt; &#39;cat&#39;). If false returns exactly what was requested.
* @param StartYear Starting Year
* @param EndYear Ending Year
*/
def getWordFrequency(Word: String, UseCanonical: Option[String] = None, StartYear: Option[Int] = None, EndYear: Option[Int] = None): ApiRequest[FrequencySummary] =
ApiRequest[FrequencySummary](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/frequency", "application/json")
.withQueryParam("useCanonical", UseCanonical)
.withQueryParam("startYear", StartYear)
.withQueryParam("endYear", EndYear)
.withPathParam("word", Word)
.withSuccessResponse[FrequencySummary](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : (success)
* code 400 : (Invalid word supplied.)
*
* @param Word Word to get syllables for
* @param UseCanonical If true will try to return a correct word root (&#39;cats&#39; -&gt; &#39;cat&#39;). If false returns exactly what was requested.
* @param SourceDictionary Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet.
* @param Limit Maximum number of results to return
*/
def getHyphenation(Word: String, UseCanonical: Option[String] = None, SourceDictionary: Option[String] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/hyphenation", "application/json")
.withQueryParam("useCanonical", UseCanonical)
.withQueryParam("sourceDictionary", SourceDictionary)
.withQueryParam("limit", Limit)
.withPathParam("word", Word)
.withSuccessResponse[Unit](200)
.withErrorResponse[Unit](400)
/**
*
*
* Expected answers:
* code 200 : Seq[Bigram] (success)
* code 400 : (Invalid word supplied.)
*
* @param Word Word to fetch phrases for
* @param Limit Maximum number of results to return
* @param Wlmi Minimum WLMI for the phrase
* @param UseCanonical If true will try to return the correct word root (&#39;cats&#39; -&gt; &#39;cat&#39;). If false returns exactly what was requested.
*/
def getPhrases(Word: String, Limit: Option[Int] = None, Wlmi: Option[Int] = None, UseCanonical: Option[String] = None): ApiRequest[Seq[Bigram]] =
ApiRequest[Seq[Bigram]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/phrases", "application/json")
.withQueryParam("limit", Limit)
.withQueryParam("wlmi", Wlmi)
.withQueryParam("useCanonical", UseCanonical)
.withPathParam("word", Word)
.withSuccessResponse[Seq[Bigram]](200)
.withErrorResponse[Unit](400)
/**
*
*
* Expected answers:
* code 200 : (success)
* code 400 : (Invalid word supplied.)
*
* @param Word Word to get pronunciations for
* @param UseCanonical If true will try to return a correct word root (&#39;cats&#39; -&gt; &#39;cat&#39;). If false returns exactly what was requested.
* @param SourceDictionary Get from a single dictionary
* @param TypeFormat Text pronunciation type
* @param Limit Maximum number of results to return
*/
def getTextPronunciations(Word: String, UseCanonical: Option[String] = None, SourceDictionary: Option[String] = None, TypeFormat: Option[String] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/pronunciations", "application/json")
.withQueryParam("useCanonical", UseCanonical)
.withQueryParam("sourceDictionary", SourceDictionary)
.withQueryParam("typeFormat", TypeFormat)
.withQueryParam("limit", Limit)
.withPathParam("word", Word)
.withSuccessResponse[Unit](200)
.withErrorResponse[Unit](400)
/**
*
*
* Expected answers:
* code 200 : (success)
* code 400 : (Invalid word supplied.)
*
* @param Word Word to fetch relationships for
* @param UseCanonical If true will try to return the correct word root (&#39;cats&#39; -&gt; &#39;cat&#39;). If false returns exactly what was requested.
* @param RelationshipTypes Limits the total results per type of relationship type
* @param LimitPerRelationshipType Restrict to the supplied relationship types
*/
def getRelatedWords(Word: String, UseCanonical: Option[String] = None, RelationshipTypes: Option[String] = None, LimitPerRelationshipType: Option[Int] = None): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/relatedWords", "application/json")
.withQueryParam("useCanonical", UseCanonical)
.withQueryParam("relationshipTypes", RelationshipTypes)
.withQueryParam("limitPerRelationshipType", LimitPerRelationshipType)
.withPathParam("word", Word)
.withSuccessResponse[Unit](200)
.withErrorResponse[Unit](400)
/**
*
*
* Expected answers:
* code 200 : Example (success)
* code 400 : (Invalid word supplied.)
*
* @param Word Word to fetch examples for
* @param UseCanonical If true will try to return the correct word root (&#39;cats&#39; -&gt; &#39;cat&#39;). If false returns exactly what was requested.
*/
def getTopExample(Word: String, UseCanonical: Option[String] = None): ApiRequest[Example] =
ApiRequest[Example](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/topExample", "application/json")
.withQueryParam("useCanonical", UseCanonical)
.withPathParam("word", Word)
.withSuccessResponse[Example](200)
.withErrorResponse[Unit](400)
}

View File

@ -0,0 +1,154 @@
package io.swagger.client.api
import io.swagger.client.model.WordList
import io.swagger.client.model.StringValue
import io.swagger.client.core._
import io.swagger.client.core.CollectionFormats._
import io.swagger.client.core.ApiKeyLocations._
object WordListApi {
/**
*
*
* Expected answers:
* code 200 : WordList (success)
* code 400 : (Invalid ID supplied)
* code 403 : (Not Authorized to access WordList)
* code 404 : (WordList not found)
*
* @param Permalink permalink of WordList to fetch
* @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)
*/
def getWordListByPermalink(Permalink: String, AuthToken: String): ApiRequest[WordList] =
ApiRequest[WordList](ApiMethods.GET, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json")
.withPathParam("permalink", Permalink)
.withHeaderParam("auth_token", AuthToken)
.withSuccessResponse[WordList](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](403)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : (success)
* code 400 : (Invalid ID supplied)
* code 403 : (Not Authorized to update WordList)
* code 404 : (WordList not found)
*
* @param Permalink permalink of WordList to update
* @param Body Updated WordList
* @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)
*/
def updateWordList(Permalink: String, Body: Option[WordList] = None, AuthToken: String): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.PUT, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json")
.withBody(Body)
.withPathParam("permalink", Permalink)
.withHeaderParam("auth_token", AuthToken)
.withSuccessResponse[Unit](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](403)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : (success)
* code 400 : (Invalid ID supplied)
* code 403 : (Not Authorized to delete WordList)
* code 404 : (WordList not found)
*
* @param Permalink ID of WordList to delete
* @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)
*/
def deleteWordList(Permalink: String, AuthToken: String): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.DELETE, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json")
.withPathParam("permalink", Permalink)
.withHeaderParam("auth_token", AuthToken)
.withSuccessResponse[Unit](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](403)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : (success)
* code 400 : (Invalid permalink supplied)
* code 403 : (Not Authorized to modify WordList)
* code 404 : (WordList not found)
*
* @param Permalink permalink of WordList to use
* @param Body Words to remove from WordList
* @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)
*/
def deleteWordsFromWordList(Permalink: String, Body: Seq[StringValue], AuthToken: String): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/deleteWords", "application/json")
.withBody(Body)
.withPathParam("permalink", Permalink)
.withHeaderParam("auth_token", AuthToken)
.withSuccessResponse[Unit](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](403)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : (success)
* code 400 : (Invalid ID supplied)
* code 403 : (Not Authorized to access WordList)
* code 404 : (WordList not found)
*
* @param Permalink ID of WordList to use
* @param SortBy Field to sort by
* @param SortOrder Direction to sort
* @param Skip Results to skip
* @param Limit Maximum number of results to return
* @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)
*/
def getWordListWords(Permalink: String, SortBy: Option[String] = None, SortOrder: Option[String] = None, Skip: Option[Int] = None, Limit: Option[Int] = None, AuthToken: String): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json")
.withQueryParam("sortBy", SortBy)
.withQueryParam("sortOrder", SortOrder)
.withQueryParam("skip", Skip)
.withQueryParam("limit", Limit)
.withPathParam("permalink", Permalink)
.withHeaderParam("auth_token", AuthToken)
.withSuccessResponse[Unit](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](403)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : (success)
* code 400 : (Invalid permalink supplied)
* code 403 : (Not Authorized to access WordList)
* code 404 : (WordList not found)
*
* @param Permalink permalink of WordList to user
* @param Body Array of words to add to WordList
* @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)
*/
def addWordsToWordList(Permalink: String, Body: Seq[StringValue], AuthToken: String): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json")
.withBody(Body)
.withPathParam("permalink", Permalink)
.withHeaderParam("auth_token", AuthToken)
.withSuccessResponse[Unit](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](403)
.withErrorResponse[Unit](404)
}

View File

@ -0,0 +1,34 @@
package io.swagger.client.api
import io.swagger.client.model.WordList
import io.swagger.client.core._
import io.swagger.client.core.CollectionFormats._
import io.swagger.client.core.ApiKeyLocations._
object WordListsApi {
/**
*
*
* Expected answers:
* code 200 : WordList (success)
* code 400 : (Invalid WordList supplied or mandatory fields are missing)
* code 403 : (Not authenticated)
* code 404 : (WordList owner not found)
*
* @param Body WordList to create
* @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above)
*/
def createWordList(Body: Option[WordList] = None, AuthToken: String): ApiRequest[WordList] =
ApiRequest[WordList](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordLists.json", "application/json")
.withBody(Body)
.withHeaderParam("auth_token", AuthToken)
.withSuccessResponse[WordList](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](403)
.withErrorResponse[Unit](404)
}

View File

@ -0,0 +1,181 @@
package io.swagger.client.api
import io.swagger.client.model.WordObject
import io.swagger.client.model.DefinitionSearchResults
import io.swagger.client.model.WordSearchResults
import io.swagger.client.model.WordOfTheDay
import io.swagger.client.core._
import io.swagger.client.core.CollectionFormats._
import io.swagger.client.core.ApiKeyLocations._
object WordsApi {
/**
*
*
* Expected answers:
* code 200 : WordObject (success)
* code 404 : (No word found.)
*
* @param HasDictionaryDef Only return words with dictionary definitions
* @param IncludePartOfSpeech CSV part-of-speech values to include
* @param ExcludePartOfSpeech CSV part-of-speech values to exclude
* @param MinCorpusCount Minimum corpus frequency for terms
* @param MaxCorpusCount Maximum corpus frequency for terms
* @param MinDictionaryCount Minimum dictionary count
* @param MaxDictionaryCount Maximum dictionary count
* @param MinLength Minimum word length
* @param MaxLength Maximum word length
*/
def getRandomWord(HasDictionaryDef: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinDictionaryCount: Option[Int] = None, MaxDictionaryCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None): ApiRequest[WordObject] =
ApiRequest[WordObject](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/randomWord", "application/json")
.withQueryParam("hasDictionaryDef", HasDictionaryDef)
.withQueryParam("includePartOfSpeech", IncludePartOfSpeech)
.withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech)
.withQueryParam("minCorpusCount", MinCorpusCount)
.withQueryParam("maxCorpusCount", MaxCorpusCount)
.withQueryParam("minDictionaryCount", MinDictionaryCount)
.withQueryParam("maxDictionaryCount", MaxDictionaryCount)
.withQueryParam("minLength", MinLength)
.withQueryParam("maxLength", MaxLength)
.withSuccessResponse[WordObject](200)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : (success)
* code 400 : (Invalid term supplied.)
* code 404 : (No results.)
*
* @param HasDictionaryDef Only return words with dictionary definitions
* @param IncludePartOfSpeech CSV part-of-speech values to include
* @param ExcludePartOfSpeech CSV part-of-speech values to exclude
* @param MinCorpusCount Minimum corpus frequency for terms
* @param MaxCorpusCount Maximum corpus frequency for terms
* @param MinDictionaryCount Minimum dictionary count
* @param MaxDictionaryCount Maximum dictionary count
* @param MinLength Minimum word length
* @param MaxLength Maximum word length
* @param SortBy Attribute to sort by
* @param SortOrder Sort direction
* @param Limit Maximum number of results to return
*/
def getRandomWords(HasDictionaryDef: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinDictionaryCount: Option[Int] = None, MaxDictionaryCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None, SortBy: Option[String] = None, SortOrder: Option[String] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] =
ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/randomWords", "application/json")
.withQueryParam("hasDictionaryDef", HasDictionaryDef)
.withQueryParam("includePartOfSpeech", IncludePartOfSpeech)
.withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech)
.withQueryParam("minCorpusCount", MinCorpusCount)
.withQueryParam("maxCorpusCount", MaxCorpusCount)
.withQueryParam("minDictionaryCount", MinDictionaryCount)
.withQueryParam("maxDictionaryCount", MaxDictionaryCount)
.withQueryParam("minLength", MinLength)
.withQueryParam("maxLength", MaxLength)
.withQueryParam("sortBy", SortBy)
.withQueryParam("sortOrder", SortOrder)
.withQueryParam("limit", Limit)
.withSuccessResponse[Unit](200)
.withErrorResponse[Unit](400)
.withErrorResponse[Unit](404)
/**
*
*
* Expected answers:
* code 200 : DefinitionSearchResults (success)
* code 400 : (Invalid term supplied.)
*
* @param Query Search term
* @param FindSenseForWord Restricts words and finds closest sense
* @param IncludeSourceDictionaries Only include these comma-delimited source dictionaries
* @param ExcludeSourceDictionaries Exclude these comma-delimited source dictionaries
* @param IncludePartOfSpeech Only include these comma-delimited parts of speech
* @param ExcludePartOfSpeech Exclude these comma-delimited parts of speech
* @param MinCorpusCount Minimum corpus frequency for terms
* @param MaxCorpusCount Maximum corpus frequency for terms
* @param MinLength Minimum word length
* @param MaxLength Maximum word length
* @param ExpandTerms Expand terms
* @param IncludeTags Return a closed set of XML tags in response
* @param SortBy Attribute to sort by
* @param SortOrder Sort direction
* @param Skip Results to skip
* @param Limit Maximum number of results to return
*/
def reverseDictionary(Query: String, FindSenseForWord: Option[String] = None, IncludeSourceDictionaries: Option[String] = None, ExcludeSourceDictionaries: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None, ExpandTerms: Option[String] = None, IncludeTags: Option[String] = None, SortBy: Option[String] = None, SortOrder: Option[String] = None, Skip: Option[String] = None, Limit: Option[Int] = None): ApiRequest[DefinitionSearchResults] =
ApiRequest[DefinitionSearchResults](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/reverseDictionary", "application/json")
.withQueryParam("query", Query)
.withQueryParam("findSenseForWord", FindSenseForWord)
.withQueryParam("includeSourceDictionaries", IncludeSourceDictionaries)
.withQueryParam("excludeSourceDictionaries", ExcludeSourceDictionaries)
.withQueryParam("includePartOfSpeech", IncludePartOfSpeech)
.withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech)
.withQueryParam("minCorpusCount", MinCorpusCount)
.withQueryParam("maxCorpusCount", MaxCorpusCount)
.withQueryParam("minLength", MinLength)
.withQueryParam("maxLength", MaxLength)
.withQueryParam("expandTerms", ExpandTerms)
.withQueryParam("includeTags", IncludeTags)
.withQueryParam("sortBy", SortBy)
.withQueryParam("sortOrder", SortOrder)
.withQueryParam("skip", Skip)
.withQueryParam("limit", Limit)
.withSuccessResponse[DefinitionSearchResults](200)
.withErrorResponse[Unit](400)
/**
*
*
* Expected answers:
* code 200 : WordSearchResults (success)
* code 400 : (Invalid query supplied.)
*
* @param Query Search query
* @param CaseSensitive Search case sensitive
* @param IncludePartOfSpeech Only include these comma-delimited parts of speech
* @param ExcludePartOfSpeech Exclude these comma-delimited parts of speech
* @param MinCorpusCount Minimum corpus frequency for terms
* @param MaxCorpusCount Maximum corpus frequency for terms
* @param MinDictionaryCount Minimum number of dictionary entries for words returned
* @param MaxDictionaryCount Maximum dictionary definition count
* @param MinLength Minimum word length
* @param MaxLength Maximum word length
* @param Skip Results to skip
* @param Limit Maximum number of results to return
*/
def searchWords(Query: String, CaseSensitive: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinDictionaryCount: Option[Int] = None, MaxDictionaryCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None, Skip: Option[Int] = None, Limit: Option[Int] = None): ApiRequest[WordSearchResults] =
ApiRequest[WordSearchResults](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/search/{query}", "application/json")
.withQueryParam("caseSensitive", CaseSensitive)
.withQueryParam("includePartOfSpeech", IncludePartOfSpeech)
.withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech)
.withQueryParam("minCorpusCount", MinCorpusCount)
.withQueryParam("maxCorpusCount", MaxCorpusCount)
.withQueryParam("minDictionaryCount", MinDictionaryCount)
.withQueryParam("maxDictionaryCount", MaxDictionaryCount)
.withQueryParam("minLength", MinLength)
.withQueryParam("maxLength", MaxLength)
.withQueryParam("skip", Skip)
.withQueryParam("limit", Limit)
.withPathParam("query", Query)
.withSuccessResponse[WordSearchResults](200)
.withErrorResponse[Unit](400)
/**
*
*
* Expected answers:
* code 0 : WordOfTheDay (success)
*
* @param Date Fetches by date in yyyy-MM-dd
*/
def getWordOfTheDay(Date: Option[String] = None): ApiRequest[WordOfTheDay] =
ApiRequest[WordOfTheDay](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/wordOfTheDay", "application/json")
.withQueryParam("date", Date)
.withSuccessResponse[WordOfTheDay](0)
}

View File

@ -0,0 +1,323 @@
package io.swagger.client.core
import java.io.File
import java.security.cert.X509Certificate
import javax.net.ssl._
import akka.actor.ActorSystem
import akka.io.IO
import akka.pattern.ask
import akka.util.Timeout
import org.joda.time.DateTime
import org.joda.time.format.ISODateTimeFormat
import org.json4s.JsonAST.JString
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.Serialization
import spray.can.Http
import spray.can.Http.HostConnectorSetup
import spray.client.pipelining
import spray.client.pipelining._
import spray.http.HttpEncodings._
import spray.http.HttpHeaders.{RawHeader, `Accept-Encoding`}
import spray.http.Uri.Query
import spray.http._
import spray.http.parser.HttpParser
import spray.httpx.encoding.{Deflate, Encoder, Gzip}
import spray.httpx.unmarshalling._
import spray.io.ClientSSLEngineProvider
import scala.concurrent.{ExecutionContext, Future}
import scala.reflect.ClassTag
import scala.util.control.NonFatal
object ApiInvoker {
def apply()(implicit system: ActorSystem): ApiInvoker =
apply(DefaultFormats + DateTimeSerializer)
def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker =
apply(DefaultFormats + DateTimeSerializer ++ serializers)
def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats)
case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true)
def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess)
def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = {
StatusCodes.getForKey(code) foreach { c =>
StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true)
}
}
/**
* Allows request execution without calling apiInvoker.execute(request)
* request.response can be used to get a future of the ApiResponse generated.
* request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a
* Future will failed with a ClassCastException
* @param request the apiRequest to be executed
*/
implicit class ApiRequestImprovements[T](request: ApiRequest[T]) {
def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] =
response(ec, system, invoker)
def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] =
invoker.execute(request)
def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] =
invoker.execute(request).map(_.content).mapTo[U]
}
/**
* Allows transformation from ApiMethod to spray HttpMethods
* @param method the ApiMethod to be converted
*/
implicit class ApiMethodExtensions(val method: ApiMethod) {
def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET)
}
case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( {
case JString(s) =>
ISODateTimeFormat.dateTimeParser().parseDateTime(s)
}, {
case d: DateTime =>
JString(ISODateTimeFormat.dateTimeParser().print(d))
}))
}
class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes {
import io.swagger.client.core.ApiInvoker._
import io.swagger.client.core.ParametersMap._
implicit val ec = system.dispatcher
implicit val jsonFormats = formats
def settings = ApiSettings(system)
import spray.http.MessagePredicate._
val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) &&
Encoder.DefaultFilter &&
minEntitySize(settings.compressionSizeThreshold)
settings.customCodes.foreach(addCustomStatusCode)
private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer =
request =>
credentialsSeq.foldLeft(request) {
case (req, BasicCredentials(login, password)) =>
req ~> addCredentials(BasicHttpCredentials(login, password))
case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) =>
req ~> addHeader(RawHeader(keyName, keyValue.value))
case (req, _) => req
}
private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request =>
val rawHeaders = for {
(name, value) <- headers.asFormattedParams
header = RawHeader(name, String.valueOf(value))
} yield header
request.withHeaders(rawHeaders.toList)
}
private def bodyPart(name: String, value: Any): BodyPart = {
value match {
case f: File =>
BodyPart(f, name)
case v: String =>
BodyPart(HttpEntity(String.valueOf(v)))
case NumericValue(v) =>
BodyPart(HttpEntity(String.valueOf(v)))
case m: ApiModel =>
BodyPart(HttpEntity(Serialization.write(m)))
}
}
private def formDataContent(request: ApiRequest[_]) = {
val params = request.formParams.asFormattedParams
if (params.isEmpty)
None
else
Some(
normalizedContentType(request.contentType).mediaType match {
case MediaTypes.`multipart/form-data` =>
MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))})
case MediaTypes.`application/x-www-form-urlencoded` =>
FormData(params.mapValues(String.valueOf))
case m: MediaType => // Default : application/x-www-form-urlencoded.
FormData(params.mapValues(String.valueOf))
}
)
}
private def bodyContent(request: ApiRequest[_]): Option[Any] = {
request.bodyParam.map(Extraction.decompose).map(compact)
}
private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = {
val builder = new RequestBuilder(request.method.toSprayMethod)
val httpRequest = request.method.toSprayMethod match {
case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri)
case HttpMethods.POST | HttpMethods.PUT =>
formDataContent(request) orElse bodyContent(request) match {
case Some(c: FormData) =>
builder.apply(uri, c)
case Some(c: MultipartFormData) =>
builder.apply(uri, c)
case Some(c: String) =>
builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c))
case _ =>
builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " "))
}
case _ => builder.apply(uri)
}
httpRequest ~>
addHeaders(request.headerParams) ~>
addAuthentication(request.credentials) ~>
encode(Gzip(CompressionFilter))
}
def makeQuery(r: ApiRequest[_]): Query = {
r.credentials.foldLeft(r.queryParams) {
case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) =>
params + (keyName -> key.value)
case (params, _) => params
}.asFormattedParams
.mapValues(String.valueOf)
.foldRight[Query](Uri.Query.Empty) {
case ((name, value), acc) => acc.+:(name, value)
}
}
def makeUri(r: ApiRequest[_]): Uri = {
val opPath = r.operationPath.replaceAll("\\{format\\}", "json")
val opPathWithParams = r.pathParams.asFormattedParams
.mapValues(String.valueOf)
.foldLeft(opPath) {
case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value)
}
val query = makeQuery(r)
Uri(r.basePath + opPathWithParams).withQuery(query)
}
def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = {
try {
implicit val timeout: Timeout = settings.connectionTimeout
val uri = makeUri(r)
val connector = HostConnectorSetup(
uri.authority.host.toString,
uri.effectivePort,
sslEncryption = "https".equals(uri.scheme),
defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate)))
val request = createRequest(uri, r)
for {
Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector
response <- hostConnector.ask(request).mapTo[HttpResponse]
} yield {
response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r)
}
}
catch {
case NonFatal(x) => Future.failed(x)
}
}
def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = {
request.responseForCode(response.status.intValue) match {
case Some( (manifest: Manifest[T], state: ResponseState) ) =>
entityUnmarshaller(manifest)(response.entity) match {
case Right(value)
state match {
case ResponseState.Success =>
ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap)
case ResponseState.Error =>
throw new ApiError(response.status.intValue, "Error response received",
Some(value),
headers = response.headers.map(header => (header.name, header.value)).toMap)
}
case Left(MalformedContent(error, Some(cause)))
throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause)
case Left(MalformedContent(error, None))
throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString))
case Left(ContentExpected)
throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString))
}
case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString))
}
}
def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] =
Unmarshaller[T](MediaTypes.`application/json`) {
case x: HttpEntity.NonEmpty
parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`))
.noNulls
.camelizeKeys
.extract[T]
}
}
sealed trait CustomContentTypes {
def normalizedContentType(original: String): ContentType =
MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original)
def parseContentType(contentType: String): ContentType = {
val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType)
val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader)
(parsedContentTypeHeader: @unchecked) match {
case Right(ct: HttpHeaders.`Content-Type`) =>
ct.contentType
case Left(error: ErrorInfo) =>
throw new IllegalArgumentException(
s"Error converting '$contentType' to a ContentType header: '${error.summary}'")
}
}
}
sealed trait UntrustedSslContext {
this: ApiInvoker =>
implicit lazy val trustfulSslContext: SSLContext = {
settings.alwaysTrustCertificates match {
case false =>
SSLContext.getDefault
case true =>
class IgnoreX509TrustManager extends X509TrustManager {
def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {}
def getAcceptedIssuers = null
}
val context = SSLContext.getInstance("TLS")
context.init(null, Array(new IgnoreX509TrustManager), null)
context
}
}
implicit val clientSSLEngineProvider =
ClientSSLEngineProvider {
_ =>
val engine = trustfulSslContext.createSSLEngine()
engine.setUseClientMode(true)
engine
}
}

View File

@ -0,0 +1,50 @@
package io.swagger.client.core
sealed trait ResponseState
object ResponseState {
case object Success extends ResponseState
case object Error extends ResponseState
}
case class ApiRequest[U](
// required fields
method: ApiMethod,
basePath: String,
operationPath: String,
contentType: String,
// optional fields
responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty,
bodyParam: Option[Any] = None,
formParams: Map[String, Any] = Map.empty,
pathParams: Map[String, Any] = Map.empty,
queryParams: Map[String, Any] = Map.empty,
headerParams: Map[String, Any] = Map.empty,
credentials: Seq[Credentials] = List.empty) {
def withCredentials(cred: Credentials) = copy[U](credentials = credentials :+ cred)
def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) = withCredentials(ApiKeyCredentials(key, keyName, location))
def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Success)))
def withErrorResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Error)))
def withDefaultSuccessResponse[T](implicit m: Manifest[T]) = withSuccessResponse[T](0)
def withDefaultErrorResponse[T](implicit m: Manifest[T]) = withErrorResponse[T](0)
def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0)
def withoutBody() = copy[U](bodyParam = None)
def withBody(body: Any) = copy[U](bodyParam = Some(body))
def withFormParam(name: String, value: Any) = copy[U](formParams = formParams + (name -> value))
def withPathParam(name: String, value: Any) = copy[U](pathParams = pathParams + (name -> value))
def withQueryParam(name: String, value: Any) = copy[U](queryParams = queryParams + (name -> value))
def withHeaderParam(name: String, value: Any) = copy[U](headerParams = headerParams + (name -> value))
}

View File

@ -0,0 +1,32 @@
package io.swagger.client.core
import java.util.concurrent.TimeUnit
import akka.actor.{ExtendedActorSystem, Extension, ExtensionKey}
import com.typesafe.config.Config
import io.swagger.client.core.ApiInvoker.CustomStatusCode
import spray.http.HttpHeaders.RawHeader
import scala.collection.JavaConversions._
import scala.concurrent.duration.FiniteDuration
class ApiSettings(config: Config) extends Extension {
def this(system: ExtendedActorSystem) = this(system.settings.config)
private def cfg = config.getConfig("io.swagger.client.apiRequest")
val alwaysTrustCertificates = cfg.getBoolean("trust-certificates")
val defaultHeaders = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render))
val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS)
val compressionEnabled = cfg.getBoolean("compression.enabled")
val compressionSizeThreshold = cfg.getBytes("compression.size-threshold").toInt
val customCodes = cfg.getConfigList("custom-codes").toList.map { c => CustomStatusCode(
c.getInt("code"),
c.getString("reason"),
c.getBoolean("success"))
}
}
object ApiSettings extends ExtensionKey[ApiSettings]

View File

@ -0,0 +1,166 @@
package io.swagger.client.core
import java.io.File
import java.net.URLEncoder
import scala.util.Try
sealed trait ApiReturnWithHeaders {
def headers: Map[String, String]
def header(name: String): Option[String] = headers.get(name)
def getStringHeader(name: String) = header(name)
def getIntHeader(name: String) = castedHeader(name, java.lang.Integer.parseInt)
def getLongHeader(name: String) = castedHeader(name, java.lang.Long.parseLong)
def getFloatHeader(name: String) = castedHeader(name, java.lang.Float.parseFloat)
def getDoubleHeader(name: String) = castedHeader(name, java.lang.Double.parseDouble)
def getBooleanHeader(name: String) = castedHeader(name, java.lang.Boolean.parseBoolean)
private def castedHeader[U](name: String, conversion: String => U): Option[U] = { Try { header(name).map( conversion ) }.get }
}
sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty)
extends ApiReturnWithHeaders
sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty)
extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause)
with ApiReturnWithHeaders
sealed case class ApiMethod(value: String)
object ApiMethods {
val CONNECT = ApiMethod("CONNECT")
val DELETE = ApiMethod("DELETE")
val GET = ApiMethod("GET")
val HEAD = ApiMethod("HEAD")
val OPTIONS = ApiMethod("OPTIONS")
val PATCH = ApiMethod("PATCH")
val POST = ApiMethod("POST")
val PUT = ApiMethod("PUT")
val TRACE = ApiMethod("TRACE")
}
/**
* This trait needs to be added to any model defined by the api.
*/
trait ApiModel
/**
* Single trait defining a credential that can be transformed to a paramName / paramValue tupple
*/
sealed trait Credentials {
def asQueryParam: Option[(String, String)] = None
}
sealed case class BasicCredentials(user: String, password: String) extends Credentials
sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials {
override def asQueryParam: Option[(String, String)] = location match {
case ApiKeyLocations.QUERY => Some((keyName, key.value))
case _ => None
}
}
sealed case class ApiKeyValue(value: String)
sealed trait ApiKeyLocation
object ApiKeyLocations {
case object QUERY extends ApiKeyLocation
case object HEADER extends ApiKeyLocation
}
/**
* Case class used to unapply numeric values only in pattern matching
* @param value the string representation of the numeric value
*/
sealed case class NumericValue(value: String) {
override def toString = value
}
object NumericValue {
def unapply(n: Any): Option[NumericValue] = n match {
case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n)))
case _ => None
}
}
/**
* Used for params being arrays
*/
sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV)
object ArrayValues {
def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues =
ArrayValues(values.getOrElse(Seq.empty), format)
def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV)
}
/**
* Defines how arrays should be rendered in query strings.
*/
sealed trait CollectionFormat
trait MergedArrayFormat extends CollectionFormat {
def separator: String
}
object CollectionFormats {
case object CSV extends MergedArrayFormat {
override val separator = ","
}
case object TSV extends MergedArrayFormat {
override val separator = "\t"
}
case object SSV extends MergedArrayFormat {
override val separator = " "
}
case object PIPES extends MergedArrayFormat {
override val separator = "|"
}
case object MULTI extends CollectionFormat
}
object ParametersMap {
/**
* Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tupples,
* with valid url-encoding, arrays handling, files preservation, ...
*/
implicit class ParametersMapImprovements(val m: Map[String, Any]) {
def asFormattedParamsList = m.toList.flatMap(formattedParams)
def asFormattedParams = m.flatMap(formattedParams)
private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20")
private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2)
private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match {
case arr: ArrayValues =>
arr.format match {
case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _))
case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator)))
}
case None => Seq.empty
case Some(opt) =>
formattedParams(name, opt)
case s: Seq[Any] =>
formattedParams(name, ArrayValues(s))
case v: String => Seq((name, urlEncode(v)))
case NumericValue(v) => Seq((name, urlEncode(v)))
case f: File => Seq((name, f))
case m: ApiModel => Seq((name, m))
}
}
}

View File

@ -0,0 +1,16 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class ApiTokenStatus (
Valid: Option[Boolean],
Token: Option[String],
ResetsInMillis: Option[Long],
RemainingCalls: Option[Long],
ExpiresInMillis: Option[Long],
TotalRequests: Option[Long])
extends ApiModel

View File

@ -0,0 +1,24 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class AudioFile (
AttributionUrl: Option[String],
CommentCount: Option[Int],
VoteCount: Option[Int],
FileUrl: Option[String],
AudioType: Option[String],
Id: Option[Long],
Duration: Option[Double],
AttributionText: Option[String],
CreatedBy: Option[String],
Description: Option[String],
CreatedAt: Option[DateTime],
VoteWeightedAverage: Option[Float],
VoteAverage: Option[Float],
Word: Option[String])
extends ApiModel

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class AudioType (
Id: Option[Int],
Name: Option[String])
extends ApiModel

View File

@ -0,0 +1,13 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class AuthenticationToken (
Token: Option[String],
UserId: Option[Long],
UserSignature: Option[String])
extends ApiModel

View File

@ -0,0 +1,15 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Bigram (
Count: Option[Long],
Gram2: Option[String],
Gram1: Option[String],
Wlmi: Option[Double],
Mi: Option[Double])
extends ApiModel

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Category (
Id: Option[Long],
Name: Option[String])
extends ApiModel

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Citation (
Cite: Option[String],
Source: Option[String])
extends ApiModel

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class ContentProvider (
Id: Option[Int],
Name: Option[String])
extends ApiModel

View File

@ -0,0 +1,26 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Definition (
ExtendedText: Option[String],
Text: Option[String],
SourceDictionary: Option[String],
Citations: Option[Seq[Citation]],
Labels: Option[Seq[Label]],
Score: Option[Float],
ExampleUses: Option[Seq[ExampleUsage]],
AttributionUrl: Option[String],
SeqString: Option[String],
AttributionText: Option[String],
RelatedWords: Option[Seq[Related]],
Sequence: Option[String],
Word: Option[String],
Notes: Option[Seq[Note]],
TextProns: Option[Seq[TextPron]],
PartOfSpeech: Option[String])
extends ApiModel

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class DefinitionSearchResults (
Results: Option[Seq[Definition]],
TotalResults: Option[Int])
extends ApiModel

View File

@ -0,0 +1,22 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Example (
Id: Option[Long],
ExampleId: Option[Long],
Title: Option[String],
Text: Option[String],
Score: Option[ScoredWord],
Sentence: Option[Sentence],
Word: Option[String],
Provider: Option[ContentProvider],
Year: Option[Int],
Rating: Option[Float],
DocumentId: Option[Long],
Url: Option[String])
extends ApiModel

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class ExampleSearchResults (
Facets: Option[Seq[Facet]],
Examples: Option[Seq[Example]])
extends ApiModel

View File

@ -0,0 +1,11 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class ExampleUsage (
Text: Option[String])
extends ApiModel

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Facet (
FacetValues: Option[Seq[FacetValue]],
Name: Option[String])
extends ApiModel

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class FacetValue (
Count: Option[Long],
Value: Option[String])
extends ApiModel

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Frequency (
Count: Option[Long],
Year: Option[Int])
extends ApiModel

View File

@ -0,0 +1,15 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class FrequencySummary (
UnknownYearCount: Option[Int],
TotalCount: Option[Long],
FrequencyString: Option[String],
Word: Option[String],
Frequency: Option[Seq[Frequency]])
extends ApiModel

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Label (
Text: Option[String],
Type: Option[String])
extends ApiModel

View File

@ -0,0 +1,14 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Note (
NoteType: Option[String],
AppliesTo: Option[Seq[String]],
Value: Option[String],
Pos: Option[Int])
extends ApiModel

View File

@ -0,0 +1,13 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class PartOfSpeech (
Roots: Option[Seq[Root]],
StorageAbbr: Option[Seq[String]],
AllCategories: Option[Seq[Category]])
extends ApiModel

View File

@ -0,0 +1,17 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Related (
Label1: Option[String],
RelationshipType: Option[String],
Label2: Option[String],
Label3: Option[String],
Words: Option[Seq[String]],
Gram: Option[String],
Label4: Option[String])
extends ApiModel

View File

@ -0,0 +1,13 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Root (
Id: Option[Long],
Name: Option[String],
Categories: Option[Seq[Category]])
extends ApiModel

View File

@ -0,0 +1,21 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class ScoredWord (
Position: Option[Int],
Id: Option[Long],
DocTermCount: Option[Int],
Lemma: Option[String],
WordType: Option[String],
Score: Option[Float],
SentenceId: Option[Long],
Word: Option[String],
Stopword: Option[Boolean],
BaseWordScore: Option[Double],
PartOfSpeech: Option[String])
extends ApiModel

View File

@ -0,0 +1,16 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Sentence (
HasScoredWords: Option[Boolean],
Id: Option[Long],
ScoredWords: Option[Seq[ScoredWord]],
Display: Option[String],
Rating: Option[Int],
DocumentMetadataId: Option[Long])
extends ApiModel

View File

@ -0,0 +1,14 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class SimpleDefinition (
Text: Option[String],
Source: Option[String],
Note: Option[String],
PartOfSpeech: Option[String])
extends ApiModel

View File

@ -0,0 +1,14 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class SimpleExample (
Id: Option[Long],
Title: Option[String],
Text: Option[String],
Url: Option[String])
extends ApiModel

View File

@ -0,0 +1,11 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class StringValue (
Word: Option[String])
extends ApiModel

View File

@ -0,0 +1,13 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class Syllable (
Text: Option[String],
Seq: Option[Int],
Type: Option[String])
extends ApiModel

View File

@ -0,0 +1,13 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class TextPron (
Raw: Option[String],
Seq: Option[Int],
RawType: Option[String])
extends ApiModel

View File

@ -0,0 +1,18 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class User (
Id: Option[Long],
Username: Option[String],
Email: Option[String],
Status: Option[Int],
FaceBookId: Option[String],
UserName: Option[String],
DisplayName: Option[String],
Password: Option[String])
extends ApiModel

View File

@ -0,0 +1,21 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class WordList (
Id: Option[Long],
Permalink: Option[String],
Name: Option[String],
CreatedAt: Option[DateTime],
UpdatedAt: Option[DateTime],
LastActivityAt: Option[DateTime],
Username: Option[String],
UserId: Option[Long],
Description: Option[String],
NumberWordsInList: Option[Long],
Type: Option[String])
extends ApiModel

View File

@ -0,0 +1,17 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class WordListWord (
Id: Option[Long],
Word: Option[String],
Username: Option[String],
UserId: Option[Long],
CreatedAt: Option[DateTime],
NumberCommentsOnWord: Option[Long],
NumberLists: Option[Long])
extends ApiModel

View File

@ -0,0 +1,16 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class WordObject (
Id: Option[Long],
Word: Option[String],
OriginalWord: Option[String],
Suggestions: Option[Seq[String]],
CanonicalForm: Option[String],
Vulgar: Option[String])
extends ApiModel

View File

@ -0,0 +1,22 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class WordOfTheDay (
Id: Option[Long],
ParentId: Option[String],
Category: Option[String],
CreatedBy: Option[String],
CreatedAt: Option[DateTime],
ContentProvider: Option[ContentProvider],
HtmlExtra: Option[String],
Word: Option[String],
Definitions: Option[Seq[SimpleDefinition]],
Examples: Option[Seq[SimpleExample]],
Note: Option[String],
PublishDate: Option[DateTime])
extends ApiModel

View File

@ -0,0 +1,13 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class WordSearchResult (
Count: Option[Long],
Lexicality: Option[Double],
Word: Option[String])
extends ApiModel

View File

@ -0,0 +1,12 @@
package io.swagger.client.model
import io.swagger.client.core.ApiModel
import org.joda.time.DateTime
case class WordSearchResults (
SearchResults: Option[Seq[WordSearchResult]],
TotalResults: Option[Int])
extends ApiModel