[Scalatra] replace {} with : in scalatra path (#3694)

* replace {} with : in scalatra path

* remove unused var in scalatra code gen
This commit is contained in:
wing328 2016-09-02 00:25:07 +08:00 committed by GitHub
parent 5467c41dad
commit 11ae12b09d
13 changed files with 282 additions and 181 deletions

View File

@ -4,6 +4,7 @@ import io.swagger.codegen.CliOption;
import io.swagger.codegen.CodegenConfig;
import io.swagger.codegen.CodegenConstants;
import io.swagger.codegen.CodegenOperation;
import io.swagger.codegen.CodegenParameter;
import io.swagger.codegen.CodegenType;
import io.swagger.codegen.DefaultCodegen;
import io.swagger.codegen.SupportingFile;
@ -161,8 +162,29 @@ public class ScalatraServerCodegen extends DefaultCodegen implements CodegenConf
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) operations.get("operation");
for (CodegenOperation op : operationList) {
// force http method to lower case
op.httpMethod = op.httpMethod.toLowerCase();
String[] items = op.path.split("/", -1);
String scalaPath = "";
int pathParamIndex = 0;
for (int i = 0; i < items.length; ++i) {
if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {}
scalaPath = scalaPath + ":" + items[i].replace("{", "").replace("}", "");
pathParamIndex++;
} else {
scalaPath = scalaPath + items[i];
}
if (i != items.length -1) {
scalaPath = scalaPath + "/";
}
}
op.vendorExtensions.put("x-scalatra-path", scalaPath);
}
return objs;
}

View File

