diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java index 7ecf25fba71..aeb3e8b542b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java @@ -1,13 +1,8 @@ package io.swagger.codegen.languages; -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; +import com.google.common.base.Strings; +import io.swagger.codegen.*; +import io.swagger.models.Model; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; @@ -93,17 +88,16 @@ public FinchServerCodegen() { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } else { additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); - }; + } supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); - //supportingFiles.add(new SupportingFile("web.xml", "/src/main/webapp/WEB-INF", "web.xml")); - //supportingFiles.add(new SupportingFile("JettyMain.mustache", sourceFolder, "JettyMain.scala")); - //supportingFiles.add(new SupportingFile("Bootstrap.mustache", sourceFolder, "FinchBootstrap.scala")); - //supportingFiles.add(new SupportingFile("ServletApp.mustache", sourceFolder, "ServletApp.scala")); - //supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties")); - //supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt")); - //supportingFiles.add(new SupportingFile("sbt", "", "sbt")); + supportingFiles.add(new SupportingFile("Server.mustache", sourceFolder, "Server.scala")); + supportingFiles.add(new SupportingFile("DataAccessor.mustache", sourceFolder, "DataAccessor.scala")); + + supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties")); + supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt")); + supportingFiles.add(new SupportingFile("sbt", "", "sbt")); supportingFiles.add(new SupportingFile("endpoint.mustache", sourceFolder, "endpoint.scala")); supportingFiles.add(new SupportingFile("errors.mustache", sourceFolder, "errors.scala")); @@ -174,6 +168,23 @@ public String modelFileFolder() { return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); } + /** + * Convert Swagger Model object to Codegen Model object + * + * @param name the name of the model + * @param model Swagger Model object + * @param allDefinitions a map of all Swagger models from the spec + * @return Codegen Model object + */ + @Override + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); + + codegenModel.vendorExtensions.put("x-varcount", codegenModel.vars.size()); + + return codegenModel; + } + @Override public Map postProcessOperations(Map objs) { Map operations = (Map) objs.get("operations"); diff --git a/modules/swagger-codegen/src/main/resources/finch/Bootstrap.mustache b/modules/swagger-codegen/src/main/resources/finch/Bootstrap.mustache deleted file mode 100644 index 483ee4e5444..00000000000 --- a/modules/swagger-codegen/src/main/resources/finch/Bootstrap.mustache +++ /dev/null @@ -1,22 +0,0 @@ -{{>licenseInfo}} - -import {{apiPackage}}._ -import akka.actor.ActorSystem -import io.swagger.app.{ResourcesApp, SwaggerApp} -import javax.servlet.ServletContext -import org.scalatra.LifeCycle - -class ScalatraBootstrap extends LifeCycle { - implicit val swagger = new SwaggerApp - - override def init(context: ServletContext) { - implicit val system = ActorSystem("appActorSystem") - try { - {{#apiInfo}}{{#apis}}context mount (new {{classname}}, "{{basePathWithoutHost}}/{{baseName}}/*") - {{/apis}}{{/apiInfo}} - context mount (new ResourcesApp, "/api-docs/*") - } catch { - case e: Throwable => e.printStackTrace() - } - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/DataAccessor.mustache b/modules/swagger-codegen/src/main/resources/finch/DataAccessor.mustache new file mode 100644 index 00000000000..43088f7b6ca --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/DataAccessor.mustache @@ -0,0 +1,21 @@ +package {{packageName}} + +trait DataAccessor { + // TODO: apiInfo -> apis -> operations = ??? + // NOTE: ??? throws a not implemented exception + +{{#apiInfo}} + {{#apis}} +{{#operations}} + {{#operation}} + /** + * {{{description}}} + * @return A {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} + */ + def {{baseName}}_{{operationId}}({{#allParams}}{{paramName}}: {{{dataType}}}{{^-last}}, {{/-last}}{{/allParams}}): {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} = ??? + + {{/operation}} +{{/operations}} + {{/apis}} +{{/apiInfo}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/JettyMain.mustache b/modules/swagger-codegen/src/main/resources/finch/JettyMain.mustache deleted file mode 100644 index 1eedae148b3..00000000000 --- a/modules/swagger-codegen/src/main/resources/finch/JettyMain.mustache +++ /dev/null @@ -1,45 +0,0 @@ -{{>licenseInfo}} - -import org.eclipse.jetty.server._ -import org.eclipse.jetty.webapp.WebAppContext -import org.scalatra.servlet.ScalatraListener - -object JettyMain { - - object conf { - val port = sys.env.get("PORT") map (_.toInt) getOrElse (8080) - val stopTimeout = sys.env.get("STOP_TIMEOUT") map (_.toInt) getOrElse (5000) - val connectorIdleTimeout = sys.env.get("CONNECTOR_IDLE_TIMEOUT") map (_.toInt) getOrElse (90000) - val webapp = sys.env.get("PUBLIC") getOrElse "webapp" - val contextPath = sys.env.get("CONTEXT_PATH") getOrElse "/" - } - - def main(args: Array[String]) = { - val server: Server = new Server - println("starting jetty") - - server setStopTimeout conf.stopTimeout - //server setDumpAfterStart true - server setStopAtShutdown true - - val httpConfig = new HttpConfiguration() - httpConfig setSendDateHeader true - httpConfig setSendServerVersion false - - val connector = new NetworkTrafficServerConnector(server, new HttpConnectionFactory(httpConfig)) - connector setPort conf.port - connector setSoLingerTime 0 - connector setIdleTimeout conf.connectorIdleTimeout - server addConnector connector - - val webapp = conf.webapp - val webApp = new WebAppContext - webApp setContextPath conf.contextPath - webApp setResourceBase conf.webapp - webApp setEventListeners Array(new ScalatraListener) - - server setHandler webApp - - server.start() - } -} diff --git a/modules/swagger-codegen/src/main/resources/finch/Server.mustache b/modules/swagger-codegen/src/main/resources/finch/Server.mustache new file mode 100644 index 00000000000..3cbb357403c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/Server.mustache @@ -0,0 +1,33 @@ +package {{packageName}} + +import com.twitter.finagle.Http +import com.twitter.finagle.util.LoadService +import com.twitter.util.{Await, Future} + +{{#imports}}import {{import}} +{{/imports}} + +class Server { + // Loads implementation defined in resources/META-INF/services/{{packageName}}.DataAccessor + val db = LoadService[DataAccessor]() match { + case accessor :: _ => accessor + case _ => new DataAccessor { } + } + + val service = endpoint.makeService(db) + + val server = Http.serve(":8080", service) //creates service + + Await.ready(server) + + def close(): Future[Unit] = { + Await.ready(server.close()) + } +} + +/** + * Launches the PetstoreAPI service when the system is ready. + */ +object Server extends Server with App { + Await.ready(server) +} diff --git a/modules/swagger-codegen/src/main/resources/finch/ServletApp.mustache b/modules/swagger-codegen/src/main/resources/finch/ServletApp.mustache deleted file mode 100644 index faeeb5fcb7a..00000000000 --- a/modules/swagger-codegen/src/main/resources/finch/ServletApp.mustache +++ /dev/null @@ -1,41 +0,0 @@ -{{>licenseInfo}} - -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.ScalatraServlet -import org.json4s.{DefaultFormats, Formats} - -class ResourcesApp(implicit protected val system: ActorSystem, val swagger: SwaggerApp) - 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) - } -} - -class SwaggerApp extends Swagger(apiInfo = ApiSwagger.apiInfo, apiVersion = "1.0", swaggerVersion = "1.2") - -object ApiSwagger { - val apiInfo = ApiInfo( - """{{{appName}}}""", - """{{{appDescription}}}""", - """{{{infoUrl}}}""", - """{{{infoEmail}}}""", - """{{{licenseInfo}}}""", - """{{{licenseUrl}}}""") -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/api.mustache b/modules/swagger-codegen/src/main/resources/finch/api.mustache index e554ea2346f..6d76a59ee96 100644 --- a/modules/swagger-codegen/src/main/resources/finch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/finch/api.mustache @@ -1,53 +1,46 @@ -{{>licenseInfo}} - package {{packageName}} {{#imports}}//import {{import}} {{/imports}} -//import java.io.File - -import org.scalatra.{ TypedParamSupport, ScalatraServlet } -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 scala.collection.JavaConverters._ - -class {{classname}} (implicit val swagger: Swagger) extends ScalatraServlet - with FileUploadSupport - with JacksonJsonSupport - with SwaggerSupport { - protected implicit val jsonFormats: Formats = DefaultFormats - - protected val applicationDescription: String = "{{classname}}" - override protected val applicationName: Option[String] = Some("{{basePathWithoutHost}}/{{baseName}}") - - before() { - contentType = formats("json") - response.headers += ("Access-Control-Allow-Origin" -> "*") - } -{{#operations}} -{{#operation}} - {{newline}} - - val {{nickname}}Operation = (apiOperation[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]("{{nickname}}") - summary "{{{summary}}}" - parameters({{#allParams}}{{>queryParam}}{{>pathParam}}{{>bodyParam}}{{>formParam}}{{>headerParam}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) - ) - - {{httpMethod}}("{{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}} - println("{{paramName}}: " + {{paramName}}) - {{/allParams}} - } -{{/operation}} -{{/operations}} +import _root_.argonaut._, Argonaut._ +import com.twitter.finagle.Service +import com.twitter.finagle.http.{Request, Response} +import com.twitter.finagle.http.exp.Multipart.FileUpload +import com.twitter.util.Future +import argonaut.Argonaut._ +import io.finch._, items._ +import io.finch.argonaut._ +import java.io.File + +object {{classname}} { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + public def endpoints(da: DataAccessor) = + {{#operations}} + {{#operation}} + {{{operationId}}}(da){{^-last}} :+:{{/-last}} + {{/operation}} + {{/operations}} + + {{#operations}} + {{#operation}} + /** + * {{{description}}} + * @return And endpoint representing a {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} + */ + private def {{operationId}}(da: DataAccessor): Endpoint[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}] = + post( {{{vendorExtensions.x-scala-path}}} {{#allParams}}{{^isPathParam}}{{{dataType}}}{{^-last}} ? {{/-last}}{{/isPathParam}}{{/allParams}}) { {{#hasParams}}({{#allParams}}{{paramName}}: {{{dataType}}}{{^-last}}, {{/-last}}{{/allParams}}) => {{/hasParams}} + {{#returnType}} + Ok(da.{{baseName}}_{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}})) + {{/returnType}} + {{^returnType}} + NoContent(da.{{baseName}}_{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}})) + {{/returnType}} + } + + {{/operation}} + {{/operations}} } diff --git a/modules/swagger-codegen/src/main/resources/finch/build.sbt b/modules/swagger-codegen/src/main/resources/finch/build.sbt index 00575312d85..016f1ef3218 100644 --- a/modules/swagger-codegen/src/main/resources/finch/build.sbt +++ b/modules/swagger-codegen/src/main/resources/finch/build.sbt @@ -1,46 +1,16 @@ -import AssemblyKeys._ // put this at the top of the file - -import NativePackagerKeys._ - -packageArchetype.java_server - -assemblySettings - scalariformSettings organization := "io.swagger" -seq(webSettings :_*) - -mainClass in assembly := Some("JettyMain") - -name := "scalatra-sample" +name := "finch-sample" version := "0.1.0-SNAPSHOT" -scalaVersion := "2.11.2" +scalaVersion := "2.11.8" -scalacOptions += "-language:postfixOps" +resolvers += Resolver.sonatypeRepo("snapshots") -libraryDependencies ++= Seq( - "org.scalatest" %% "scalatest" % "2.2.1" % "test", - "org.scalatra" %% "scalatra" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-json" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3", - "org.json4s" %% "json4s-jackson" % "3.2.10", - "org.json4s" %% "json4s-ext" % "3.2.10", - "commons-codec" % "commons-codec" % "1.7", - "net.databinder.dispatch" %% "dispatch-core" % "0.11.2", - //"net.databinder.dispatch" %% "json4s-jackson" % "0.11.2", - "net.databinder.dispatch" %% "dispatch-json4s-jackson" % "0.11.2", - "com.typesafe.akka" %% "akka-actor" % "2.3.6", - "org.eclipse.jetty" % "jetty-server" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty" % "jetty-webapp" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar")) -) +resolvers += "TM" at "http://maven.twttr.com" resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository" @@ -48,17 +18,25 @@ resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/reposi resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/" -ivyXML := - - - - +Defaults.itSettings -mergeStrategy in assembly <<= (mergeStrategy in assembly) { - (old) => { - case "about.html" => MergeStrategy.discard - case x => old(x) - } -} +scalacOptions += "-language:postfixOps" + +lazy val `it-config-sbt-project` = project.in(file(".")).configs(IntegrationTest) -net.virtualvoid.sbt.graph.Plugin.graphSettings +libraryDependencies ++= Seq( + "com.github.finagle" %% "finch-core" % "0.9.3", + "com.github.finagle" %% "finch-argonaut" % "0.9.3", + "io.argonaut" %% "argonaut" % "6.1", + "com.github.finagle" %% "finch-test" % "0.9.3" % "test", + "org.scalacheck" %% "scalacheck" % "1.12.5" % "test", + "org.scalatest" %% "scalatest" % "2.2.5" % "test" +) + +assemblyMergeStrategy in assembly := { + case "application.conf" => MergeStrategy.concat + case "about.html" => MergeStrategy.discard + case x => + val oldStrategy = (assemblyMergeStrategy in assembly).value + oldStrategy(x) +} diff --git a/modules/swagger-codegen/src/main/resources/finch/endpoint.mustache b/modules/swagger-codegen/src/main/resources/finch/endpoint.mustache index 7e9bb1f628e..8f258ea2043 100644 --- a/modules/swagger-codegen/src/main/resources/finch/endpoint.mustache +++ b/modules/swagger-codegen/src/main/resources/finch/endpoint.mustache @@ -1,5 +1,3 @@ -{{>licenseInfo}} - package {{packageName}} import _root_.argonaut._, Argonaut._ @@ -7,6 +5,7 @@ import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.http.exp.Multipart.FileUpload import com.twitter.util.Future +import argonaut.Argonaut._ import io.finch._, items._ import io.finch.argonaut._ @@ -37,38 +36,21 @@ object endpoint { ) } - - -{{#apiInfo}} -{{#apis}} - /** - * Private method that compiles all service endpoints. - * @return Bundled compilation of all service endpoints. - */ - private def pets(db: PetstoreDb) = - {{#operations}} - {{#operation}} - {{{operationId}}}(db){{^-last}} :+:{{/-last}} - {{/operation}} - - {{#operation}} /** - * {{{description}}} - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def {{operationId}}(db: PetstoreDb): Endpoint[] = - post( {{{vendorExtensions.x-scala-path}}} {{#allParams}}{{^isPathParam}}{{{dataType}}}{{^-last}} ? {{/-last}}{{/isPathParam}}{{/allParams}}) { {{#hasParams}}({{#allParams}}{{paramName}}: {{{dataType}}}{{^-last}}, {{/-last}}{{/allParams}}) => {{/hasParams}} - {{#returnType}} - Ok(db.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}})) - {{/returnType}} - {{^returnType}} - NoContent(db.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}})) - {{/returnType}} - } - - {{/operation}} - {{/operations}} - -{{/apis}} -{{/apiInfo}} - + * Compiles together all the endpoints relating to public service methods. + * + * @return A service that contains all provided endpoints of the API. + */ + def makeService(da: DataAccessor): Service[Request, Response] = ( + {{#apiInfo}} + {{#apis}} + {{classname}}.endpoints(da) {{^-last}} :+:{{/-last}} + {{/apis}} + {{/apiInfo}} + ).handle({ + case e: PetstoreError => NotFound(e) + }).toService + + + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/errors.mustache b/modules/swagger-codegen/src/main/resources/finch/errors.mustache index a20d8db55cd..eb90b48052a 100644 --- a/modules/swagger-codegen/src/main/resources/finch/errors.mustache +++ b/modules/swagger-codegen/src/main/resources/finch/errors.mustache @@ -1,13 +1,9 @@ -{{>licenseInfo}} - package {{packageName}} -package io.finch.petstore - /** * The parent error from which most PetstoreAPI errors extend. Thrown whenever something in the api goes wrong. */ -sealed abstract class PetstoreError(msg: String) extends Exception(msg) { +abstract class PetstoreError(msg: String) extends Exception(msg) { def message: String } diff --git a/modules/swagger-codegen/src/main/resources/finch/model.mustache b/modules/swagger-codegen/src/main/resources/finch/model.mustache index fb02ef09586..ec5d160c5b6 100644 --- a/modules/swagger-codegen/src/main/resources/finch/model.mustache +++ b/modules/swagger-codegen/src/main/resources/finch/model.mustache @@ -1,5 +1,3 @@ -{{>licenseInfo}} - package {{packageName}} import argonaut.Argonaut._ @@ -22,7 +20,7 @@ object {{classname}} { /** * Creates the codec for converting {{classname}} from and to JSON. */ - implicit val {{classname}}Codec: CodecJson[{{classname}}] = casecodec2({{classname}}.apply, {{classname}}.unapply)({{#vars}}"{{baseName}}"{{^-last}}, {{/-last}}{{/vars}}) + implicit val {{classname}}Codec: CodecJson[{{classname}}] = casecodec{{#vendorExtensions.x-varcount}}{{vendorExtensions.x-varcount}}{{/vendorExtensions.x-varcount}}({{classname}}.apply, {{classname}}.unapply)({{#vars}}"{{baseName}}"{{^-last}}, {{/-last}}{{/vars}}) } {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/finch/project/build.properties b/modules/swagger-codegen/src/main/resources/finch/project/build.properties index be6c454fbac..27e88aa115a 100644 --- a/modules/swagger-codegen/src/main/resources/finch/project/build.properties +++ b/modules/swagger-codegen/src/main/resources/finch/project/build.properties @@ -1 +1 @@ -sbt.version=0.13.5 +sbt.version=0.13.13 diff --git a/modules/swagger-codegen/src/main/resources/finch/project/plugins.sbt b/modules/swagger-codegen/src/main/resources/finch/project/plugins.sbt index 7358abbbbc6..1dd4b06fc4d 100644 --- a/modules/swagger-codegen/src/main/resources/finch/project/plugins.sbt +++ b/modules/swagger-codegen/src/main/resources/finch/project/plugins.sbt @@ -1,9 +1,7 @@ -addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.1") +resolvers += Resolver.typesafeRepo("releases") -addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "0.7.5") +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.3") -addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.9.0") +addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.1.4") -addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.3.0") - -addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.7.4") +addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.6.0") diff --git a/modules/swagger-codegen/src/main/resources/finch/web.xml b/modules/swagger-codegen/src/main/resources/finch/web.xml deleted file mode 100644 index 2a08440458e..00000000000 --- a/modules/swagger-codegen/src/main/resources/finch/web.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - org.scalatra.servlet.ScalatraListener - - - - default - /*.html - /css/* - /js/*.js - /images/* - - diff --git a/samples/server/petstore/finch/build.sbt b/samples/server/petstore/finch/build.sbt index 00575312d85..016f1ef3218 100644 --- a/samples/server/petstore/finch/build.sbt +++ b/samples/server/petstore/finch/build.sbt @@ -1,46 +1,16 @@ -import AssemblyKeys._ // put this at the top of the file - -import NativePackagerKeys._ - -packageArchetype.java_server - -assemblySettings - scalariformSettings organization := "io.swagger" -seq(webSettings :_*) - -mainClass in assembly := Some("JettyMain") - -name := "scalatra-sample" +name := "finch-sample" version := "0.1.0-SNAPSHOT" -scalaVersion := "2.11.2" +scalaVersion := "2.11.8" -scalacOptions += "-language:postfixOps" +resolvers += Resolver.sonatypeRepo("snapshots") -libraryDependencies ++= Seq( - "org.scalatest" %% "scalatest" % "2.2.1" % "test", - "org.scalatra" %% "scalatra" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-json" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3", - "org.json4s" %% "json4s-jackson" % "3.2.10", - "org.json4s" %% "json4s-ext" % "3.2.10", - "commons-codec" % "commons-codec" % "1.7", - "net.databinder.dispatch" %% "dispatch-core" % "0.11.2", - //"net.databinder.dispatch" %% "json4s-jackson" % "0.11.2", - "net.databinder.dispatch" %% "dispatch-json4s-jackson" % "0.11.2", - "com.typesafe.akka" %% "akka-actor" % "2.3.6", - "org.eclipse.jetty" % "jetty-server" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty" % "jetty-webapp" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar")) -) +resolvers += "TM" at "http://maven.twttr.com" resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository" @@ -48,17 +18,25 @@ resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/reposi resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/" -ivyXML := - - - - +Defaults.itSettings -mergeStrategy in assembly <<= (mergeStrategy in assembly) { - (old) => { - case "about.html" => MergeStrategy.discard - case x => old(x) - } -} +scalacOptions += "-language:postfixOps" + +lazy val `it-config-sbt-project` = project.in(file(".")).configs(IntegrationTest) -net.virtualvoid.sbt.graph.Plugin.graphSettings +libraryDependencies ++= Seq( + "com.github.finagle" %% "finch-core" % "0.9.3", + "com.github.finagle" %% "finch-argonaut" % "0.9.3", + "io.argonaut" %% "argonaut" % "6.1", + "com.github.finagle" %% "finch-test" % "0.9.3" % "test", + "org.scalacheck" %% "scalacheck" % "1.12.5" % "test", + "org.scalatest" %% "scalatest" % "2.2.5" % "test" +) + +assemblyMergeStrategy in assembly := { + case "application.conf" => MergeStrategy.concat + case "about.html" => MergeStrategy.discard + case x => + val oldStrategy = (assemblyMergeStrategy in assembly).value + oldStrategy(x) +} diff --git a/samples/server/petstore/finch/project/build.properties b/samples/server/petstore/finch/project/build.properties index be6c454fbac..27e88aa115a 100644 --- a/samples/server/petstore/finch/project/build.properties +++ b/samples/server/petstore/finch/project/build.properties @@ -1 +1 @@ -sbt.version=0.13.5 +sbt.version=0.13.13 diff --git a/samples/server/petstore/finch/project/plugins.sbt b/samples/server/petstore/finch/project/plugins.sbt index 7358abbbbc6..1dd4b06fc4d 100644 --- a/samples/server/petstore/finch/project/plugins.sbt +++ b/samples/server/petstore/finch/project/plugins.sbt @@ -1,9 +1,7 @@ -addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.1") +resolvers += Resolver.typesafeRepo("releases") -addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "0.7.5") +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.3") -addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "0.9.0") +addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.1.4") -addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.3.0") - -addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.7.4") +addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.6.0") diff --git a/samples/server/petstore/finch/src/main/scala/ApiResponse.scala b/samples/server/petstore/finch/src/main/scala/ApiResponse.scala index cecbb92e4a8..eec55a82923 100644 --- a/samples/server/petstore/finch/src/main/scala/ApiResponse.scala +++ b/samples/server/petstore/finch/src/main/scala/ApiResponse.scala @@ -1,45 +1,22 @@ -/** - * 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. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package io.swagger.petstore import argonaut.Argonaut._ import argonaut.CodecJson /** - * - * @param code - * @param _type - * @param message + * Describes the result of uploading an image resource + * @param code + * @param _type + * @param message */ case class ApiResponse(code: Option[Int], - _type: Option[String], - message: Option[String]) + _type: Option[String], + message: Option[String] + ) object ApiResponse { /** * Creates the codec for converting ApiResponse from and to JSON. */ - implicit val ApiResponseCodec: CodecJson[ApiResponse] = casecodec2(ApiResponse.apply, ApiResponse.unapply)("code", "type", "message") + implicit val ApiResponseCodec: CodecJson[ApiResponse] = casecodec3(ApiResponse.apply, ApiResponse.unapply)("code", "type", "message") } diff --git a/samples/server/petstore/finch/src/main/scala/Category.scala b/samples/server/petstore/finch/src/main/scala/Category.scala index 445a2d5726f..4d4111e0b5a 100644 --- a/samples/server/petstore/finch/src/main/scala/Category.scala +++ b/samples/server/petstore/finch/src/main/scala/Category.scala @@ -1,39 +1,16 @@ -/** - * 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. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package io.swagger.petstore import argonaut.Argonaut._ import argonaut.CodecJson /** - * - * @param id - * @param name + * A category for a pet + * @param id + * @param name */ case class Category(id: Option[Long], - name: Option[String]) + name: Option[String] + ) object Category { /** diff --git a/samples/server/petstore/finch/src/main/scala/DataAccessor.scala b/samples/server/petstore/finch/src/main/scala/DataAccessor.scala new file mode 100644 index 00000000000..f6361aba887 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/DataAccessor.scala @@ -0,0 +1,127 @@ +package io.swagger.petstore + +trait DataAccessor { + // TODO: apiInfo -> apis -> operations = ??? + // NOTE: ??? throws a not implemented exception + + /** + * + * @return A Unit + */ + def Pet_addPet(body: Pet): Unit = ??? + + /** + * + * @return A Unit + */ + def Pet_deletePet(petId: Long, apiKey: String): Unit = ??? + + /** + * + * @return A List[Pet] + */ + def Pet_findPetsByStatus(status: List[String]): List[Pet] = ??? + + /** + * + * @return A List[Pet] + */ + def Pet_findPetsByTags(tags: List[String]): List[Pet] = ??? + + /** + * + * @return A Pet + */ + def Pet_getPetById(petId: Long): Pet = ??? + + /** + * + * @return A Unit + */ + def Pet_updatePet(body: Pet): Unit = ??? + + /** + * + * @return A Unit + */ + def Pet_updatePetWithForm(petId: Long, name: String, status: String): Unit = ??? + + /** + * + * @return A ApiResponse + */ + def Pet_uploadFile(petId: Long, additionalMetadata: String, file: File): ApiResponse = ??? + + /** + * + * @return A Unit + */ + def Store_deleteOrder(orderId: String): Unit = ??? + + /** + * + * @return A Map[String, Int] + */ + def Store_getInventory(): Map[String, Int] = ??? + + /** + * + * @return A Order + */ + def Store_getOrderById(orderId: Long): Order = ??? + + /** + * + * @return A Order + */ + def Store_placeOrder(body: Order): Order = ??? + + /** + * + * @return A Unit + */ + def User_createUser(body: User): Unit = ??? + + /** + * + * @return A Unit + */ + def User_createUsersWithArrayInput(body: List[User]): Unit = ??? + + /** + * + * @return A Unit + */ + def User_createUsersWithListInput(body: List[User]): Unit = ??? + + /** + * + * @return A Unit + */ + def User_deleteUser(username: String): Unit = ??? + + /** + * + * @return A User + */ + def User_getUserByName(username: String): User = ??? + + /** + * + * @return A String + */ + def User_loginUser(username: String, password: String): String = ??? + + /** + * + * @return A Unit + */ + def User_logoutUser(): Unit = ??? + + /** + * + * @return A Unit + */ + def User_updateUser(username: String, body: User): Unit = ??? + +} \ No newline at end of file diff --git a/samples/server/petstore/finch/src/main/scala/Order.scala b/samples/server/petstore/finch/src/main/scala/Order.scala index ccc2b93154f..7981711b858 100644 --- a/samples/server/petstore/finch/src/main/scala/Order.scala +++ b/samples/server/petstore/finch/src/main/scala/Order.scala @@ -1,27 +1,3 @@ -/** - * 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. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package io.swagger.petstore import argonaut.Argonaut._ @@ -29,24 +5,25 @@ import argonaut.CodecJson //import java.util.Date /** - * - * @param id - * @param petId - * @param quantity - * @param shipDate + * An order for a pets from the pet store + * @param id + * @param petId + * @param quantity + * @param shipDate * @param status Order Status - * @param complete + * @param complete */ case class Order(id: Option[Long], - petId: Option[Long], - quantity: Option[Int], - shipDate: Option[Date], - status: Option[String], - complete: Option[Boolean]) + petId: Option[Long], + quantity: Option[Int], + shipDate: Option[Date], + status: Option[String], + complete: Option[Boolean] + ) object Order { /** * Creates the codec for converting Order from and to JSON. */ - implicit val OrderCodec: CodecJson[Order] = casecodec2(Order.apply, Order.unapply)("id", "petId", "quantity", "shipDate", "status", "complete") + implicit val OrderCodec: CodecJson[Order] = casecodec6(Order.apply, Order.unapply)("id", "petId", "quantity", "shipDate", "status", "complete") } diff --git a/samples/server/petstore/finch/src/main/scala/Pet.scala b/samples/server/petstore/finch/src/main/scala/Pet.scala index d185b58d5b0..9984e84f16e 100644 --- a/samples/server/petstore/finch/src/main/scala/Pet.scala +++ b/samples/server/petstore/finch/src/main/scala/Pet.scala @@ -1,27 +1,3 @@ -/** - * 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. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package io.swagger.petstore import argonaut.Argonaut._ @@ -30,24 +6,25 @@ import argonaut.CodecJson //import Tag /** - * - * @param id - * @param category - * @param name - * @param photoUrls - * @param tags + * A pet for sale in the pet store + * @param id + * @param category + * @param name + * @param photoUrls + * @param tags * @param status pet status in the store */ case class Pet(id: Option[Long], - category: Option[Category], - name: String, - photoUrls: List[String], - tags: Option[List[Tag]], - status: Option[String]) + category: Option[Category], + name: String, + photoUrls: List[String], + tags: Option[List[Tag]], + status: Option[String] + ) object Pet { /** * Creates the codec for converting Pet from and to JSON. */ - implicit val PetCodec: CodecJson[Pet] = casecodec2(Pet.apply, Pet.unapply)("id", "category", "name", "photoUrls", "tags", "status") + implicit val PetCodec: CodecJson[Pet] = casecodec6(Pet.apply, Pet.unapply)("id", "category", "name", "photoUrls", "tags", "status") } diff --git a/samples/server/petstore/finch/src/main/scala/PetApi.scala b/samples/server/petstore/finch/src/main/scala/PetApi.scala index 2ec0b80e33b..cfb8ee3616c 100644 --- a/samples/server/petstore/finch/src/main/scala/PetApi.scala +++ b/samples/server/petstore/finch/src/main/scala/PetApi.scala @@ -1,183 +1,104 @@ -/** - * 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. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package io.swagger.petstore //import Pet -//import ApiResponse -//import java.io.File //import java.io.File +//import ApiResponse -import org.scalatra.{ TypedParamSupport, ScalatraServlet } -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 scala.collection.JavaConverters._ - -class PetApi(implicit val swagger: Swagger) extends ScalatraServlet - with FileUploadSupport - with JacksonJsonSupport - with SwaggerSupport { - protected implicit val jsonFormats: Formats = DefaultFormats - - protected val applicationDescription: String = "PetApi" - override protected val applicationName: Option[String] = Some("/v2/Pet") - - before() { - 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("")) - ) - - 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) - ) - - 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("")) - ) - - 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() - - println("status: " + status) - } - - val findPetsByTagsOperation = (apiOperation[List[Pet]]("findPetsByTags") - 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 ("csv".equals("default")) { - tagsString match { - case Some(str) => str.split(",") - case None => List() - } - } else - List() - - println("tags: " + tags) - } - - val getPetByIdOperation = (apiOperation[Pet]("getPetById") - 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) - } - - val updatePetOperation = (apiOperation[Unit]("updatePet") - summary "Update an existing pet" - parameters (bodyParam[Pet]("body").description("")) - ) - - 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) - ) - - 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) - } - - val uploadFileOperation = (apiOperation[ApiResponse]("uploadFile") - 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) - val file = fileParams("file") - println("file: " + file) - } +import _root_.argonaut._, Argonaut._ +import com.twitter.finagle.Service +import com.twitter.finagle.http.{Request, Response} +import com.twitter.finagle.http.exp.Multipart.FileUpload +import com.twitter.util.Future +import argonaut.Argonaut._ +import io.finch._, items._ +import io.finch.argonaut._ +import java.io.File + +object PetApi { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + public def endpoints(da: DataAccessor) = + addPet(da) :+: + deletePet(da) :+: + findPetsByStatus(da) :+: + findPetsByTags(da) :+: + getPetById(da) :+: + updatePet(da) :+: + updatePetWithForm(da) :+: + uploadFile(da) + + /** + * + * @return And endpoint representing a Unit + */ + private def addPet(da: DataAccessor): Endpoint[Unit] = + post( Pet) { (body: Pet) => + NoContent(da.Pet_addPet(body)) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def deletePet(da: DataAccessor): Endpoint[Unit] = + post( String) { (petId: Long, apiKey: String) => + NoContent(da.Pet_deletePet(petId, apiKey)) + } + + /** + * + * @return And endpoint representing a List[Pet] + */ + private def findPetsByStatus(da: DataAccessor): Endpoint[List[Pet]] = + post( List[String]) { (status: List[String]) => + Ok(da.Pet_findPetsByStatus(status)) + } + + /** + * + * @return And endpoint representing a List[Pet] + */ + private def findPetsByTags(da: DataAccessor): Endpoint[List[Pet]] = + post( List[String]) { (tags: List[String]) => + Ok(da.Pet_findPetsByTags(tags)) + } + + /** + * + * @return And endpoint representing a Pet + */ + private def getPetById(da: DataAccessor): Endpoint[Pet] = + post( ) { (petId: Long) => + Ok(da.Pet_getPetById(petId)) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def updatePet(da: DataAccessor): Endpoint[Unit] = + post( Pet) { (body: Pet) => + NoContent(da.Pet_updatePet(body)) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def updatePetWithForm(da: DataAccessor): Endpoint[Unit] = + post( String ? String) { (petId: Long, name: String, status: String) => + NoContent(da.Pet_updatePetWithForm(petId, name, status)) + } + + /** + * + * @return And endpoint representing a ApiResponse + */ + private def uploadFile(da: DataAccessor): Endpoint[ApiResponse] = + post( String ? File) { (petId: Long, additionalMetadata: String, file: File) => + Ok(da.Pet_uploadFile(petId, additionalMetadata, file)) + } } diff --git a/samples/server/petstore/finch/src/main/scala/Server.scala b/samples/server/petstore/finch/src/main/scala/Server.scala new file mode 100644 index 00000000000..d5f8a4c7a33 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/Server.scala @@ -0,0 +1,31 @@ +package io.swagger.petstore + +import com.twitter.finagle.Http +import com.twitter.finagle.util.LoadService +import com.twitter.util.{Await, Future} + + +class Server { + // Loads implementation defined in resources/META-INF/services/io.swagger.petstore.DataAccessor + val db = LoadService[DataAccessor]() match { + case accessor :: _ => accessor + case _ => new DataAccessor { } + } + + val service = endpoint.makeService(db) + + val server = Http.serve(":8080", service) //creates service + + Await.ready(server) + + def close(): Future[Unit] = { + Await.ready(server.close()) + } +} + +/** + * Launches the PetstoreAPI service when the system is ready. + */ +object Server extends Server with App { + Await.ready(server) +} diff --git a/samples/server/petstore/finch/src/main/scala/StoreApi.scala b/samples/server/petstore/finch/src/main/scala/StoreApi.scala index 54fa810844a..56cf25fdb0f 100644 --- a/samples/server/petstore/finch/src/main/scala/StoreApi.scala +++ b/samples/server/petstore/finch/src/main/scala/StoreApi.scala @@ -1,97 +1,62 @@ -/** - * 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. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package io.swagger.petstore //import Order -//import java.io.File - -import org.scalatra.{ TypedParamSupport, ScalatraServlet } -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 scala.collection.JavaConverters._ - -class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet - with FileUploadSupport - with JacksonJsonSupport - with SwaggerSupport { - protected implicit val jsonFormats: Formats = DefaultFormats - - protected val applicationDescription: String = "StoreApi" - override protected val applicationName: Option[String] = Some("/v2/Store") - - before() { - contentType = formats("json") - response.headers += ("Access-Control-Allow-Origin" -> "*") - } - - val deleteOrderOperation = (apiOperation[Unit]("deleteOrder") - 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) - } - - val getInventoryOperation = (apiOperation[Map[String, Int]]("getInventory") - summary "Returns pet inventories by status" - parameters () - ) - - get("/store/inventory", operation(getInventoryOperation)) { - } - - val getOrderByIdOperation = (apiOperation[Order]("getOrderById") - 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) - } - - val placeOrderOperation = (apiOperation[Order]("placeOrder") - summary "Place an order for a pet" - parameters (bodyParam[Order]("body").description("")) - ) - - post("/store/order", operation(placeOrderOperation)) { - - val body = parsedBody.extract[Order] - println("body: " + body) - } +import _root_.argonaut._, Argonaut._ +import com.twitter.finagle.Service +import com.twitter.finagle.http.{Request, Response} +import com.twitter.finagle.http.exp.Multipart.FileUpload +import com.twitter.util.Future +import argonaut.Argonaut._ +import io.finch._, items._ +import io.finch.argonaut._ +import java.io.File + +object StoreApi { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + public def endpoints(da: DataAccessor) = + deleteOrder(da) :+: + getInventory(da) :+: + getOrderById(da) :+: + placeOrder(da) + + /** + * + * @return And endpoint representing a Unit + */ + private def deleteOrder(da: DataAccessor): Endpoint[Unit] = + post( ) { (orderId: String) => + NoContent(da.Store_deleteOrder(orderId)) + } + + /** + * + * @return And endpoint representing a Map[String, Int] + */ + private def getInventory(da: DataAccessor): Endpoint[Map[String, Int]] = + post( ) { + Ok(da.Store_getInventory()) + } + + /** + * + * @return And endpoint representing a Order + */ + private def getOrderById(da: DataAccessor): Endpoint[Order] = + post( ) { (orderId: Long) => + Ok(da.Store_getOrderById(orderId)) + } + + /** + * + * @return And endpoint representing a Order + */ + private def placeOrder(da: DataAccessor): Endpoint[Order] = + post( Order) { (body: Order) => + Ok(da.Store_placeOrder(body)) + } } diff --git a/samples/server/petstore/finch/src/main/scala/Tag.scala b/samples/server/petstore/finch/src/main/scala/Tag.scala index 5e15880de8b..b2a35e511ef 100644 --- a/samples/server/petstore/finch/src/main/scala/Tag.scala +++ b/samples/server/petstore/finch/src/main/scala/Tag.scala @@ -1,39 +1,16 @@ -/** - * 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. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package io.swagger.petstore import argonaut.Argonaut._ import argonaut.CodecJson /** - * - * @param id - * @param name + * A tag for a pet + * @param id + * @param name */ case class Tag(id: Option[Long], - name: Option[String]) + name: Option[String] + ) object Tag { /** diff --git a/samples/server/petstore/finch/src/main/scala/User.scala b/samples/server/petstore/finch/src/main/scala/User.scala index 526ef2608a4..351bc5b9a37 100644 --- a/samples/server/petstore/finch/src/main/scala/User.scala +++ b/samples/server/petstore/finch/src/main/scala/User.scala @@ -1,55 +1,32 @@ -/** - * 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. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package io.swagger.petstore import argonaut.Argonaut._ import argonaut.CodecJson /** - * - * @param id - * @param username - * @param firstName - * @param lastName - * @param email - * @param password - * @param phone + * A User who is purchasing from the pet store + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone * @param userStatus User Status */ 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]) + username: Option[String], + firstName: Option[String], + lastName: Option[String], + email: Option[String], + password: Option[String], + phone: Option[String], + userStatus: Option[Int] + ) object User { /** * Creates the codec for converting User from and to JSON. */ - implicit val UserCodec: CodecJson[User] = casecodec2(User.apply, User.unapply)("id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus") + implicit val UserCodec: CodecJson[User] = casecodec8(User.apply, User.unapply)("id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus") } diff --git a/samples/server/petstore/finch/src/main/scala/UserApi.scala b/samples/server/petstore/finch/src/main/scala/UserApi.scala index 446d689f2b8..4dfe5ab8b5b 100644 --- a/samples/server/petstore/finch/src/main/scala/UserApi.scala +++ b/samples/server/petstore/finch/src/main/scala/UserApi.scala @@ -1,153 +1,102 @@ -/** - * 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. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package io.swagger.petstore //import User -//import java.io.File - -import org.scalatra.{ TypedParamSupport, ScalatraServlet } -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 scala.collection.JavaConverters._ - -class UserApi(implicit val swagger: Swagger) extends ScalatraServlet - with FileUploadSupport - with JacksonJsonSupport - with SwaggerSupport { - protected implicit val jsonFormats: Formats = DefaultFormats - - protected val applicationDescription: String = "UserApi" - override protected val applicationName: Option[String] = Some("/v2/User") - - before() { - contentType = formats("json") - response.headers += ("Access-Control-Allow-Origin" -> "*") - } - - val createUserOperation = (apiOperation[Unit]("createUser") - summary "Create user" - parameters (bodyParam[User]("body").description("")) - ) - - 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("")) - ) - - 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("")) - ) - - 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("")) - ) - - 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("")) - ) - - 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("")) - ) - - get("/user/login", operation(loginUserOperation)) { - - val username = params.getAs[String]("username") - - println("username: " + username) - - val password = params.getAs[String]("password") - - println("password: " + password) - } - - val logoutUserOperation = (apiOperation[Unit]("logoutUser") - summary "Logs out current logged in user session" - parameters () - ) - - get("/user/logout", operation(logoutUserOperation)) { - } - - val updateUserOperation = (apiOperation[Unit]("updateUser") - summary "Updated user" - parameters (pathParam[String]("username").description(""), bodyParam[User]("body").description("")) - ) - - put("/user/{username}", operation(updateUserOperation)) { - - val username = params.getOrElse("username", halt(400)) - - println("username: " + username) - - val body = parsedBody.extract[User] - println("body: " + body) - } +import _root_.argonaut._, Argonaut._ +import com.twitter.finagle.Service +import com.twitter.finagle.http.{Request, Response} +import com.twitter.finagle.http.exp.Multipart.FileUpload +import com.twitter.util.Future +import argonaut.Argonaut._ +import io.finch._, items._ +import io.finch.argonaut._ +import java.io.File + +object UserApi { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + public def endpoints(da: DataAccessor) = + createUser(da) :+: + createUsersWithArrayInput(da) :+: + createUsersWithListInput(da) :+: + deleteUser(da) :+: + getUserByName(da) :+: + loginUser(da) :+: + logoutUser(da) :+: + updateUser(da) + + /** + * + * @return And endpoint representing a Unit + */ + private def createUser(da: DataAccessor): Endpoint[Unit] = + post( User) { (body: User) => + NoContent(da.User_createUser(body)) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def createUsersWithArrayInput(da: DataAccessor): Endpoint[Unit] = + post( List[User]) { (body: List[User]) => + NoContent(da.User_createUsersWithArrayInput(body)) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def createUsersWithListInput(da: DataAccessor): Endpoint[Unit] = + post( List[User]) { (body: List[User]) => + NoContent(da.User_createUsersWithListInput(body)) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def deleteUser(da: DataAccessor): Endpoint[Unit] = + post( ) { (username: String) => + NoContent(da.User_deleteUser(username)) + } + + /** + * + * @return And endpoint representing a User + */ + private def getUserByName(da: DataAccessor): Endpoint[User] = + post( ) { (username: String) => + Ok(da.User_getUserByName(username)) + } + + /** + * + * @return And endpoint representing a String + */ + private def loginUser(da: DataAccessor): Endpoint[String] = + post( String ? String) { (username: String, password: String) => + Ok(da.User_loginUser(username, password)) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def logoutUser(da: DataAccessor): Endpoint[Unit] = + post( ) { + NoContent(da.User_logoutUser()) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def updateUser(da: DataAccessor): Endpoint[Unit] = + post( User) { (username: String, body: User) => + NoContent(da.User_updateUser(username, body)) + } } diff --git a/samples/server/petstore/finch/src/main/scala/endpoint.scala b/samples/server/petstore/finch/src/main/scala/endpoint.scala index 72f0ffdfdc4..f0fdcbff787 100644 --- a/samples/server/petstore/finch/src/main/scala/endpoint.scala +++ b/samples/server/petstore/finch/src/main/scala/endpoint.scala @@ -1,27 +1,3 @@ -/** - * 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. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package io.swagger.petstore import _root_.argonaut._, Argonaut._ @@ -29,6 +5,7 @@ import com.twitter.finagle.Service import com.twitter.finagle.http.{Request, Response} import com.twitter.finagle.http.exp.Multipart.FileUpload import com.twitter.util.Future +import argonaut.Argonaut._ import io.finch._, items._ import io.finch.argonaut._ @@ -59,227 +36,19 @@ object endpoint { ) } - - - /** - * Private method that compiles all service endpoints. - * @return Bundled compilation of all service endpoints. - */ - private def pets(db: PetstoreDb) = - addPet(db) :+: - deletePet(db) :+: - findPetsByStatus(db) :+: - findPetsByTags(db) :+: - getPetById(db) :+: - updatePet(db) :+: - updatePetWithForm(db) :+: - uploadFile(db) - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def addPet(db: PetstoreDb): Endpoint[] = - post( Pet) { (body: Pet) => - NoContent(db.addPet(body)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def deletePet(db: PetstoreDb): Endpoint[] = - post( String) { (petId: Long, apiKey: String) => - NoContent(db.deletePet(petId, apiKey)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def findPetsByStatus(db: PetstoreDb): Endpoint[] = - post( List[String]) { (status: List[String]) => - Ok(db.findPetsByStatus(status)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def findPetsByTags(db: PetstoreDb): Endpoint[] = - post( List[String]) { (tags: List[String]) => - Ok(db.findPetsByTags(tags)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def getPetById(db: PetstoreDb): Endpoint[] = - post( ) { (petId: Long) => - Ok(db.getPetById(petId)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def updatePet(db: PetstoreDb): Endpoint[] = - post( Pet) { (body: Pet) => - NoContent(db.updatePet(body)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def updatePetWithForm(db: PetstoreDb): Endpoint[] = - post( String ? String) { (petId: Long, name: String, status: String) => - NoContent(db.updatePetWithForm(petId, name, status)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def uploadFile(db: PetstoreDb): Endpoint[] = - post( String ? File) { (petId: Long, additionalMetadata: String, file: File) => - Ok(db.uploadFile(petId, additionalMetadata, file)) - } - - - /** - * Private method that compiles all service endpoints. - * @return Bundled compilation of all service endpoints. - */ - private def pets(db: PetstoreDb) = - deleteOrder(db) :+: - getInventory(db) :+: - getOrderById(db) :+: - placeOrder(db) - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def deleteOrder(db: PetstoreDb): Endpoint[] = - post( ) { (orderId: String) => - NoContent(db.deleteOrder(orderId)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def getInventory(db: PetstoreDb): Endpoint[] = - post( ) { - Ok(db.getInventory()) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def getOrderById(db: PetstoreDb): Endpoint[] = - post( ) { (orderId: Long) => - Ok(db.getOrderById(orderId)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def placeOrder(db: PetstoreDb): Endpoint[] = - post( Order) { (body: Order) => - Ok(db.placeOrder(body)) - } - - - /** - * Private method that compiles all service endpoints. - * @return Bundled compilation of all service endpoints. - */ - private def pets(db: PetstoreDb) = - createUser(db) :+: - createUsersWithArrayInput(db) :+: - createUsersWithListInput(db) :+: - deleteUser(db) :+: - getUserByName(db) :+: - loginUser(db) :+: - logoutUser(db) :+: - updateUser(db) - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def createUser(db: PetstoreDb): Endpoint[] = - post( User) { (body: User) => - NoContent(db.createUser(body)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def createUsersWithArrayInput(db: PetstoreDb): Endpoint[] = - post( List[User]) { (body: List[User]) => - NoContent(db.createUsersWithArrayInput(body)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def createUsersWithListInput(db: PetstoreDb): Endpoint[] = - post( List[User]) { (body: List[User]) => - NoContent(db.createUsersWithListInput(body)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def deleteUser(db: PetstoreDb): Endpoint[] = - post( ) { (username: String) => - NoContent(db.deleteUser(username)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def getUserByName(db: PetstoreDb): Endpoint[] = - post( ) { (username: String) => - Ok(db.getUserByName(username)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def loginUser(db: PetstoreDb): Endpoint[] = - post( String ? String) { (username: String, password: String) => - Ok(db.loginUser(username, password)) - } - - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def logoutUser(db: PetstoreDb): Endpoint[] = - post( ) { - NoContent(db.logoutUser()) - } - /** - * - * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. - */ - def updateUser(db: PetstoreDb): Endpoint[] = - post( User) { (username: String, body: User) => - NoContent(db.updateUser(username, body)) - } + * Compiles together all the endpoints relating to public service methods. + * + * @return A service that contains all provided endpoints of the API. + */ + def makeService(da: DataAccessor): Service[Request, Response] = ( + PetApi.endpoints(da) :+: + StoreApi.endpoints(da) :+: + UserApi.endpoints(da) + ).handle({ + case e: PetstoreError => NotFound(e) + }).toService +} \ No newline at end of file diff --git a/samples/server/petstore/finch/src/main/scala/errors.scala b/samples/server/petstore/finch/src/main/scala/errors.scala index 9fb65d21617..69e3831c15d 100644 --- a/samples/server/petstore/finch/src/main/scala/errors.scala +++ b/samples/server/petstore/finch/src/main/scala/errors.scala @@ -1,35 +1,9 @@ -/** - * 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. - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - package io.swagger.petstore -package io.finch.petstore - /** * The parent error from which most PetstoreAPI errors extend. Thrown whenever something in the api goes wrong. */ -sealed abstract class PetstoreError(msg: String) extends Exception(msg) { +abstract class PetstoreError(msg: String) extends Exception(msg) { def message: String } diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/ApiResponse.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/ApiResponse.scala new file mode 100644 index 00000000000..cecbb92e4a8 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/ApiResponse.scala @@ -0,0 +1,45 @@ +/** + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.petstore + +import argonaut.Argonaut._ +import argonaut.CodecJson + +/** + * + * @param code + * @param _type + * @param message + */ +case class ApiResponse(code: Option[Int], + _type: Option[String], + message: Option[String]) + +object ApiResponse { + /** + * Creates the codec for converting ApiResponse from and to JSON. + */ + implicit val ApiResponseCodec: CodecJson[ApiResponse] = casecodec2(ApiResponse.apply, ApiResponse.unapply)("code", "type", "message") +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Category.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Category.scala new file mode 100644 index 00000000000..445a2d5726f --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Category.scala @@ -0,0 +1,43 @@ +/** + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.petstore + +import argonaut.Argonaut._ +import argonaut.CodecJson + +/** + * + * @param id + * @param name + */ +case class Category(id: Option[Long], + name: Option[String]) + +object Category { + /** + * Creates the codec for converting Category from and to JSON. + */ + implicit val CategoryCodec: CodecJson[Category] = casecodec2(Category.apply, Category.unapply)("id", "name") +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Order.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Order.scala new file mode 100644 index 00000000000..ff27fd593c6 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Order.scala @@ -0,0 +1,53 @@ +/** + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.petstore + +import java.util.Date + +import argonaut.Argonaut._ +import argonaut.CodecJson + +/** + * + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ +case class Order(id: Option[Long], + petId: Option[Long], + quantity: Option[Int], + shipDate: Option[Date], + status: Option[String], + complete: Option[Boolean]) + +object Order { + /** + * Creates the codec for converting Order from and to JSON. + */ + implicit val OrderCodec: CodecJson[Order] = casecodec6(Order.apply, Order.unapply)("id", "petId", "quantity", "shipDate", "status", "complete") +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Pet.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Pet.scala new file mode 100644 index 00000000000..ed06cd479b9 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Pet.scala @@ -0,0 +1,53 @@ +/** + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.petstore + +import argonaut.Argonaut._ +import argonaut.CodecJson +//import Category +//import Tag + +/** + * + * @param id + * @param category + * @param name + * @param photoUrls + * @param tags + * @param status pet status in the store + */ +case class Pet(id: Option[Long], + category: Option[Category], + name: String, + photoUrls: List[String], + tags: Option[List[Tag]], + status: Option[String]) + +object Pet { + /** + * Creates the codec for converting Pet from and to JSON. + */ + implicit val PetCodec: CodecJson[Pet] = casecodec6(Pet.apply, Pet.unapply)("id", "category", "name", "photoUrls", "tags", "status") +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/PetApi.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/PetApi.scala new file mode 100644 index 00000000000..992c9a9c70f --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/PetApi.scala @@ -0,0 +1,174 @@ +/** + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.petstore + +//import Pet +//import ApiResponse +//import java.io.File +//import java.io.File + +class PetApi(implicit val swagger: Swagger) extends ScalatraServlet + with FileUploadSupport + with JacksonJsonSupport + with SwaggerSupport { + protected implicit val jsonFormats: Formats = DefaultFormats + + protected val applicationDescription: String = "PetApi" + override protected val applicationName: Option[String] = Some("/v2/Pet") + + before() { + 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("")) + ) + + 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) + ) + + 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("")) + ) + + 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() + + println("status: " + status) + } + + val findPetsByTagsOperation = (apiOperation[List[Pet]]("findPetsByTags") + 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 ("csv".equals("default")) { + tagsString match { + case Some(str) => str.split(",") + case None => List() + } + } else + List() + + println("tags: " + tags) + } + + val getPetByIdOperation = (apiOperation[Pet]("getPetById") + 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) + } + + val updatePetOperation = (apiOperation[Unit]("updatePet") + summary "Update an existing pet" + parameters (bodyParam[Pet]("body").description("")) + ) + + 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) + ) + + 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) + } + + val uploadFileOperation = (apiOperation[ApiResponse]("uploadFile") + 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) + val file = fileParams("file") + println("file: " + file) + } + +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/PetstoreError.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/PetstoreError.scala new file mode 100644 index 00000000000..bc427e5c294 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/PetstoreError.scala @@ -0,0 +1,8 @@ +package io.swagger.petstore + +/** + * The parent error from which most PetstoreAPI errors extend. Thrown whenever something in the api goes wrong. + */ +abstract class PetstoreError(msg: String) extends Exception(msg) { + def message: String +} diff --git a/modules/swagger-codegen/src/main/resources/finch/service.mustache b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Service.scala similarity index 59% rename from modules/swagger-codegen/src/main/resources/finch/service.mustache rename to samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Service.scala index 1642a736753..b8964842590 100644 --- a/modules/swagger-codegen/src/main/resources/finch/service.mustache +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Service.scala @@ -1,16 +1,16 @@ -{{>licenseInfo}} - -package {{packageName}} +package io.swagger.petstore import com.twitter.finagle.Http import com.twitter.util.{Await, Future} -{{#imports}}import {{import}} -{{/imports}} +class PetstoreDb { -class PetstoreApp { +} +/** + * Created by jim on 11/6/16. + */ +class Server { val db = new PetstoreDb() - val service = endpoint.makeService(db) val server = Http.serve(":8080", service) //creates service @@ -20,11 +20,9 @@ class PetstoreApp { def close(): Future[Unit] = { Await.ready(server.close()) } + } -/** - * Launches the PetstoreAPI service when the system is ready. - */ -object PetstoreApp extends PetstoreApp with App { +object Server extends Server with App { Await.ready(server) -} +} \ No newline at end of file diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/StoreApi.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/StoreApi.scala new file mode 100644 index 00000000000..810f8194ac6 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/StoreApi.scala @@ -0,0 +1,88 @@ +/** + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.petstore + +//import Order +//import java.io.File + +class StoreApi(implicit val swagger: Swagger) extends ScalatraServlet + with FileUploadSupport + with JacksonJsonSupport + with SwaggerSupport { + protected implicit val jsonFormats: Formats = DefaultFormats + + protected val applicationDescription: String = "StoreApi" + override protected val applicationName: Option[String] = Some("/v2/Store") + + before() { + contentType = formats("json") + response.headers += ("Access-Control-Allow-Origin" -> "*") + } + + val deleteOrderOperation = (apiOperation[Unit]("deleteOrder") + 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) + } + + val getInventoryOperation = (apiOperation[Map[String, Int]]("getInventory") + summary "Returns pet inventories by status" + parameters () + ) + + get("/store/inventory", operation(getInventoryOperation)) { + } + + val getOrderByIdOperation = (apiOperation[Order]("getOrderById") + 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) + } + + val placeOrderOperation = (apiOperation[Order]("placeOrder") + summary "Place an order for a pet" + parameters (bodyParam[Order]("body").description("")) + ) + + post("/store/order", operation(placeOrderOperation)) { + + val body = parsedBody.extract[Order] + + println("body: " + body) + } + +} diff --git a/modules/swagger-codegen/src/main/resources/finch/licenseInfo.mustache b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Tag.scala similarity index 50% rename from modules/swagger-codegen/src/main/resources/finch/licenseInfo.mustache rename to samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Tag.scala index 2ed71d3a875..5e15880de8b 100644 --- a/modules/swagger-codegen/src/main/resources/finch/licenseInfo.mustache +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/Tag.scala @@ -1,9 +1,9 @@ /** - * {{{appName}}} - * {{{appDescription}}} + * 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. * - * {{#version}}OpenAPI spec version: {{{version}}}{{/version}} - * {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git @@ -20,4 +20,24 @@ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. - */ \ No newline at end of file + */ + +package io.swagger.petstore + +import argonaut.Argonaut._ +import argonaut.CodecJson + +/** + * + * @param id + * @param name + */ +case class Tag(id: Option[Long], + name: Option[String]) + +object Tag { + /** + * Creates the codec for converting Tag from and to JSON. + */ + implicit val TagCodec: CodecJson[Tag] = casecodec2(Tag.apply, Tag.unapply)("id", "name") +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/User.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/User.scala new file mode 100644 index 00000000000..c6f59f9470c --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/User.scala @@ -0,0 +1,55 @@ +/** + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.petstore + +import argonaut.Argonaut._ +import argonaut.CodecJson + +/** + * + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ +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]) + +object User { + /** + * Creates the codec for converting User from and to JSON. + */ + implicit val UserCodec: CodecJson[User] = casecodec8(User.apply, User.unapply)("id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus") +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/UserApi.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/UserApi.scala new file mode 100644 index 00000000000..1c1f25be073 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/UserApi.scala @@ -0,0 +1,144 @@ +/** + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.petstore + +//import User +//import java.io.File + +class UserApi(implicit val swagger: Swagger) extends ScalatraServlet + with FileUploadSupport + with JacksonJsonSupport + with SwaggerSupport { + protected implicit val jsonFormats: Formats = DefaultFormats + + protected val applicationDescription: String = "UserApi" + override protected val applicationName: Option[String] = Some("/v2/User") + + before() { + contentType = formats("json") + response.headers += ("Access-Control-Allow-Origin" -> "*") + } + + val createUserOperation = (apiOperation[Unit]("createUser") + summary "Create user" + parameters (bodyParam[User]("body").description("")) + ) + + 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("")) + ) + + 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("")) + ) + + 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("")) + ) + + 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("")) + ) + + 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("")) + ) + + get("/user/login", operation(loginUserOperation)) { + + val username = params.getAs[String]("username") + + println("username: " + username) + + val password = params.getAs[String]("password") + + println("password: " + password) + } + + val logoutUserOperation = (apiOperation[Unit]("logoutUser") + summary "Logs out current logged in user session" + parameters () + ) + + get("/user/logout", operation(logoutUserOperation)) { + } + + val updateUserOperation = (apiOperation[Unit]("updateUser") + summary "Updated user" + parameters (pathParam[String]("username").description(""), bodyParam[User]("body").description("")) + ) + + put("/user/{username}", operation(updateUserOperation)) { + + val username = params.getOrElse("username", halt(400)) + + println("username: " + username) + + val body = parsedBody.extract[User] + + println("body: " + body) + } + +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/endpoint.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/endpoint.scala new file mode 100644 index 00000000000..3bbad3fe986 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/endpoint.scala @@ -0,0 +1,302 @@ +/** + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.petstore + +import _root_.argonaut._ +import com.twitter.finagle.Service +import com.twitter.finagle.http.{Request, Response} +import com.twitter.finagle.http.exp.Multipart.FileUpload +import com.twitter.util.Future +import argonaut.Argonaut._ +import io.finch._ +import io.finch.items.{BodyItem, ParamItem} +import io.finch.argonaut._ + +/** + * Provides the paths and endpoints for all the API's public service methods. + */ +object endpoint { + + implicit val encodeException: EncodeJson[Exception] = EncodeJson { + case Error.NotPresent(ParamItem(p)) => Json.obj( + "error" -> jString("param_not_present"), "param" -> jString(p) + ) + case Error.NotPresent(BodyItem) => Json.obj( + "error" -> jString("body_not_present") + ) + case Error.NotParsed(ParamItem(p), _, _) => Json.obj( + "error" -> jString("param_not_parsed"), "param" -> jString(p) + ) + case Error.NotParsed(BodyItem, _, _) => Json.obj( + "error" -> jString("body_not_parsed") + ) + case Error.NotValid(ParamItem(p), rule) => Json.obj( + "error" -> jString("param_not_valid"), "param" -> jString(p), "rule" -> jString(rule) + ) + // Domain errors + case error: PetstoreError => Json.obj( + "error" -> jString(error.message) + ) + } + + /** + * Private method that compiles all service endpoints. + * + * @return Bundled compilation of all service endpoints. + */ + private def pets(db: PetstoreDb) = + addPet(db) :+: + deletePet(db) :+: + findPetsByStatus(db) :+: + findPetsByTags(db) :+: + getPetById(db) :+: + updatePet(db) :+: + updatePetWithForm(db) :+: + uploadFile(db) + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def addPet(db: PetstoreDb): Endpoint[] = + post(Pet) { (body: Pet) => + NoContent(db.addPet(body)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def deletePet(db: PetstoreDb): Endpoint[] = + post(String) { (petId: Long, apiKey: String) => + NoContent(db.deletePet(petId, apiKey)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def findPetsByStatus(db: PetstoreDb): Endpoint[] = + post(List[String]) { (status: List[String]) => + Ok(db.findPetsByStatus(status)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def findPetsByTags(db: PetstoreDb): Endpoint[] = + post(List[String]) { (tags: List[String]) => + Ok(db.findPetsByTags(tags)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def getPetById(db: PetstoreDb): Endpoint[] = + post() { (petId: Long) => + Ok(db.getPetById(petId)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def updatePet(db: PetstoreDb): Endpoint[] = + post(Pet) { (body: Pet) => + NoContent(db.updatePet(body)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def updatePetWithForm(db: PetstoreDb): Endpoint[] = + post(String ? String) { (petId: Long, name: String, status: String) => + NoContent(db.updatePetWithForm(petId, name, status)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def uploadFile(db: PetstoreDb): Endpoint[] = + post(String ? File) { (petId: Long, additionalMetadata: String, file: File) => + Ok(db.uploadFile(petId, additionalMetadata, file)) + } + + + /** + * Private method that compiles all service endpoints. + * + * @return Bundled compilation of all service endpoints. + */ + private def pets(db: PetstoreDb) = + deleteOrder(db) :+: + getInventory(db) :+: + getOrderById(db) :+: + placeOrder(db) + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def deleteOrder(db: PetstoreDb): Endpoint[] = + post() { (orderId: String) => + NoContent(db.deleteOrder(orderId)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def getInventory(db: PetstoreDb): Endpoint[] = + post() { + Ok(db.getInventory()) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def getOrderById(db: PetstoreDb): Endpoint[] = + post() { (orderId: Long) => + Ok(db.getOrderById(orderId)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def placeOrder(db: PetstoreDb): Endpoint[] = + post(Order) { (body: Order) => + Ok(db.placeOrder(body)) + } + + + /** + * Private method that compiles all service endpoints. + * + * @return Bundled compilation of all service endpoints. + */ + private def pets(db: PetstoreDb) = + createUser(db) :+: + createUsersWithArrayInput(db) :+: + createUsersWithListInput(db) :+: + deleteUser(db) :+: + getUserByName(db) :+: + loginUser(db) :+: + logoutUser(db) :+: + updateUser(db) + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def createUser(db: PetstoreDb): Endpoint[] = + post(User) { (body: User) => + NoContent(db.createUser(body)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def createUsersWithArrayInput(db: PetstoreDb): Endpoint[] = + post(List[User]) { (body: List[User]) => + NoContent(db.createUsersWithArrayInput(body)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def createUsersWithListInput(db: PetstoreDb): Endpoint[] = + post(List[User]) { (body: List[User]) => + NoContent(db.createUsersWithListInput(body)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def deleteUser(db: PetstoreDb): Endpoint[] = + post() { (username: String) => + NoContent(db.deleteUser(username)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def getUserByName(db: PetstoreDb): Endpoint[] = + post() { (username: String) => + Ok(db.getUserByName(username)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def loginUser(db: PetstoreDb): Endpoint[] = + post(String ? String) { (username: String, password: String) => + Ok(db.loginUser(username, password)) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def logoutUser(db: PetstoreDb): Endpoint[] = + post() { + NoContent(db.logoutUser()) + } + + /** + * + * @return A Router that contains a RequestReader of a sequence of the usernames of the Users added. + */ + def updateUser(db: PetstoreDb): Endpoint[] = + post(User) { (username: String, body: User) => + NoContent(db.updateUser(username, body)) + } + + /** + * Compiles together all the endpoints relating to public service methods. + * + * @return A service that contains all provided endpoints of the API. + */ + def makeService(db: PetstoreDb): Service[Request, Response] = ( + pets(db) :+: + store(db) :+: + users(db) + ).handle({ + case e: PetstoreError => NotFound(e) + }).toService + +} + + diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/errors.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/errors.scala new file mode 100644 index 00000000000..01a57010116 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/errors.scala @@ -0,0 +1,44 @@ +/** + * 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. + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.swagger.petstore + +/** + * Thrown when the object given is invalid + * @param message An error message + */ +case class InvalidInput(message: String) extends PetstoreError(message) + +/** + * Thrown when the given object is missing a unique ID. + * @param message An error message + */ +case class MissingIdentifier(message: String) extends PetstoreError(message) + +/** + * Thrown when the given record does not exist in the database. + * @param message An error message + */ +case class RecordNotFound(message: String) extends PetstoreError(message) + diff --git a/samples/server/petstore/finch/src/main/webapp/WEB-INF/web.xml b/samples/server/petstore/finch/src/main/webapp/WEB-INF/web.xml deleted file mode 100644 index 2a08440458e..00000000000 --- a/samples/server/petstore/finch/src/main/webapp/WEB-INF/web.xml +++ /dev/null @@ -1,17 +0,0 @@ - - - - org.scalatra.servlet.ScalatraListener - - - - default - /*.html - /css/* - /js/*.js - /images/* - -