Fix Scalatra petstore sample (#300)

* restore scalatra from codegen

* regenerate scalatra oas2 petstore, fix defaut value

* better code format for scalatra

* more format fix for scalatra

* update scalatra parameter template
This commit is contained in:
William Cheng
2018-05-03 13:26:04 +08:00
committed by GitHub
parent 751d09b162
commit 9cf185912c
19 changed files with 221 additions and 239 deletions

View File

@@ -218,7 +218,13 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
@Override
public String toDefaultValue(Schema p) {
if (ModelUtils.isBooleanSchema(p)) {
if (p.getDefault() != null) {
return p.getDefault().toString();
} else {
return null;
}
// comment out the following as the default value is no handled differently
/*if (ModelUtils.isBooleanSchema(p)) {
return "null";
} else if (ModelUtils.isDateSchema(p)) {
return "null";
@@ -239,7 +245,7 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
return "null";
} else {
return "null";
}
}*/
}
@Override
@@ -290,4 +296,5 @@ public abstract class AbstractScalaCodegen extends DefaultCodegen {
// remove " to avoid code injection
return input.replace("\"", "");
}
}

View File

@@ -10,8 +10,11 @@ class ScalatraBootstrap extends LifeCycle {
override def init(context: ServletContext) {
try {
{{#apiInfo}}{{#apis}}context mount (new {{classname}}, "{{basePathWithoutHost}}/{{baseName}}/*")
{{/apis}}{{/apiInfo}}
{{#apiInfo}}
{{#apis}}
context mount (new {{classname}}, "{{basePathWithoutHost}}/{{baseName}}/*")
{{/apis}}
{{/apiInfo}}
context mount (new ResourcesApp, "/api-docs/*")
} catch {
case e: Throwable => e.printStackTrace()

View File

@@ -33,19 +33,34 @@ class {{classname}}(implicit val swagger: Swagger) extends ScalatraServlet
{{newline}}
val {{nickname}}Operation = (apiOperation[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]("{{nickname}}")
summary "{{{summary}}}"
parameters({{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
summary "{{{summary}}}"
parameters({{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
)
{{httpMethod}}("{{{vendorExtensions.x-scalatra-path}}}",operation({{nickname}}Operation)) {
{{httpMethod}}("{{{vendorExtensions.x-scalatra-path}}}", operation({{nickname}}Operation)) {
{{#allParams}}
{{#isFile}}val {{paramName}} = fileParams("{{paramName}}"){{/isFile}}
{{^isFile}}{{#isPathParam}}
val {{paramName}} = params.getOrElse("{{paramName}}", halt(400)){{/isPathParam}}
{{>queryParamOperation}}{{>headerParamOperation}}{{>formParamMustache}}{{>bodyParamOperation}}
{{#isFile}}
val {{paramName}} = fileParams("{{paramName}}")
{{/isFile}}
println("{{paramName}}: " + {{paramName}})
{{/allParams}}
{{^isFile}}
{{#isPathParam}}
val {{paramName}} = params.getOrElse("{{paramName}}", halt(400))
{{/isPathParam}}
{{#isQueryParam}}
{{>queryParamOperation}}
{{/isQueryParam}}
{{#isHeaderParam}}
{{>headerParamOperation}}
{{/isHeaderParam}}
{{#isFormParams}}
{{>formParamOperation}}
{{/isFormParams}}
{{#isBodyParams}}
{{>bodyParamOperation}}
{{/isBodyParams}}
{{/isFile}}
//println("{{paramName}}: " + {{paramName}})
{{/allParams}}
}
{{/operation}}

View File

@@ -1,3 +1 @@
{{#isBodyParam}}
val {{paramName}} = parsedBody.extract[{{dataType}}]
{{/isBodyParam}}
val {{paramName}} = parsedBody.extract[{{dataType}}]

View File

@@ -1,3 +1 @@
{{#isFormParam}}
val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}")
{{/isFormParam}}
val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}")

View File

@@ -1,3 +1 @@
{{#isHeaderParam}}
val {{paramName}} = request.getHeader("{{paramName}}")
{{/isHeaderParam}}
val {{paramName}} = request.getHeader("{{paramName}}")

View File

@@ -8,9 +8,11 @@ package {{package}}
case class {{classname}}(
{{#vars}}
{{#description}}
/* {{{description}}} */
/* {{{description}}} */
{{/description}}
{{name}}: {{^required}}Option[{{/required}}{{datatype}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}}
{{/vars}})
{{/vars}}
)
{{/model}}
{{/models}}

View File

@@ -1,13 +1,12 @@
{{#isQueryParam}}
{{#collectionFormat}}val {{paramName}}String = params.getAs[String]("{{paramName}}")
val {{paramName}} = if("{{collectionFormat}}" == "default" || "{{collectionFormat}}" == "csv") {
{{paramName}}String match {
case Some(str) => str.split(",").toSeq
case None => Seq()
}
{{#collectionFormat}}val {{paramName}}String = params.getAs[String]("{{paramName}}")
val {{paramName}} = if("{{collectionFormat}}" == "default" || "{{collectionFormat}}" == "csv") {
{{paramName}}String match {
case Some(str) => str.split(",").toSeq
case None => Seq()
}
else
Seq()
{{/collectionFormat}}
{{^collectionFormat}}val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}"){{/collectionFormat}}
{{/isQueryParam}}
} else
Seq()
{{/collectionFormat}}
{{^collectionFormat}}
val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}")
{{/collectionFormat}}

View File

@@ -23,7 +23,6 @@ class ScalatraBootstrap extends LifeCycle {
context mount (new PetApi, "/v2/Pet/*")
context mount (new StoreApi, "/v2/Store/*")
context mount (new UserApi, "/v2/User/*")
context mount (new ResourcesApp, "/api-docs/*")
} catch {
case e: Throwable => e.printStackTrace()

View File

@@ -30,7 +30,7 @@ object ApiSwagger {
val apiInfo = ApiInfo(
"""Swagger Petstore""",
"""This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.""",
"""http://swagger.io""",
"""http://org.openapitools""",
"""apiteam@swagger.io""",
"""Apache-2.0""",
"""http://www.apache.org/licenses/LICENSE-2.0.html""")

View File

@@ -42,143 +42,118 @@ class PetApi(implicit val swagger: Swagger) extends ScalatraServlet
val addPetOperation = (apiOperation[Unit]("addPet")
summary "Add a new pet to the store"
parameters(bodyParam[Pet]("pet").description(""))
summary "Add a new pet to the store"
parameters(bodyParam[Pet]("pet").description(""))
)
post("/pet",operation(addPetOperation)) {
val pet = parsedBody.extract[Pet]
println("pet: " + pet)
post("/pet", operation(addPetOperation)) {
//println("pet: " + pet)
}
val deletePetOperation = (apiOperation[Unit]("deletePet")
summary "Deletes a pet"
parameters(pathParam[Long]("petId").description(""), headerParam[String]("apiKey").description("").optional)
summary "Deletes a pet"
parameters(pathParam[Long]("petId").description(""), headerParam[String]("apiKey").description("").optional)
)
delete("/pet/:petId",operation(deletePetOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
val apiKey = request.getHeader("apiKey")
println("apiKey: " + apiKey)
delete("/pet/:petId", operation(deletePetOperation)) {
val petId = params.getOrElse("petId", halt(400))
//println("petId: " + petId)
val apiKey = request.getHeader("apiKey")
//println("apiKey: " + apiKey)
}
val findPetsByStatusOperation = (apiOperation[List[Pet]]("findPetsByStatus")
summary "Finds Pets by status"
parameters(queryParam[List[String]]("status").description(""))
summary "Finds Pets by status"
parameters(queryParam[List[String]]("status").description(""))
)
get("/pet/findByStatus",operation(findPetsByStatusOperation)) {
val status = params.getAs[List[String]]("status")
get("/pet/findByStatus", operation(findPetsByStatusOperation)) {
val statusString = params.getAs[String]("status")
val status = if("csv" == "default" || "csv" == "csv") {
statusString match {
case Some(str) => str.split(",").toSeq
case None => Seq()
}
} else
Seq()
println("status: " + status)
//println("status: " + status)
}
val findPetsByTagsOperation = (apiOperation[List[Pet]]("findPetsByTags")
summary "Finds Pets by tags"
parameters(queryParam[List[String]]("tags").description(""))
summary "Finds Pets by tags"
parameters(queryParam[List[String]]("tags").description(""))
)
get("/pet/findByTags",operation(findPetsByTagsOperation)) {
val tags = params.getAs[List[String]]("tags")
get("/pet/findByTags", operation(findPetsByTagsOperation)) {
val tagsString = params.getAs[String]("tags")
val tags = if("csv" == "default" || "csv" == "csv") {
tagsString match {
case Some(str) => str.split(",").toSeq
case None => Seq()
}
} else
Seq()
println("tags: " + tags)
//println("tags: " + tags)
}
val getPetByIdOperation = (apiOperation[Pet]("getPetById")
summary "Find pet by ID"
parameters(pathParam[Long]("petId").description(""))
summary "Find pet by ID"
parameters(pathParam[Long]("petId").description(""))
)
get("/pet/:petId",operation(getPetByIdOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
get("/pet/:petId", operation(getPetByIdOperation)) {
val petId = params.getOrElse("petId", halt(400))
//println("petId: " + petId)
}
val updatePetOperation = (apiOperation[Unit]("updatePet")
summary "Update an existing pet"
parameters(bodyParam[Pet]("pet").description(""))
summary "Update an existing pet"
parameters(bodyParam[Pet]("pet").description(""))
)
put("/pet",operation(updatePetOperation)) {
val pet = parsedBody.extract[Pet]
println("pet: " + pet)
put("/pet", operation(updatePetOperation)) {
//println("pet: " + pet)
}
val updatePetWithFormOperation = (apiOperation[Unit]("updatePetWithForm")
summary "Updates a pet in the store with form data"
parameters(pathParam[Long]("petId").description(""), formParam[String]("name").description("").optional, formParam[String]("status").description("").optional)
summary "Updates a pet in the store with form data"
parameters(pathParam[Long]("petId").description(""), formParam[String]("name").description("").optional, formParam[String]("status").description("").optional)
)
post("/pet/:petId",operation(updatePetWithFormOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
val name = params.getAs[String]("name")
println("name: " + name)
val status = params.getAs[String]("status")
println("status: " + status)
post("/pet/:petId", operation(updatePetWithFormOperation)) {
val petId = params.getOrElse("petId", halt(400))
//println("petId: " + petId)
//println("name: " + name)
//println("status: " + status)
}
val uploadFileOperation = (apiOperation[ApiResponse]("uploadFile")
summary "uploads an image"
parameters(pathParam[Long]("petId").description(""), formParam[String]("additionalMetadata").description("").optional, formParam[File]("file").description("").optional)
summary "uploads an image"
parameters(pathParam[Long]("petId").description(""), formParam[String]("additionalMetadata").description("").optional, formParam[File]("file").description("").optional)
)
post("/pet/:petId/uploadImage",operation(uploadFileOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
val additionalMetadata = params.getAs[String]("additionalMetadata")
println("additionalMetadata: " + additionalMetadata)
post("/pet/:petId/uploadImage", operation(uploadFileOperation)) {
val petId = params.getOrElse("petId", halt(400))
//println("petId: " + petId)
//println("additionalMetadata: " + additionalMetadata)
val file = fileParams("file")
println("file: " + file)
//println("file: " + file)
}
}

View File

@@ -40,56 +40,46 @@ class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet
val deleteOrderOperation = (apiOperation[Unit]("deleteOrder")
summary "Delete purchase order by ID"
parameters(pathParam[String]("orderId").description(""))
summary "Delete purchase order by ID"
parameters(pathParam[String]("orderId").description(""))
)
delete("/store/order/:orderId",operation(deleteOrderOperation)) {
val orderId = params.getOrElse("orderId", halt(400))
println("orderId: " + orderId)
delete("/store/order/:orderId", operation(deleteOrderOperation)) {
val orderId = params.getOrElse("orderId", halt(400))
//println("orderId: " + orderId)
}
val getInventoryOperation = (apiOperation[Map[String, Int]]("getInventory")
summary "Returns pet inventories by status"
parameters()
summary "Returns pet inventories by status"
parameters()
)
get("/store/inventory",operation(getInventoryOperation)) {
get("/store/inventory", operation(getInventoryOperation)) {
}
val getOrderByIdOperation = (apiOperation[Order]("getOrderById")
summary "Find purchase order by ID"
parameters(pathParam[Long]("orderId").description(""))
summary "Find purchase order by ID"
parameters(pathParam[Long]("orderId").description(""))
)
get("/store/order/:orderId",operation(getOrderByIdOperation)) {
val orderId = params.getOrElse("orderId", halt(400))
println("orderId: " + orderId)
get("/store/order/:orderId", operation(getOrderByIdOperation)) {
val orderId = params.getOrElse("orderId", halt(400))
//println("orderId: " + orderId)
}
val placeOrderOperation = (apiOperation[Order]("placeOrder")
summary "Place an order for a pet"
parameters(bodyParam[Order]("order").description(""))
summary "Place an order for a pet"
parameters(bodyParam[Order]("order").description(""))
)
post("/store/order",operation(placeOrderOperation)) {
val order = parsedBody.extract[Order]
println("order: " + order)
post("/store/order", operation(placeOrderOperation)) {
//println("order: " + order)
}
}

View File

@@ -40,126 +40,97 @@ class UserApi(implicit val swagger: Swagger) extends ScalatraServlet
val createUserOperation = (apiOperation[Unit]("createUser")
summary "Create user"
parameters(bodyParam[User]("user").description(""))
summary "Create user"
parameters(bodyParam[User]("user").description(""))
)
post("/user",operation(createUserOperation)) {
val user = parsedBody.extract[User]
println("user: " + user)
post("/user", operation(createUserOperation)) {
//println("user: " + user)
}
val createUsersWithArrayInputOperation = (apiOperation[Unit]("createUsersWithArrayInput")
summary "Creates list of users with given input array"
parameters(bodyParam[List[User]]("user").description(""))
summary "Creates list of users with given input array"
parameters(bodyParam[List[User]]("user").description(""))
)
post("/user/createWithArray",operation(createUsersWithArrayInputOperation)) {
val user = parsedBody.extract[List[User]]
println("user: " + user)
post("/user/createWithArray", operation(createUsersWithArrayInputOperation)) {
//println("user: " + user)
}
val createUsersWithListInputOperation = (apiOperation[Unit]("createUsersWithListInput")
summary "Creates list of users with given input array"
parameters(bodyParam[List[User]]("user").description(""))
summary "Creates list of users with given input array"
parameters(bodyParam[List[User]]("user").description(""))
)
post("/user/createWithList",operation(createUsersWithListInputOperation)) {
val user = parsedBody.extract[List[User]]
println("user: " + user)
post("/user/createWithList", operation(createUsersWithListInputOperation)) {
//println("user: " + user)
}
val deleteUserOperation = (apiOperation[Unit]("deleteUser")
summary "Delete user"
parameters(pathParam[String]("username").description(""))
summary "Delete user"
parameters(pathParam[String]("username").description(""))
)
delete("/user/:username",operation(deleteUserOperation)) {
val username = params.getOrElse("username", halt(400))
println("username: " + username)
delete("/user/:username", operation(deleteUserOperation)) {
val username = params.getOrElse("username", halt(400))
//println("username: " + username)
}
val getUserByNameOperation = (apiOperation[User]("getUserByName")
summary "Get user by user name"
parameters(pathParam[String]("username").description(""))
summary "Get user by user name"
parameters(pathParam[String]("username").description(""))
)
get("/user/:username",operation(getUserByNameOperation)) {
val username = params.getOrElse("username", halt(400))
println("username: " + username)
get("/user/:username", operation(getUserByNameOperation)) {
val username = params.getOrElse("username", halt(400))
//println("username: " + username)
}
val loginUserOperation = (apiOperation[String]("loginUser")
summary "Logs user into the system"
parameters(queryParam[String]("username").description(""), queryParam[String]("password").description(""))
summary "Logs user into the system"
parameters(queryParam[String]("username").description(""), queryParam[String]("password").description(""))
)
get("/user/login",operation(loginUserOperation)) {
val username = params.getAs[String]("username")
get("/user/login", operation(loginUserOperation)) {
val username = params.getAs[String]("username")
println("username: " + username)
val password = params.getAs[String]("password")
//println("username: " + username)
val password = params.getAs[String]("password")
println("password: " + password)
//println("password: " + password)
}
val logoutUserOperation = (apiOperation[Unit]("logoutUser")
summary "Logs out current logged in user session"
parameters()
summary "Logs out current logged in user session"
parameters()
)
get("/user/logout",operation(logoutUserOperation)) {
get("/user/logout", operation(logoutUserOperation)) {
}
val updateUserOperation = (apiOperation[Unit]("updateUser")
summary "Updated user"
parameters(pathParam[String]("username").description(""), bodyParam[User]("user").description(""))
summary "Updated user"
parameters(pathParam[String]("username").description(""), bodyParam[User]("user").description(""))
)
put("/user/:username",operation(updateUserOperation)) {
val username = params.getOrElse("username", halt(400))
println("username: " + username)
val user = parsedBody.extract[User]
println("user: " + user)
put("/user/:username", operation(updateUserOperation)) {
val username = params.getOrElse("username", halt(400))
//println("username: " + username)
//println("user: " + user)
}
}

View File

@@ -13,6 +13,9 @@ package io.swagger.server.model
case class ApiResponse(
code: Option[Int],
`type`: Option[String],
message: Option[String]
)
`type`: Option[String],
message: Option[String]
)

View File

@@ -13,5 +13,7 @@ package io.swagger.server.model
case class Category(
id: Option[Long],
name: Option[String]
)
name: Option[String]
)

View File

@@ -14,10 +14,16 @@ import java.util.Date
case class Order(
id: Option[Long],
petId: Option[Long],
quantity: Option[Int],
shipDate: Option[Date],
petId: Option[Long],
quantity: Option[Int],
shipDate: Option[Date],
/* Order Status */
status: Option[String],
complete: Option[Boolean]
)
complete: Option[Boolean]
)

View File

@@ -13,10 +13,16 @@ package io.swagger.server.model
case class Pet(
id: Option[Long],
category: Option[Category],
name: String,
photoUrls: List[String],
tags: Option[List[Tag]],
category: Option[Category],
name: String,
photoUrls: List[String],
tags: Option[List[Tag]],
/* pet status in the store */
status: Option[String]
)
)

View File

@@ -13,5 +13,7 @@ package io.swagger.server.model
case class Tag(
id: Option[Long],
name: Option[String]
)
name: Option[String]
)

View File

@@ -13,12 +13,20 @@ package io.swagger.server.model
case class User(
id: Option[Long],
username: Option[String],
firstName: Option[String],
lastName: Option[String],
email: Option[String],
password: Option[String],
phone: Option[String],
username: Option[String],
firstName: Option[String],
lastName: Option[String],
email: Option[String],
password: Option[String],
phone: Option[String],
/* User Status */
userStatus: Option[Int]
)
)