@ -38,7 +38,7 @@ class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet
parameters({{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}})
)
{{httpMethod}}("{{path}}",operation({{nickname}}Operation)) {
{{httpMethod}}("{{{vendorExtensions.x-scalatra-path}}}",operation({{nickname}}Operation)) {
{{#allParams}}
{{#isFile}}val {{paramName}} = fileParams("{{paramName}}"){{/isFile}}
{{^isFile}}{{#isPathParam}}

View File

@ -24,7 +24,7 @@
import com.wordnik.client.api._
import akka.actor.ActorSystem
import io.swagger.app.{ ResourcesApp, SwaggerApp }
import io.swagger.app.{ResourcesApp, SwaggerApp}
import javax.servlet.ServletContext
import org.scalatra.LifeCycle
@ -37,7 +37,7 @@ 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

@ -27,26 +27,26 @@ package io.swagger.app
import _root_.akka.actor.ActorSystem
import org.scalatra.swagger.{ ApiInfo, SwaggerWithAuth, Swagger }
import org.scalatra.swagger.{ JacksonSwaggerBase, Swagger }
import org.scalatra.swagger.{JacksonSwaggerBase, Swagger}
import org.scalatra.ScalatraServlet
import org.json4s.{ DefaultFormats, Formats }
import org.json4s.{DefaultFormats, Formats}
class ResourcesApp(implicit protected val system: ActorSystem, val swagger: SwaggerApp)
extends ScalatraServlet with JacksonSwaggerBase {
extends ScalatraServlet with JacksonSwaggerBase {
before() {
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
protected def buildFullUrl(path: String) = if (path.startsWith("http")) path else {
val port = request.getServerPort
val h = request.getServerName
val prot = if (port == 443) "https" else "http"
val (proto, host) = if (port != 80 && port != 443) ("http", h + ":" + port.toString) else (prot, h)
"%s://%s%s%s".format(
proto,
host,
request.getContextPath,
path)
val port = request.getServerPort
val h = request.getServerName
val prot = if (port == 443) "https" else "http"
val (proto, host) = if (port != 80 && port != 443) ("http", h+":"+port.toString) else (prot, h)
"%s://%s%s%s".format(
proto,
host,
request.getContextPath,
path)
}
}

View File

@ -25,8 +25,8 @@
package com.wordnik.client.api
import com.wordnik.client.model.Pet
import java.io.File
import com.wordnik.client.model.ApiResponse
import java.io.File
import java.io.File
@ -35,11 +35,11 @@ import org.scalatra.swagger._
import org.json4s._
import org.json4s.JsonDSL._
import org.scalatra.json.{ JValueResult, JacksonJsonSupport }
import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException }
import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException}
import scala.collection.JavaConverters._
class PetApi(implicit val swagger: Swagger) extends ScalatraServlet
class PetApi (implicit val swagger: Swagger) extends ScalatraServlet
with FileUploadSupport
with JacksonJsonSupport
with SwaggerSupport {
@ -52,133 +52,164 @@ class PetApi(implicit val swagger: Swagger) extends ScalatraServlet
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
val addPetOperation = (apiOperation[Unit]("addPet")
summary "Add a new pet to the store"
parameters (bodyParam[Pet]("body").description(""))
summary "Add a new pet to the store"
parameters(bodyParam[Pet]("body").description(""))
)
post("/pet", operation(addPetOperation)) {
val body = parsedBody.extract[Pet]
post("/pet",operation(addPetOperation)) {
val body = parsedBody.extract[Pet]
println("body: " + body)
}
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))
delete("/pet/:petId",operation(deletePetOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
val apiKey = request.getHeader("apiKey")
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 statusString = params.getAs[String]("status")
val status = if ("multi".equals("default")) {
statusString match {
case Some(str) => str.split(",")
case None => List()
get("/pet/findByStatus",operation(findPetsByStatusOperation)) {
val statusString = params.getAs[String]("status")
val status = if("csv".equals("default")) {
statusString match {
case Some(str) => str.split(",")
case None => List()
}
}
} else
List()
else
List()
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 tagsString = params.getAs[String]("tags")
val tags = if ("multi".equals("default")) {
tagsString match {
case Some(str) => str.split(",")
case None => List()
get("/pet/findByTags",operation(findPetsByTagsOperation)) {
val tagsString = params.getAs[String]("tags")
val tags = if("csv".equals("default")) {
tagsString match {
case Some(str) => str.split(",")
case None => List()
}
}
} else
List()
else
List()
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))
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]("body").description(""))
summary "Update an existing pet"
parameters(bodyParam[Pet]("body").description(""))
)
put("/pet", operation(updatePetOperation)) {
val body = parsedBody.extract[Pet]
put("/pet",operation(updatePetOperation)) {
val body = parsedBody.extract[Pet]
println("body: " + body)
}
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))
post("/pet/:petId",operation(updatePetWithFormOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
val name = params.getAs[String]("name")
val name = params.getAs[String]("name")
println("name: " + name)
val status = params.getAs[String]("status")
val status = params.getAs[String]("status")
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))
post("/pet/:petId/uploadImage",operation(uploadFileOperation)) {
val petId = params.getOrElse("petId", halt(400))
println("petId: " + petId)
val additionalMetadata = params.getAs[String]("additionalMetadata")
val additionalMetadata = params.getAs[String]("additionalMetadata")
println("additionalMetadata: " + additionalMetadata)
val file = fileParams("file")
println("file: " + file)
println("file: " + file)
}
}

View File

@ -33,11 +33,11 @@ import org.scalatra.swagger._
import org.json4s._
import org.json4s.JsonDSL._
import org.scalatra.json.{ JValueResult, JacksonJsonSupport }
import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException }
import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException}
import scala.collection.JavaConverters._
class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet
class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet
with FileUploadSupport
with JacksonJsonSupport
with SwaggerSupport {
@ -50,47 +50,57 @@ class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
val deleteOrderOperation = (apiOperation[Unit]("deleteOrder")
summary "Delete purchase order by ID"
parameters (pathParam[Long]("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))
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))
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]("body").description(""))
summary "Place an order for a pet"
parameters(bodyParam[Order]("body").description(""))
)
post("/store/order", operation(placeOrderOperation)) {
val body = parsedBody.extract[Order]
post("/store/order",operation(placeOrderOperation)) {
val body = parsedBody.extract[Order]
println("body: " + body)
}

View File

@ -33,11 +33,11 @@ import org.scalatra.swagger._
import org.json4s._
import org.json4s.JsonDSL._
import org.scalatra.json.{ JValueResult, JacksonJsonSupport }
import org.scalatra.servlet.{ FileUploadSupport, MultipartConfig, SizeConstraintExceededException }
import org.scalatra.servlet.{FileUploadSupport, MultipartConfig, SizeConstraintExceededException}
import scala.collection.JavaConverters._
class UserApi(implicit val swagger: Swagger) extends ScalatraServlet
class UserApi (implicit val swagger: Swagger) extends ScalatraServlet
with FileUploadSupport
with JacksonJsonSupport
with SwaggerSupport {
@ -50,103 +50,127 @@ class UserApi(implicit val swagger: Swagger) extends ScalatraServlet
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
val createUserOperation = (apiOperation[Unit]("createUser")
summary "Create user"
parameters (bodyParam[User]("body").description(""))
summary "Create user"
parameters(bodyParam[User]("body").description(""))
)
post("/user", operation(createUserOperation)) {
val body = parsedBody.extract[User]
post("/user",operation(createUserOperation)) {
val body = parsedBody.extract[User]
println("body: " + body)
}
val createUsersWithArrayInputOperation = (apiOperation[Unit]("createUsersWithArrayInput")
summary "Creates list of users with given input array"
parameters (bodyParam[List[User]]("body").description(""))
summary "Creates list of users with given input array"
parameters(bodyParam[List[User]]("body").description(""))
)
post("/user/createWithArray", operation(createUsersWithArrayInputOperation)) {
val body = parsedBody.extract[List[User]]
post("/user/createWithArray",operation(createUsersWithArrayInputOperation)) {
val body = parsedBody.extract[List[User]]
println("body: " + body)
}
val createUsersWithListInputOperation = (apiOperation[Unit]("createUsersWithListInput")
summary "Creates list of users with given input array"
parameters (bodyParam[List[User]]("body").description(""))
summary "Creates list of users with given input array"
parameters(bodyParam[List[User]]("body").description(""))
)
post("/user/createWithList", operation(createUsersWithListInputOperation)) {
val body = parsedBody.extract[List[User]]
post("/user/createWithList",operation(createUsersWithListInputOperation)) {
val body = parsedBody.extract[List[User]]
println("body: " + body)
}
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))
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))
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")
val password = params.getAs[String]("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]("body").description(""))
summary "Updated user"
parameters(pathParam[String]("username").description(""), bodyParam[User]("body").description(""))
)
put("/user/{username}", operation(updateUserOperation)) {
val username = params.getOrElse("username", halt(400))
put("/user/:username",operation(updateUserOperation)) {
val username = params.getOrElse("username", halt(400))
println("username: " + username)
val body = parsedBody.extract[User]
val body = parsedBody.extract[User]
println("body: " + body)
}

View File

@ -24,7 +24,10 @@
package com.wordnik.client.model
case class ApiResponse(
case class ApiResponse (
code: Option[Int],
_type: Option[String],
message: Option[String])
_type: Option[String],
message: Option[String]
)

View File

@ -24,6 +24,9 @@
package com.wordnik.client.model
case class Category(
case class Category (
id: Option[Long],
name: Option[String])
name: Option[String]
)

View File

@ -26,10 +26,12 @@ package com.wordnik.client.model
import java.util.Date
case class Order(
case class Order (
id: Option[Long],
petId: Option[Long],
quantity: Option[Int],
shipDate: Option[Date],
status: Option[String], // Order Status
complete: Option[Boolean])
petId: Option[Long],
quantity: Option[Int],
shipDate: Option[Date],
status: Option[String], // Order Status
complete: Option[Boolean]
)

View File

@ -27,11 +27,12 @@ package com.wordnik.client.model
import com.wordnik.client.model.Category
import com.wordnik.client.model.Tag
case class Pet(
case class Pet (
id: Option[Long],
category: Option[Category],
name: String,
photoUrls: List[String],
tags: Option[List[Tag]],
status: Option[String] // pet status in the store
)
category: Option[Category],
name: String,
photoUrls: List[String],
tags: Option[List[Tag]],
status: Option[String] // pet status in the store
)

View File

@ -24,6 +24,9 @@
package com.wordnik.client.model
case class Tag(
case class Tag (
id: Option[Long],
name: Option[String])
name: Option[String]
)

View File

@ -24,13 +24,15 @@
package com.wordnik.client.model
case class User(
case class User (
id: Option[Long],
username: Option[String],
firstName: Option[String],
lastName: Option[String],
email: Option[String],
password: Option[String],
phone: Option[String],
userStatus: Option[Int] // User Status
)
username: Option[String],
firstName: Option[String],
lastName: Option[String],
email: Option[String],
password: Option[String],
phone: Option[String],
userStatus: Option[Int] // User Status
)