├── settings.gradle ├── .travis.yml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── test │ └── scala │ │ └── com │ │ └── github │ │ └── xiaodongw │ │ └── swagger │ │ └── finatra │ │ ├── Gender.java │ │ ├── SampleApp.scala │ │ ├── Models.scala │ │ └── SampleController.scala └── main │ └── scala │ └── com │ ├── github │ └── xiaodongw │ │ └── swagger │ │ └── finatra │ │ ├── SwaggerSupport.scala │ │ ├── SchemaUtil.scala │ │ ├── SwaggerController.scala │ │ ├── WebjarsController.scala │ │ ├── FinatraOperation.scala │ │ └── FinatraSwagger.scala │ └── twitter │ └── finatra │ └── http │ └── SwaggerRouteDSL.scala ├── publish.md ├── .gitignore ├── finatra1.md ├── README.md ├── publish.gradle ├── gradlew.bat ├── gradlew └── LICENSE /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'swagger-finatra' -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | jdk: 3 | - oraclejdk8 4 | 5 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiaodongw/swagger-finatra/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /src/test/scala/com/github/xiaodongw/swagger/finatra/Gender.java: -------------------------------------------------------------------------------- 1 | package com.github.xiaodongw.swagger.finatra; 2 | 3 | public enum Gender { 4 | Male, 5 | Female 6 | } 7 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Nov 29 20:30:46 PST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-bin.zip 7 | -------------------------------------------------------------------------------- /publish.md: -------------------------------------------------------------------------------- 1 | Publish to Maven Central 2 | 3 | 1. Publish to Sonatype 4 | 5 | gradle clean uploadArchives 6 | 7 | 2. Promote to Maven Central 8 | * Go to https://oss.sonatype.org/ 9 | * Close the staging repository if there is no problem. 10 | * Release the repository if close succeeded. 11 | 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | *.log 3 | 4 | # sbt specific 5 | .cache/ 6 | .history/ 7 | .lib/ 8 | dist/* 9 | target/ 10 | lib_managed/ 11 | src_managed/ 12 | project/boot/ 13 | project/plugins/project/ 14 | 15 | # Scala-IDE specific 16 | .scala_dependencies 17 | .worksheet 18 | 19 | # Intellij 20 | .idea 21 | *.iml 22 | classes/ 23 | 24 | # Gradle 25 | .gradle 26 | gradle.properties 27 | build/ 28 | -------------------------------------------------------------------------------- /src/main/scala/com/github/xiaodongw/swagger/finatra/SwaggerSupport.scala: -------------------------------------------------------------------------------- 1 | package com.github.xiaodongw.swagger.finatra 2 | 3 | import com.twitter.finatra.http.{Controller, SwaggerRouteDSL} 4 | 5 | trait SwaggerSupport extends SwaggerRouteDSL { 6 | self: Controller => 7 | override protected val dsl = self 8 | 9 | implicit protected val convertToFinatraOperation = FinatraOperation.convertToFinatraOperation _ 10 | implicit protected val convertToFinatraSwagger = FinatraSwagger.convertToFinatraSwagger _ 11 | implicit protected val convertToSwaggerRouteDSL = SwaggerRouteDSL.convertToSwaggerRouteDSL _ 12 | } 13 | -------------------------------------------------------------------------------- /src/main/scala/com/github/xiaodongw/swagger/finatra/SchemaUtil.scala: -------------------------------------------------------------------------------- 1 | package com.github.xiaodongw.swagger.finatra 2 | 3 | import io.swagger.models.{ArrayModel, Model, RefModel} 4 | import io.swagger.models.properties.{ArrayProperty, Property, RefProperty} 5 | 6 | object SchemaUtil { 7 | def toModel(schema: Property): Model = { 8 | val model = schema match { 9 | case null => null 10 | case p: RefProperty => new RefModel(p.getSimpleRef) 11 | case p: ArrayProperty => { 12 | val arrayModel = new ArrayModel() 13 | arrayModel.setItems(p.getItems) 14 | arrayModel 15 | } 16 | case _ => null 17 | } 18 | model 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/scala/com/github/xiaodongw/swagger/finatra/SwaggerController.scala: -------------------------------------------------------------------------------- 1 | package com.github.xiaodongw.swagger.finatra 2 | 3 | import com.twitter.finagle.http.Request 4 | import com.twitter.finatra.http.Controller 5 | import com.twitter.finatra.response.Mustache 6 | import io.swagger.models.Swagger 7 | import io.swagger.util.Json 8 | 9 | class SwaggerController(docPath: String = "/api-docs", swagger: Swagger) extends Controller { 10 | get(s"${docPath}/model") { request: Request => 11 | response.ok.body(Json.mapper.writeValueAsString(swagger)) 12 | .contentType("application/json").toFuture 13 | } 14 | 15 | get(s"${docPath}/ui") { request: Request => 16 | response.temporaryRedirect 17 | .location(s"/webjars/swagger-ui/2.2.8/index.html?url=${docPath}/model") 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/test/scala/com/github/xiaodongw/swagger/finatra/SampleApp.scala: -------------------------------------------------------------------------------- 1 | package com.github.xiaodongw.swagger.finatra 2 | 3 | import com.fasterxml.jackson.databind.PropertyNamingStrategy 4 | import com.twitter.finatra.http.HttpServer 5 | import com.twitter.finatra.http.filters.CommonFilters 6 | import com.twitter.finatra.http.routing.HttpRouter 7 | import io.swagger.models.auth.BasicAuthDefinition 8 | import io.swagger.models.{Info, Swagger} 9 | import io.swagger.util.Json 10 | 11 | object SampleSwagger extends Swagger { 12 | Json.mapper().setPropertyNamingStrategy(new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy) 13 | 14 | Resolvers.register() 15 | } 16 | 17 | object SampleApp extends HttpServer { 18 | val info = new Info() 19 | .description("The Student / Course management API, this is a sample for swagger document generation") 20 | .version("1.0.1") 21 | .title("Student / Course Management API") 22 | SampleSwagger 23 | .info(info) 24 | .addSecurityDefinition("sampleBasic", { 25 | val d = new BasicAuthDefinition() 26 | d.setType("basic") 27 | d 28 | }) 29 | 30 | 31 | override def configureHttp(router: HttpRouter) { 32 | router 33 | .filter[CommonFilters] 34 | .add[WebjarsController] 35 | .add(new SwaggerController(swagger = SampleSwagger)) 36 | .add[SampleController] 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/test/scala/com/github/xiaodongw/swagger/finatra/Models.scala: -------------------------------------------------------------------------------- 1 | package com.github.xiaodongw.swagger.finatra 2 | 3 | import com.twitter.finagle.http.Request 4 | import com.twitter.finatra.request.{QueryParam, RouteParam} 5 | import io.swagger.annotations.{ApiModel, ApiModelProperty} 6 | import javax.inject.Inject 7 | import org.joda.time.{DateTime, LocalDate} 8 | 9 | @ApiModel(value="AddressModel", description="Sample address model for documentation") 10 | case class Address(street: String, zip: String) 11 | 12 | case class Student(firstName: String, lastName: String, gender: Gender, birthday: LocalDate, grade: Int, address: Option[Address]) 13 | 14 | case class StudentWithRoute( 15 | @RouteParam 16 | @ApiModelProperty(name = "student_id", value = "Id of the student") 17 | id: String, 18 | @Inject request: Request, 19 | firstName: String, 20 | lastName: String, 21 | gender: Gender, 22 | birthday: LocalDate, 23 | grade: Int, 24 | emails: Array[String], 25 | address: Option[Address] 26 | ) 27 | 28 | case class StringWithRequest( 29 | @Inject request: Request, 30 | firstName: String 31 | ) 32 | 33 | object CourseType extends Enumeration { 34 | val LEC, LAB = Value 35 | } 36 | 37 | case class Course(time: DateTime, 38 | name: String, 39 | @ApiModelProperty(required = false, example = "[math,stem]") 40 | tags: Seq[String], 41 | @ApiModelProperty(dataType = "string", allowableValues = "LEC,LAB") 42 | typ: CourseType.Value, 43 | @ApiModelProperty(readOnly = true) 44 | capacity: Int, 45 | @ApiModelProperty(dataType = "double", required = true) 46 | cost: BigDecimal) 47 | -------------------------------------------------------------------------------- /finatra1.md: -------------------------------------------------------------------------------- 1 | # swagger-finatra 2 | Add Swagger support for Finatra web framework. 3 | 4 | Support for Finatra 1.6 is discontinued, 0.5.1 is the last version. 5 | 6 | # Getting started 7 | ## Gradle 8 | #### Add repository 9 | 10 | repositories { 11 | maven { url "https://oss.sonatype.org/content/repositories/releases/" } 12 | } 13 | 14 | #### Add Dependency 15 | 16 | ##### Scala 2.10, Finatra 1.6.0 17 | 18 | compile "com.github.xiaodongw:swagger-finatra_2.10:0.5.1" 19 | 20 | ## SBT 21 | resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/releases/" 22 | 23 | #### Add Dependency 24 | 25 | ##### Finatra 1.6.0 26 | 27 | libraryDependencies += "com.github.xiaodongw" %% "swagger-finatra" % "0.5.1" 28 | 29 | ## Add document information for you controller 30 | object SampleSwagger extends Swagger 31 | 32 | class SampleController extends Controller with SwaggerSupport { 33 | implicit protected val swagger = SampleSwagger 34 | 35 | get("/students/:id", 36 | swagger { o => 37 | o.summary("Read the detail information about the student") 38 | .tag("Student") 39 | .routeParam[String]("id", "the student id") 40 | .responseWith[Student](200, "the student details") 41 | .responseWith(404, "the student is not found") 42 | }) { request => 43 | ... 44 | } 45 | 46 | ## Add document controller 47 | 48 | ##### Finatra 1.6.0 49 | 50 | object SampleApp extends FinatraServer { 51 | val info = new Info() 52 | .description("The Student / Course management API, this is a sample for swagger document generation") 53 | .version("1.0.1") 54 | .title("Student / Course Management API") 55 | SampleSwagger.info(info) 56 | 57 | register(new SwaggerController(finatraSwagger = SampleSwagger)) 58 | ... 59 | } 60 | 61 | Swagger API document: ```http://localhost:7070/api-docs``` 62 | 63 | Swagger UI: ```http://localhost:7070/api-docs/ui``` 64 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # swagger-finatra 2 | Add Swagger support for Finatra (1.6 and 2.2.0) web framework. 3 | 4 | It requires Java 8 from version 0.6.0. 5 | 6 | # Getting started 7 | ## Gradle 8 | #### Add repository 9 | 10 | repositories { 11 | maven { url "https://oss.sonatype.org/content/repositories/releases/" } 12 | } 13 | 14 | #### Add Dependency 15 | 16 | ##### Scala 2.10, Finatra 2.2.0 17 | 18 | compile "com.github.xiaodongw:swagger-finatra_2.10:0.7.2" 19 | 20 | ##### Scala 2.11, Finatra 2.2.0 21 | 22 | compile "com.github.xiaodongw:swagger-finatra_2.11:0.7.2" 23 | 24 | ## SBT 25 | resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/releases/" 26 | 27 | #### Add Dependency 28 | 29 | ##### Finatra 2.2.0 30 | 31 | libraryDependencies += "com.github.xiaodongw" %% "swagger-finatra" % "0.7.2" 32 | 33 | ## Add document information for you controller 34 | object SampleSwagger extends Swagger 35 | 36 | class SampleController extends Controller with SwaggerSupport { 37 | implicit protected val swagger = SampleSwagger 38 | 39 | getWithDoc("/students/:id") { o => 40 | o.summary("Read the detail information about the student") 41 | .tag("Student") 42 | .routeParam[String]("id", "the student id") 43 | .responseWith[Student](200, "the student details") 44 | .responseWith(404, "the student is not found") 45 | } { request => 46 | ... 47 | } 48 | 49 | ## Add document controller 50 | 51 | ##### Finatra 2.2.0 52 | object SampleApp extends HttpServer { 53 | val info = new Info() 54 | .description("The Student / Course management API, this is a sample for swagger document generation") 55 | .version("1.0.1") 56 | .title("Student / Course Management API") 57 | SampleSwagger.info(info) 58 | 59 | override def configureHttp(router: HttpRouter) { 60 | router 61 | .add[WebjarsController] 62 | .add(new SwaggerController(swagger = SampleSwagger)) 63 | ... 64 | } 65 | } 66 | Swagger API document: ```http://localhost:8888/api-docs/model``` 67 | 68 | Swagger UI: ```http://localhost:8888/api-docs/ui``` 69 | 70 | # Finatra 1.6 71 | Previous version of Finatra (1.6) is also supported, Check [here](finatra1.md) for the guide. 72 | -------------------------------------------------------------------------------- /publish.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven' 2 | apply plugin: 'signing' 3 | 4 | group = 'com.github.xiaodongw' 5 | 6 | version = '0.7.2' 7 | 8 | if(!project.hasProperty("ossrhUsername")) { 9 | ext.ossrhUsername = "" 10 | } 11 | 12 | if(!project.hasProperty("ossrhPassword")) { 13 | ext.ossrhPassword = "" 14 | } 15 | 16 | task javadocJar(type: Jar) { 17 | classifier = 'javadoc' 18 | from javadoc 19 | } 20 | 21 | task sourcesJar(type: Jar) { 22 | classifier = 'sources' 23 | from sourceSets.main.allSource 24 | } 25 | 26 | artifacts { 27 | archives javadocJar, sourcesJar 28 | } 29 | 30 | signing { 31 | required { project.hasProperty("signing.keyId") && gradle.taskGraph.hasTask("uploadArchives") } 32 | sign configurations.archives 33 | } 34 | 35 | install { 36 | repositories.mavenInstaller { 37 | pom.version = "${version}" 38 | pom.artifactId = "swagger-finatra_${scalaVersionMain}" 39 | } 40 | } 41 | 42 | uploadArchives { 43 | repositories { 44 | mavenDeployer { 45 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 46 | 47 | repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") { 48 | authentication(userName: ossrhUsername, password: ossrhPassword) 49 | } 50 | 51 | snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") { 52 | authentication(userName: ossrhUsername, password: ossrhPassword) 53 | } 54 | 55 | pom.project { 56 | name "swagger-finatra" 57 | artifactId "swagger-finatra_${scalaVersionMain}" 58 | packaging 'jar' 59 | // optionally artifactId can be defined here 60 | description 'Add Swagger support for Finatra to generate REST API docuemnt' 61 | url 'https://github.com/xiaodongw/swagger-finatra/' 62 | 63 | scm { 64 | connection 'https://github.com/xiaodongw/swagger-finatra.git' 65 | developerConnection 'https://github.com/xiaodongw/swagger-finatra.git' 66 | url 'https://github.com/xiaodongw/swagger-finatra.git' 67 | } 68 | 69 | licenses { 70 | license { 71 | name 'The Apache License, Version 2.0' 72 | url 'http://www.apache.org/licenses/LICENSE-2.0.txt' 73 | } 74 | } 75 | 76 | developers { 77 | developer { 78 | id 'xiaodongw' 79 | name 'Xiaodong Wang' 80 | email 'xiaodongw79@gmail.com' 81 | } 82 | } 83 | } 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /src/main/scala/com/github/xiaodongw/swagger/finatra/WebjarsController.scala: -------------------------------------------------------------------------------- 1 | package com.github.xiaodongw.swagger.finatra 2 | 3 | import java.util.Date 4 | import java.util.concurrent.TimeUnit 5 | import javax.inject.Inject 6 | 7 | import com.twitter.finagle.http.Request 8 | import com.twitter.finatra.http.Controller 9 | import com.twitter.finatra.http.response.ResponseBuilder 10 | import com.twitter.finatra.http.routing.FileResolver 11 | import com.twitter.util.Duration 12 | 13 | import scala.language.postfixOps 14 | import scala.util.{Failure, Success, Try} 15 | 16 | object WebjarsController { 17 | private val DEFAULT_EXPIRE_TIME_MS: Long = 86400000L // 1 day 18 | } 19 | 20 | class WebjarsController @Inject() (resolver: FileResolver) extends Controller { 21 | import WebjarsController._ 22 | 23 | private val root: String = "/webjars" 24 | private val disableCache: Boolean = false 25 | 26 | get(s"${root}/:*") { request: Request => 27 | val resourcePath = request.getParam("*") 28 | 29 | val webjarsResourceURI: String = "/META-INF/resources/webjars/" + resourcePath 30 | //logger.log(Level.FINE, "Webjars resource requested: {0}", webjarsResourceURI) 31 | 32 | if (isDirectoryRequest(webjarsResourceURI)) { 33 | response.forbidden 34 | } else { 35 | val eTagNameTry = Try(getETagName(webjarsResourceURI)) 36 | eTagNameTry match { 37 | case Failure(e) => 38 | response.notFound 39 | case Success(eTagName) => 40 | if (!disableCache) { 41 | if (checkETagMatch(request, eTagName) || checkLastModify(request)) { 42 | response.notModified 43 | } else { 44 | val inputStream = getClass.getResourceAsStream(webjarsResourceURI) 45 | if (inputStream != null) { 46 | val resp = response.ok 47 | try { 48 | if (!disableCache) { 49 | prepareCacheHeaders(resp, eTagName) 50 | } 51 | val filename: String = getFileName(webjarsResourceURI) 52 | resp.mediaType = resolver.getContentType(filename) 53 | resp.body(inputStream) 54 | } finally { 55 | inputStream.close 56 | } 57 | } 58 | else { 59 | response.notFound 60 | } 61 | } 62 | } 63 | } 64 | } 65 | } 66 | 67 | private def isDirectoryRequest(uri: String): Boolean = { 68 | uri.endsWith("/") 69 | } 70 | 71 | private def getFileName(webjarsResourceURI: String): String = { 72 | val tokens: Array[String] = webjarsResourceURI.split("/") 73 | tokens(tokens.length - 1) 74 | } 75 | 76 | private def getETagName(webjarsResourceURI: String): String = { 77 | val tokens: Array[String] = webjarsResourceURI.split("/") 78 | if (tokens.length < 7) { 79 | throw new IllegalArgumentException("insufficient URL has given: " + webjarsResourceURI) 80 | } 81 | val version: String = tokens(5) 82 | val fileName: String = tokens(tokens.length - 1) 83 | val eTag: String = fileName + "_" + version 84 | eTag 85 | } 86 | 87 | private def checkETagMatch(request: Request, eTagName: String): Boolean = { 88 | request.headerMap.get("If-None-Match") match { 89 | case None => false 90 | case Some(token) => token == eTagName 91 | } 92 | } 93 | 94 | private def checkLastModify(request: Request): Boolean = { 95 | request.headerMap.get("If-Modified-Since").map(_.toLong) match { 96 | case None => false 97 | case Some(last) => last - System.currentTimeMillis > 0L 98 | } 99 | } 100 | 101 | private def prepareCacheHeaders(response: ResponseBuilder#EnrichedResponse, eTag: String): Unit = { 102 | response.header("ETag", eTag) 103 | response.expires = new Date(System.currentTimeMillis() + DEFAULT_EXPIRE_TIME_MS) 104 | response.lastModified = new Date(System.currentTimeMillis() + DEFAULT_EXPIRE_TIME_MS) 105 | response.cacheControl = Duration(DEFAULT_EXPIRE_TIME_MS, TimeUnit.MILLISECONDS) 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/main/scala/com/twitter/finatra/http/SwaggerRouteDSL.scala: -------------------------------------------------------------------------------- 1 | package com.twitter.finatra.http 2 | 3 | import com.github.xiaodongw.swagger.finatra.FinatraSwagger 4 | import com.twitter.finagle.http.RouteIndex 5 | import io.swagger.models.{Operation, Swagger} 6 | 7 | /** 8 | * To work around the accessibility of RouteDSL, this class is in "com.twitter.finatra.http" package 9 | */ 10 | object SwaggerRouteDSL { 11 | implicit def convertToSwaggerRouteDSL(dsl: RouteDSL)(implicit swagger: Swagger): SwaggerRouteDSL = new SwaggerRouteDSLWapper(dsl)(swagger) 12 | } 13 | 14 | trait SwaggerRouteDSL { 15 | implicit protected val swagger: Swagger 16 | protected val dsl: RouteDSL 17 | 18 | def postWithDoc[RequestType: Manifest, ResponseType: Manifest](route: String, name: String = "", admin: Boolean = false, routeIndex: Option[RouteIndex] = None) 19 | (doc: Operation => Unit) 20 | (callback: RequestType => ResponseType): Unit = { 21 | registerOperation(route, "post")(doc) 22 | dsl.post(route, name, admin, routeIndex)(callback) 23 | } 24 | 25 | def getWithDoc[RequestType: Manifest, ResponseType: Manifest](route: String, name: String = "", admin: Boolean = false, routeIndex: Option[RouteIndex] = None) 26 | (doc: Operation => Unit) 27 | (callback: RequestType => ResponseType): Unit = { 28 | registerOperation(route, "get")(doc) 29 | dsl.get(route, name, admin, routeIndex)(callback) 30 | } 31 | 32 | def putWithDoc[RequestType: Manifest, ResponseType: Manifest](route: String, name: String = "", admin: Boolean = false, routeIndex: Option[RouteIndex] = None) 33 | (doc: Operation => Unit) 34 | (callback: RequestType => ResponseType): Unit = { 35 | registerOperation(route, "put")(doc) 36 | dsl.put(route, name, admin, routeIndex)(callback) 37 | } 38 | 39 | def patchWithDoc[RequestType: Manifest, ResponseType: Manifest](route: String, name: String = "", admin: Boolean = false, routeIndex: Option[RouteIndex] = None) 40 | (doc: Operation => Unit) 41 | (callback: RequestType => ResponseType): Unit = { 42 | registerOperation(route, "patch")(doc) 43 | dsl.patch(route, name, admin, routeIndex)(callback) 44 | } 45 | 46 | def headWithDoc[RequestType: Manifest, ResponseType: Manifest](route: String, name: String = "", admin: Boolean = false, routeIndex: Option[RouteIndex] = None) 47 | (doc: Operation => Unit) 48 | (callback: RequestType => ResponseType): Unit = { 49 | registerOperation(route, "head")(doc) 50 | dsl.head(route, name, admin, routeIndex)(callback) 51 | } 52 | 53 | def deleteWithDoc[RequestType: Manifest, ResponseType: Manifest](route: String, name: String = "", admin: Boolean = false, routeIndex: Option[RouteIndex] = None) 54 | (doc: Operation => Unit) 55 | (callback: RequestType => ResponseType): Unit = { 56 | registerOperation(route, "delete")(doc) 57 | dsl.delete(route, name, admin, routeIndex)(callback) 58 | } 59 | 60 | def optionsWithDoc[RequestType: Manifest, ResponseType: Manifest](route: String, name: String = "", admin: Boolean = false, routeIndex: Option[RouteIndex] = None) 61 | (doc: Operation => Unit) 62 | (callback: RequestType => ResponseType): Unit = { 63 | registerOperation(route, "options")(doc) 64 | dsl.options(route, name, admin, routeIndex)(callback) 65 | } 66 | 67 | private def registerOperation(path: String, method: String)(doc: Operation => Unit): Unit = { 68 | val op = new Operation 69 | doc(op) 70 | 71 | FinatraSwagger.convertToFinatraSwagger(swagger).registerOperation(path, method, op) 72 | } 73 | } 74 | 75 | private class SwaggerRouteDSLWapper(protected val dsl: RouteDSL)(implicit protected val swagger: Swagger) extends SwaggerRouteDSL 76 | -------------------------------------------------------------------------------- /src/main/scala/com/github/xiaodongw/swagger/finatra/FinatraOperation.scala: -------------------------------------------------------------------------------- 1 | package com.github.xiaodongw.swagger.finatra 2 | 3 | import io.swagger.models.parameters._ 4 | import io.swagger.models.properties.{ArrayProperty, RefProperty} 5 | import io.swagger.models._ 6 | import io.swagger.util.Json 7 | import scala.collection.JavaConverters._ 8 | import scala.reflect.runtime.universe._ 9 | 10 | object FinatraOperation { 11 | implicit def convertToFinatraOperation(operation: Operation): FinatraOperation = new FinatraOperation(operation) 12 | } 13 | 14 | class FinatraOperation(operation: Operation) { 15 | import FinatraSwagger._ 16 | 17 | def routeParam[T: TypeTag](name: String, description: String = "", required: Boolean = true) 18 | (implicit swagger: Swagger): Operation = { 19 | val param = new PathParameter() 20 | .name(name) 21 | .description(description) 22 | .required(required) 23 | .property(swagger.registerModel[T]) 24 | 25 | operation.parameter(param) 26 | 27 | operation 28 | } 29 | 30 | def request[T <: Product : TypeTag](implicit swagger: Swagger): Operation = { 31 | swagger.register[T].foreach(operation.parameter) 32 | 33 | operation 34 | } 35 | 36 | def queryParam[T: TypeTag](name: String, description: String = "", required: Boolean = true) 37 | (implicit swagger: Swagger): Operation = { 38 | val param = new QueryParameter() 39 | .name(name) 40 | .description(description) 41 | .required(required) 42 | .property(swagger.registerModel[T]) 43 | 44 | operation.parameter(param) 45 | 46 | operation 47 | } 48 | 49 | def headerParam[T: TypeTag](name: String, description: String = "", required: Boolean = true) 50 | (implicit swagger: Swagger): Operation = { 51 | val param = new HeaderParameter() 52 | .name(name) 53 | .description(description) 54 | .required(required) 55 | .property(swagger.registerModel[T]) 56 | 57 | operation.parameter(param) 58 | 59 | operation 60 | } 61 | 62 | def formParam[T: TypeTag](name: String, description: String = "", required: Boolean = true) 63 | (implicit swagger: Swagger): Operation = { 64 | val param = new FormParameter() 65 | .name(name) 66 | .description(description) 67 | .required(required) 68 | .property(swagger.registerModel[T]) 69 | 70 | operation.parameter(param) 71 | 72 | operation 73 | } 74 | 75 | def cookieParam[T: TypeTag](name: String, description: String = "", required: Boolean = true) 76 | (implicit swagger: Swagger): Operation = { 77 | val param = new CookieParameter() 78 | .name(name) 79 | .description(description) 80 | .required(required) 81 | .property(swagger.registerModel[T]) 82 | 83 | operation.parameter(param) 84 | 85 | operation 86 | } 87 | 88 | def bodyParam[T: TypeTag](name: String, description: String = "", example: Option[T] = None) 89 | (implicit swagger: Swagger): Operation = { 90 | val schema = swagger.registerModel[T] 91 | 92 | val model = SchemaUtil.toModel(schema) 93 | 94 | //todo not working 95 | example.foreach { e => 96 | if(model != null) { 97 | model.setExample(Json.mapper.writeValueAsString(e)) 98 | } 99 | } 100 | 101 | val param = new BodyParameter() 102 | .name(name) 103 | .description(description) 104 | .schema(model) 105 | 106 | operation.parameter(param) 107 | 108 | operation 109 | } 110 | 111 | def responseWith[T: TypeTag](status: Int, description: String = "", example: Option[T] = None) 112 | (implicit finatraSwagger: Swagger): Operation = { 113 | val ref = finatraSwagger.registerModel[T] 114 | 115 | //todo not working, sample is not in the generated api, waiting for swagger fix 116 | example.foreach { e => 117 | if(ref != null) { 118 | val example = Json.mapper.writeValueAsString(e) 119 | 120 | ref.setExample(example) 121 | //val model = api.swagger.getDefinitions.get(ref.asInstanceOf[RefProperty].getSimpleRef) 122 | //model.setExample(example) 123 | } 124 | } 125 | 126 | val param = new Response() 127 | .description(description) 128 | .schema(ref) 129 | 130 | operation.response(status, param) 131 | 132 | operation 133 | } 134 | 135 | def addSecurity(name: String, scopes: List[String]): Operation = { 136 | operation.addSecurity(name, scopes.asJava) 137 | 138 | operation 139 | } 140 | 141 | def tags(tags: List[String]): Operation = { 142 | operation.setTags(tags.asJava) 143 | operation 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /src/test/scala/com/github/xiaodongw/swagger/finatra/SampleController.scala: -------------------------------------------------------------------------------- 1 | package com.github.xiaodongw.swagger.finatra 2 | 3 | import java.util.Date 4 | 5 | import com.twitter.finagle.http.{Request, Response} 6 | import com.twitter.finagle.{Service, SimpleFilter} 7 | import com.twitter.finatra.http.Controller 8 | import com.twitter.util.Future 9 | import org.joda.time.{DateTime, LocalDate} 10 | 11 | class SampleFilter extends SimpleFilter[Request, Response] { 12 | override def apply(request: Request, service: Service[Request, Response]): Future[Response] = { 13 | service(request) 14 | } 15 | } 16 | 17 | class SampleController extends Controller with SwaggerSupport { 18 | override implicit protected val swagger = SampleSwagger 19 | 20 | case class HelloResponse(text: String, time: Date) 21 | 22 | getWithDoc("/students/:id") { o => 23 | o.summary("Read student information") 24 | .description("Read the detail information about the student.") 25 | .tag("Student") 26 | .routeParam[String]("id", "the student id") 27 | .produces("application/json") 28 | .responseWith[Student](200, "the student object", 29 | example = Some(Student("Tom", "Wang", Gender.Male, new LocalDate(), 4, Some(Address("California Street", "94111"))))) 30 | .responseWith[Unit](404, "the student is not found") 31 | } { request: Request => 32 | val id = request.getParam("id") 33 | 34 | response.ok.json(Student("Alice", "Wang", Gender.Female, new LocalDate(), 4, Some(Address("California Street", "94111")))).toFuture 35 | } 36 | 37 | postWithDoc("/students/:id") { o => 38 | o.summary("Sample request with route") 39 | .description("Read the detail information about the student.") 40 | .tag("Student") 41 | .request[StudentWithRoute] 42 | } { request: StudentWithRoute => 43 | val id = request.id 44 | 45 | response.ok.json(Student("Alice", "Wang", Gender.Female, new LocalDate(), 4, Some(Address("California Street", "94111")))).toFuture 46 | } 47 | 48 | postWithDoc("/students/test/:id") { o => 49 | o.summary("Sample request with route2") 50 | .description("Read the detail information about the student.") 51 | .tag("Student") 52 | .request[StudentWithRoute] 53 | } { request: StudentWithRoute => 54 | val id = request.id 55 | 56 | response.ok.json(Student("Alice", "Wang", Gender.Female, new LocalDate(), 4, Some(Address("California Street", "94111")))).toFuture 57 | } 58 | 59 | postWithDoc("/students/firstName") { 60 | _.request[StringWithRequest] 61 | .tag("Student") 62 | } { request: StringWithRequest => 63 | request.firstName 64 | } 65 | 66 | postWithDoc("/students") { o => 67 | o.summary("Create a new student") 68 | .tag("Student") 69 | .bodyParam[Student]("student", "the student details") 70 | .responseWith[Unit](200, "the student is created") 71 | .responseWith[Unit](500, "internal error") 72 | } { student: Student => 73 | //val student = request.contentString 74 | response.ok.json(student).toFuture 75 | } 76 | 77 | postWithDoc("/students/bulk") { o => 78 | o.summary("Create a list of students") 79 | .tag("Student") 80 | .bodyParam[Array[Student]]("students", "the list of students") 81 | .responseWith[Unit](200, "the students are created") 82 | .responseWith[Unit](500, "internal error") 83 | } { students: List[Student] => 84 | response.ok.json(students).toFuture 85 | } 86 | 87 | putWithDoc("/students/:id") { o => 88 | o.summary("Update the student") 89 | .tag("Student") 90 | .formParam[String]("name", "the student name") 91 | .formParam[Int]("grade", "the student grade") 92 | .routeParam[String]("id", "student ID") 93 | .cookieParam[String]("who", "who make the update") 94 | .headerParam[String]("token", "the token") 95 | .responseWith[Unit](200, "the student is updated") 96 | .responseWith[Unit](404, "the student is not found") 97 | } { request: Request => 98 | val id = request.getParam("id") 99 | val name = request.getParam("name") 100 | val grade = request.getIntParam("grade") 101 | val who = request.cookies.getOrElse("who", "Sam") //todo swagger-ui not set the cookie? 102 | val token = request.headerMap("token") 103 | 104 | response.ok.toFuture 105 | } 106 | 107 | getWithDoc("/students") { o => 108 | o.summary("Get a list of students") 109 | .tag("Student") 110 | .responseWith[Array[String]](200, "the student ids") 111 | .responseWith[Unit](500, "internal error") 112 | .addSecurity("sampleBasic", List()) 113 | } { request: Request => 114 | response.ok.json(Array("student1", "student2")).toFuture 115 | } 116 | 117 | getWithDoc("/courses") { o => 118 | o.summary("Get a list of courses") 119 | .tag("Course") 120 | .responseWith[Array[String]](200, "the courses ids") 121 | .responseWith[Unit](500, "internal error") 122 | } { request: Request => 123 | response.ok.json(Array("course1", "course2")).toFuture 124 | } 125 | 126 | getWithDoc("/courses/:id") { o => 127 | o.summary("Get the detail of a course") 128 | .tag("Course") 129 | .routeParam[String]("id", "the course id") 130 | .responseWith[Course](200, "the courses detail") 131 | .responseWith[Unit](500, "internal error") 132 | } { request: Request => 133 | response.ok.json(Course(new DateTime(), "calculation", Seq("math"), CourseType.LAB, 20, BigDecimal(300.54))).toFuture 134 | } 135 | 136 | filter[SampleFilter].getWithDoc("/courses/:courseId/student/:studentId") { o => 137 | o.summary("Is the student in this course") 138 | .tags(List("Course", "Student")) 139 | .routeParam[String]("courseId", "the course id") 140 | .routeParam[String]("studentId", "the student id") 141 | .responseWith[Boolean](200, "true / false") 142 | .responseWith[Unit](500, "internal error") 143 | .deprecated(true) 144 | } { request: Request => 145 | response.ok.json(true).toFuture 146 | } 147 | 148 | 149 | } 150 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /src/main/scala/com/github/xiaodongw/swagger/finatra/FinatraSwagger.scala: -------------------------------------------------------------------------------- 1 | package com.github.xiaodongw.swagger.finatra 2 | 3 | import com.fasterxml.jackson.databind.{JavaType, ObjectMapper} 4 | import com.google.inject.{Inject => GInject} 5 | import com.twitter.finagle.http.Request 6 | import com.twitter.finatra.request.{FormParam, QueryParam, RouteParam, Header => HeaderParam} 7 | import io.swagger.converter.{ModelConverter, ModelConverterContext, ModelConverters} 8 | import io.swagger.jackson.ModelResolver 9 | import io.swagger.models._ 10 | import io.swagger.models.parameters._ 11 | import io.swagger.models.properties.{Property, RefProperty} 12 | import io.swagger.util.Json 13 | import java.lang.annotation.Annotation 14 | import java.lang.reflect.ParameterizedType 15 | import java.util 16 | import javax.inject.{Inject => JInject} 17 | import io.swagger.annotations.ApiModelProperty 18 | import net.bytebuddy.ByteBuddy 19 | import net.bytebuddy.description.`type`.TypeDescription 20 | import net.bytebuddy.description.modifier.Visibility 21 | import scala.collection.JavaConverters._ 22 | import scala.collection.mutable 23 | import scala.reflect.runtime._ 24 | import scala.reflect.runtime.universe._ 25 | 26 | object FinatraSwagger { 27 | private val finatraRouteParamter = ":(\\w+)".r 28 | 29 | /** 30 | * Cache of dynamically generated class bodies keyed by qualified names 31 | */ 32 | private val dynamicClassBodies: mutable.HashMap[String, Class[_]] = new mutable.HashMap[String, Class[_]]() 33 | 34 | implicit def convertToFinatraSwagger(swagger: Swagger): FinatraSwagger = new FinatraSwagger(swagger) 35 | } 36 | 37 | sealed trait ModelParam { 38 | val name: String 39 | val description: String 40 | val required: Boolean 41 | val typ: Class[_] 42 | } 43 | 44 | sealed trait FinatraRequestParam 45 | case class RouteRequestParam(name: String, typ: Class[_], description: String = "", required: Boolean = true) extends FinatraRequestParam with ModelParam 46 | case class QueryRequestParam(name: String, typ: Class[_], description: String = "", required: Boolean = true) extends FinatraRequestParam with ModelParam 47 | case class BodyRequestParam(description: String = "", name: String, typ: Class[_], innerOptionType: Option[java.lang.reflect.Type] = None) extends FinatraRequestParam 48 | case class RequestInjectRequestParam(name: String) extends FinatraRequestParam 49 | case class HeaderRequestParam(name: String, required: Boolean = true, description: String = "", typ: Class[_]) extends FinatraRequestParam with ModelParam 50 | case class FormRequestParam(name: String, description: String = "", required: Boolean = true, typ: Class[_]) extends FinatraRequestParam with ModelParam 51 | 52 | object Resolvers { 53 | class ScalaOptionResolver(objectMapper: ObjectMapper) extends ModelResolver(objectMapper) { 54 | override def resolveProperty( 55 | propType: JavaType, 56 | context: ModelConverterContext, 57 | annotations: Array[Annotation], 58 | next: util.Iterator[ModelConverter]): Property = { 59 | if (propType.getRawClass == classOf[Option[_]]) { 60 | try { 61 | return super.resolveProperty(propType.containedType(0), context, annotations, next) 62 | } catch { 63 | case _: Exception => 64 | } 65 | } 66 | 67 | super.resolveProperty(propType, context, annotations, next) 68 | } 69 | } 70 | 71 | def register(objectMapper: ObjectMapper = Json.mapper): Unit = { 72 | ModelConverters.getInstance().addConverter(new ScalaOptionResolver(objectMapper)) 73 | } 74 | } 75 | 76 | class FinatraSwagger(swagger: Swagger) { 77 | 78 | import FinatraSwagger._ 79 | 80 | /** 81 | * Register a request object that contains body information/route information/etc 82 | * 83 | * @tparam T 84 | * @return 85 | */ 86 | def register[T: TypeTag]: List[Parameter] = { 87 | val properties = getFinatraProps[T] 88 | 89 | val className = currentMirror.runtimeClass(typeOf[T]).getName 90 | 91 | val swaggerProps = 92 | properties.collect { 93 | case x: ModelParam => x 94 | }.map { 95 | case param @ (x: RouteRequestParam) => 96 | new PathParameter(). 97 | name(param.name). 98 | description(param.description). 99 | required(param.required). 100 | property(registerModel(param.typ)) 101 | case param @ (x: QueryRequestParam) => 102 | new QueryParameter(). 103 | name(param.name). 104 | description(param.description). 105 | required(param.required). 106 | property(registerModel(param.typ)) 107 | case param @ (x: HeaderRequestParam) => 108 | new HeaderParameter(). 109 | name(param.name). 110 | description(param.description). 111 | required(param.required). 112 | property(registerModel(param.typ)) 113 | case param @ (x: FormRequestParam) => 114 | new FormParameter(). 115 | name(param.name). 116 | description(param.description). 117 | required(param.required). 118 | property(registerModel(param.typ)) 119 | } 120 | 121 | val bodyElements = properties.collect { case b: BodyRequestParam => b } 122 | 123 | swaggerProps ++ List(registerDynamicBody(bodyElements, className)).flatten 124 | } 125 | 126 | /** 127 | * Given the request object format its finatra parameters via reflection 128 | * 129 | * @tparam T 130 | * @return 131 | */ 132 | private def getFinatraProps[T: TypeTag]: List[FinatraRequestParam] = { 133 | val clazz = currentMirror.runtimeClass(typeOf[T]) 134 | 135 | val fields = clazz.getDeclaredFields 136 | 137 | val constructorArgWithField = 138 | clazz. 139 | getConstructors. 140 | head.getParameters. 141 | map(m => (clazz: Class[_ <: Annotation]) => { 142 | val annotation = m.getAnnotationsByType(clazz) 143 | 144 | if (annotation.isEmpty) { 145 | None 146 | } else { 147 | Some(annotation) 148 | } 149 | }). 150 | zip(fields) 151 | 152 | val ast: List[Option[FinatraRequestParam]] = 153 | constructorArgWithField.map { case (annotationExtractor, field) => 154 | val routeParam = annotationExtractor(classOf[RouteParam]) 155 | val queryParam = annotationExtractor(classOf[QueryParam]) 156 | val injectJavax = annotationExtractor(classOf[JInject]) 157 | val injectGuice = annotationExtractor(classOf[GInject]) 158 | val header = annotationExtractor(classOf[HeaderParam]) 159 | val form = annotationExtractor(classOf[FormParam]) 160 | val modelPropertyAnnotations = annotationExtractor(classOf[ApiModelProperty]) 161 | 162 | val (isRequired, innerOptionType) = field.getGenericType match { 163 | case parameterizedType: ParameterizedType => 164 | 165 | val required = parameterizedType.getRawType.asInstanceOf[Class[_]] == classOf[Option[_]] 166 | 167 | (required, Some(parameterizedType.getActualTypeArguments.apply(0))) 168 | case _ => 169 | (true, None) 170 | } 171 | 172 | val modelProp = modelPropertyAnnotations.flatMap(_.headOption).map(_.asInstanceOf[ApiModelProperty]) 173 | 174 | val (name, description) = modelProp match { 175 | case Some(p) => 176 | val n = if(!p.name().isEmpty) p.name() else field.getName 177 | (n, p.value()) 178 | case None => 179 | (field.getName, "") 180 | } 181 | 182 | if (routeParam.isDefined) { 183 | Some(RouteRequestParam(name, description = description, typ = field.getType)) 184 | } 185 | else if (queryParam.isDefined) { 186 | Some(QueryRequestParam(name, description = description, typ = field.getType, required = isRequired)) 187 | } 188 | else if ((injectJavax.isDefined || injectGuice.isDefined) && field.getType.isAssignableFrom(classOf[Request])) { 189 | Some(RequestInjectRequestParam(name)) 190 | } 191 | else if (header.isDefined) { 192 | Some(HeaderRequestParam(name, description = description, typ = field.getType, required = isRequired)) 193 | } 194 | else if (form.isDefined) { 195 | Some(FormRequestParam(name, description = description, typ = field.getType, required = isRequired)) 196 | } 197 | else { 198 | Some(BodyRequestParam(name = name, description = description, typ = field.getType, innerOptionType = innerOptionType)) 199 | } 200 | }.toList 201 | 202 | ast.flatten 203 | } 204 | 205 | private def emitBodyClassForElements(bodyElements: List[BodyRequestParam], className: String): Class[_] = { 206 | val byteBuddy = new ByteBuddy() 207 | 208 | // add "Body" to avoid name collisions 209 | val bodyEmittedClass = byteBuddy.subclass(classOf[Object]).name(className) 210 | 211 | val bodyFields = bodyElements.foldLeft(bodyEmittedClass) { (asm, body) => 212 | // if we have an inner option type, unwrap the option 213 | // and pass it to the class builder so we can get proper 214 | // definitions of the inner type in the swagger model 215 | val bodyType = body.innerOptionType.getOrElse(body.typ).asInstanceOf[Class[_]] 216 | 217 | asm.defineField(body.name, new TypeDescription.Generic.OfNonGenericType.ForLoadedType(bodyType), Visibility.PUBLIC) 218 | } 219 | 220 | bodyFields.make().load(getClass.getClassLoader).getLoaded 221 | } 222 | 223 | /** 224 | * Creates a fake object for swagger to reflect upon 225 | * 226 | * @param bodyElements 227 | * @param name 228 | * @return 229 | */ 230 | private def registerDynamicBody(bodyElements: List[BodyRequestParam], name: String): Option[Parameter] = { 231 | if (bodyElements.isEmpty) { 232 | return None 233 | } 234 | 235 | val className = name + "Body" 236 | 237 | val bodyClass = dynamicClassBodies.getOrElse(className, emitBodyClassForElements(bodyElements, className)) 238 | 239 | dynamicClassBodies.put(className, bodyClass) 240 | 241 | val schema = registerModel(bodyClass, Some(name)) 242 | 243 | val model = SchemaUtil.toModel(schema) 244 | 245 | Some( 246 | new BodyParameter().name("body").schema(model) 247 | ) 248 | } 249 | 250 | def registerModel[T: TypeTag]: Property = { 251 | val paramType: Type = typeOf[T] 252 | if (paramType =:= TypeTag.Nothing.tpe) { 253 | null 254 | } else { 255 | val typeClass = currentMirror.runtimeClass(paramType) 256 | 257 | registerModel(typeClass) 258 | } 259 | } 260 | 261 | private def registerModel(typeClass: Class[_], name: Option[String] = None) = { 262 | val modelConverters = ModelConverters.getInstance() 263 | val models = modelConverters.readAll(typeClass) 264 | for (entry <- models.entrySet().asScala) { 265 | swagger.addDefinition(entry.getKey, entry.getValue) 266 | } 267 | val schema = modelConverters.readAsProperty(typeClass) 268 | 269 | schema 270 | } 271 | 272 | def convertPath(path: String): String = { 273 | FinatraSwagger.finatraRouteParamter.replaceAllIn(path, "{$1}") 274 | } 275 | 276 | def registerOperation(path: String, method: String, operation: Operation): Swagger = { 277 | val swaggerPath = convertPath(path) 278 | 279 | var spath = swagger.getPath(swaggerPath) 280 | if (spath == null) { 281 | spath = new Path() 282 | swagger.path(swaggerPath, spath) 283 | } 284 | 285 | spath.set(method, operation) 286 | 287 | swagger 288 | } 289 | } 290 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------